1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
10 #include <anna/statistics/Engine.hpp>
11 #include <anna/diameter/codec/Engine.hpp>
12 #include <anna/http/Transport.hpp>
13 #include <anna/diameter/stack/Engine.hpp>
14 #include <anna/diameter/helpers/base/functions.hpp>
15 #include <anna/diameter/helpers/dcca/functions.hpp>
16 #include <anna/time/functions.hpp>
17 #include <anna/diameter.comm/ApplicationMessageOamModule.hpp>
20 #include "Launcher.hpp"
23 #define SIGUSR2_TASKS_INPUT_FILENAME "./sigusr2.tasks.input"
24 #define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.tasks.output"
25 #define DIAMETER_CODEC_ENGINE_NAME_PREFIX "MyCodecEngine"
27 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
28 a_myDiameterEngine = new MyDiameterEngine();
29 a_myDiameterEngine->setRealm("ADL.ericsson.com");
30 a_myDiameterEngine->setAutoBind(false); // allow to create client-sessions without binding them, in order to set timeouts.
31 a_logFile = "launcher.log";
32 a_burstLogFile = "launcher.burst";
34 a_detailedLog = false;
37 a_counterRecorder = NULL;
38 a_counterRecorderClock = NULL;
40 a_diameterLocalServer = NULL;
41 a_cerPathfile = "cer.xml";
42 a_dwrPathfile = "dwr.xml";
45 a_burstRepeat = false;
46 a_burstActive = false;
48 a_burstDeliveryIt = a_burstMessages.begin();
50 a_burstPopCounter = 0;
53 anna::diameter::comm::Message *Launcher::createCommMessage() throw(anna::RuntimeException) {
54 return a_commMessages.create();
57 void Launcher::releaseCommMessage(anna::diameter::comm::Message *msg) throw() {
58 a_commMessages.release(msg);
61 anna::diameter::codec::Message *Launcher::createCodecMessage() throw(anna::RuntimeException) {
62 return a_codecMessages.create();
65 void Launcher::releaseCodecMessage(anna::diameter::codec::Message *msg) throw() {
66 a_codecMessages.release(msg);
70 void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) {
72 // <CER> ::= < Diameter Header: 257, REQ >
73 // { Origin-Host } 264 diameterIdentity
74 // { Origin-Realm } 296 idem
75 // 1* { Host-IP-Address } 257, address
76 // { Vendor-Id } 266 Unsigned32
77 // { Product-Name } 269 UTF8String
78 // [Origin-State-Id] 278 Unsigned32
79 // * [ Supported-Vendor-Id ] 265 Unsigned32
80 // * [ Auth-Application-Id ] 258 Unsigned32
81 // * [Acct-Application-Id] 259 Unsigned32
82 anna::diameter::codec::Message diameterCER;
83 int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
84 std::string OH = a_myDiameterEngine->getHost();
85 std::string OR = a_myDiameterEngine->getRealm();
86 std::string hostIP = anna::functions::getHostnameIP(); // Address
87 int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
88 std::string productName = "ANNA Diameter Launcher"; // UTF8String
89 bool loadingError = false;
92 diameterCER.loadXML(a_cerPathfile);
93 } catch(anna::RuntimeException &ex) {
99 LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
100 diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
101 diameterCER.setApplicationId(applicationId);
102 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
103 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
104 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>"
105 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
106 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
107 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
111 // <DWR> ::= < Diameter Header: 280, REQ >
114 anna::diameter::codec::Message diameterDWR;
115 loadingError = false;
118 diameterDWR.loadXML(a_dwrPathfile);
119 } catch(anna::RuntimeException &ex) {
125 LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
126 diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
127 diameterDWR.setApplicationId(applicationId);
128 diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
129 diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
132 //////////////////////////
133 // IDEM FOR CEA AND DWA //
134 //////////////////////////
136 // // <CER> ::= < Diameter Header: 257, REQ >
137 // // { Origin-Host } 264 diameterIdentity
138 // // { Origin-Realm } 296 idem
139 // // 1* { Host-IP-Address } 257, address
140 // // { Vendor-Id } 266 Unsigned32
141 // // { Product-Name } 269 UTF8String
142 // // [Origin-State-Id] 278 Unsigned32
143 // // * [ Supported-Vendor-Id ] 265 Unsigned32
144 // // * [ Auth-Application-Id ] 258 Unsigned32
145 // // * [Acct-Application-Id] 259 Unsigned32
146 // anna::diameter::codec::Message diameterCER;
147 // int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
148 // std::string OH = a_myDiameterEngine->getHost();
149 // std::string OR = a_myDiameterEngine->getRealm();
150 // std::string hostIP = anna::functions::getHostnameIP(); // Address
151 // int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
152 // std::string productName = "ANNA Diameter Launcher"; // UTF8String
153 // bool loadingError = false;
156 // diameterCER.loadXML("cer.xml");
157 // } catch (anna::RuntimeException &ex) {
159 // loadingError = true;
162 // if (loadingError) {
163 // LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
164 // diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
165 // diameterCER.setApplicationId(applicationId);
166 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
167 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
168 // 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>"
169 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
170 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
171 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
175 // // <DWR> ::= < Diameter Header: 280, REQ >
176 // // { Origin-Host }
177 // // { Origin-Realm }
178 // anna::diameter::codec::Message diameterDWR;
179 // loadingError = false;
182 // diameterDWR.loadXML("dwr.xml");
183 // } catch (anna::RuntimeException &ex) {
185 // loadingError = true;
188 // if (loadingError) {
189 // LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
190 // diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
191 // diameterDWR.setApplicationId(applicationId);
192 // diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
193 // diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
195 // Assignment for CER/DWR and CEA/DWA:
196 a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code());
197 //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code());
200 void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw() {
201 // if (!logEnabled()) return;
202 anna::diameter::codec::Message codecMsg;
203 try { codecMsg.decode(db); } catch(anna::RuntimeException &ex) { ex.trace(); }
204 writeLogFile(codecMsg, logExtension, detail);
208 // Si ya lo tengo decodificado:
209 void Launcher::writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw() {
210 // if (!logEnabled()) return;
212 std::string targetFile = a_logFile;
216 targetFile += logExtension;
219 std::ofstream out(targetFile.c_str(), std::ifstream::out | std::ifstream::app);
221 std::string title = "[";
222 title += logExtension;
224 // Build complete log:
225 std::string log = "\n";
226 std::string xml = decodedMessage.asXMLString();
230 anna::time::Date now;
233 title += now.asString();
234 log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline);
237 log += anna::functions::highlight("Used resource");
248 std::string name = anna::functions::asString(decodedMessage.getHopByHop());
250 name += anna::functions::asString(decodedMessage.getEndToEnd());
252 name += anna::functions::asString(decodedMessage.getId().first);
254 name += ((decodedMessage.getId().second) ? "request.":"answer.");
255 name += logExtension;
257 std::ofstream outMsg(name.c_str(), std::ifstream::out | std::ifstream::app);
258 outMsg.write(xml.c_str(), xml.size());
263 out.write(log.c_str(), log.size());
267 void Launcher::writeBurstLogFile(const std::string &buffer) throw() {
268 std::ofstream out(a_burstLogFile.c_str(), std::ifstream::out | std::ifstream::app);
269 out.write(buffer.c_str(), buffer.size());
270 out.close(); // close() will be called when the object is destructed (i.e., when it goes out of scope).
271 // you'd call close() only if you indeed for some reason wanted to close the filestream
272 // earlier than it goes out of scope.
275 void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional) throw(anna::RuntimeException) {
276 CommandLine& cl(anna::CommandLine::instantiate());
278 if(!cl.exists(commandLineParameter) && optional) return; // start error if mandatory
280 std::string parameter = cl.getValue(commandLineParameter);
282 if(anna::functions::isLike("^[0-9]+$", parameter)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
283 int msecs = cl.getIntegerValue(commandLineParameter);
285 if(msecs > a_timeEngine->getMaxTimeout()) { // 600000 ms
286 std::string msg = "Commandline parameter '";
287 msg += commandLineParameter;
288 msg += "' is greater than allowed max timeout for timming engine: ";
289 msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
290 throw RuntimeException(msg, ANNA_FILE_LOCATION);
294 std::string msg = "Commandline parameter '";
295 msg += commandLineParameter;
296 msg += "' is perhaps very big (over 5 minutes). Take into account memory consumption issues.";
297 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
300 if(msecs <= a_timeEngine->getResolution()) {
301 std::string msg = "Commandline parameter '";
302 msg += commandLineParameter;
303 msg += "' (and in general, all time measures) must be greater than timming engine resolution: ";
304 msg += anna::functions::asString(a_timeEngine->getResolution());
305 throw RuntimeException(msg, ANNA_FILE_LOCATION);
311 // Excepcion (por no ser entero):
312 std::string msg = "Error at commandline parameter '";
313 msg += commandLineParameter;
316 msg += "': must be a non-negative integer number";
317 throw RuntimeException(msg, ANNA_FILE_LOCATION);
320 void Launcher::startDiameterServer(int diameterServerSessions) throw(anna::RuntimeException) {
321 if(diameterServerSessions <= 0) return;
325 CommandLine& cl(anna::CommandLine::instantiate());
326 anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("diameterServer"), address, port);
327 //ServerSocket *createServerSocket(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, int category = 1, const std::string & description = "")
328 a_diameterLocalServer = (MyLocalServer*)(a_myDiameterEngine->createLocalServer(address, port, diameterServerSessions));
329 a_diameterLocalServer->setDescription("Launcher diameter local server");
330 a_diameterLocalServer->setProgrammedAnswersCodecEngine(getCodecEngine());
331 int allowedInactivityTime = 90000; // ms
333 if(cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime");
335 a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime);
338 void Launcher::initialize()
339 throw(anna::RuntimeException) {
340 anna::comm::Application::initialize();
341 CommandLine& cl(anna::CommandLine::instantiate());
342 anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single);
343 // if (cl.exists ("clone"))
344 // workMode = anna::comm::Communicator::WorkMode::Clone;
345 a_communicator = new MyCommunicator(workMode);
346 a_timeEngine = new anna::timex::Engine((anna::Millisecond)600000, (anna::Millisecond)150);
347 // Counters record procedure:
348 anna::Millisecond cntRecordPeriod = (anna::Millisecond)300000; // ms
350 if(cl.exists("cntRecordPeriod")) cntRecordPeriod = cl.getIntegerValue("cntRecordPeriod");
352 if(cntRecordPeriod != 0) {
353 checkTimeMeasure("cntRecordPeriod");
354 a_counterRecorderClock = new MyCounterRecorderClock("Counters record procedure clock", cntRecordPeriod); // clock
355 std::string cntDir = ".";
357 if(cl.exists("cntDir")) cntDir = cl.getValue("cntDir");
359 a_counterRecorder = new MyCounterRecorder(cntDir + anna::functions::asString("/Counters.Pid%d", (int)getPid()));
364 throw(anna::RuntimeException) {
365 LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
366 CommandLine& cl(anna::CommandLine::instantiate());
368 a_start_time.setNow();
370 anna::statistics::Engine::instantiate().enable();
372 // Checking command line parameters
373 if(cl.exists("sessionBasedModelsClientSocketSelection")) {
374 std::string type = cl.getValue("sessionBasedModelsClientSocketSelection");
376 if((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) {
377 throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
382 if(cl.exists("trace"))
383 anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
386 // Help on startup traces:
387 anna::Logger::information(help(), ANNA_FILE_LOCATION);
388 // Test messages dtd:
389 std::string msg = "\n ------------- TESTMESSAGES DTD -------------\n";
390 msg += anna::diameter::codec::MessageDTD;
391 anna::Logger::information(msg, ANNA_FILE_LOCATION);
395 if(cl.exists("httpServer")) {
396 anna::comm::Network& network = anna::comm::Network::instantiate();
399 anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
400 //const anna::comm::Device* device = network.find(Device::asAddress(address)); // here provide IP
401 const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // trick to solve
402 a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
406 a_codecEngine = new anna::diameter::codec::Engine(DIAMETER_CODEC_ENGINE_NAME_PREFIX);
407 anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
408 anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id; its value don't mind, is not used (ADL is monostack) */);
409 // Analyze comma-separated list:
411 std::string dictionaryParameter = cl.getValue("dictionary");
412 lst.apply(dictionaryParameter, ",");
414 if(lst.size() >= 1) { // always true (at least one, because -dictionary is mandatory)
415 anna::Tokenizer::const_iterator tok_min(lst.begin());
416 anna::Tokenizer::const_iterator tok_max(lst.end());
417 anna::Tokenizer::const_iterator tok_iter;
418 std::string pathFile;
421 for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
422 pathFile = anna::Tokenizer::data(tok_iter);
427 getCodecEngine()->setDictionary(d);
428 LOGDEBUG(anna::Logger::debug(getCodecEngine()->asString(), ANNA_FILE_LOCATION));
431 std::string all_in_one = "./dictionary-all-in-one.xml";
432 std::ofstream out(all_in_one.c_str(), std::ifstream::out);
433 std::string buffer = d->asXMLString();
434 out.write(buffer.c_str(), buffer.size());
436 std::cout << "Written accumulated '" << all_in_one << "' (provide it next time to be more comfortable)." << std::endl;
439 ///////////////////////////////
440 // Diameter library COUNTERS //
441 ///////////////////////////////
442 anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
443 oamDiameterComm.initializeCounterScope(1); // 1000 - 1999
444 oamDiameterComm.enableCounters();
445 oamDiameterComm.enableAlarms();
446 anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate();
447 oamDiameterCodec.initializeCounterScope(2); // 2000 - 2999
448 oamDiameterCodec.enableCounters();
449 oamDiameterCodec.enableAlarms();
454 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/);
455 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived, "", 1 /*1001*/);
456 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/);
457 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession, "", 3 /*1003*/);
458 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */);
459 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession, "", 5);
460 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK, "", 6);
461 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK, "", 7);
462 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK, "", 8);
463 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK, "", 9);
464 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK, "", 10);
465 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK, "", 11);
466 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK, "", 12);
467 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK, "", 13);
468 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK, "", 14);
469 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK, "", 15);
470 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK, "", 16);
471 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK, "", 17);
472 /* Diameter Base (capabilities exchange & keep alive) */
474 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK, "", 18);
475 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK, "", 19);
476 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20);
477 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK, "", 21);
478 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK, "", 22);
479 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23);
480 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK, "", 24);
481 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK, "", 25);
482 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26);
484 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27);
485 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK, "", 28);
486 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK, "", 29);
487 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30);
488 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK, "", 31);
489 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK, "", 32);
490 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33);
491 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK, "", 34);
492 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK, "", 35);
493 /* server socket operations (enable/disable listening port for any local server) */
494 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36);
495 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37);
498 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity, "", 38);
499 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession, "", 39);
500 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession, "", 40);
501 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer, "", 41);
502 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer, "", 42);
503 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity, "", 43);
504 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity, "", 44);
505 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities, "", 45);
506 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46);
508 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient, "", 47);
509 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession, "", 48);
510 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49);
511 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession, "", 50);
512 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer, "", 51);
513 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer, "", 52);
514 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers, "", 53);
515 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers, "", 54);
516 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired, "", 55);
517 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired, "", 56);
518 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired, "", 57);
519 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown, "", 58);
520 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown, "", 59);
521 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown, "", 60);
526 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength, "", 0 /*2000*/);
527 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/);
528 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength, "", 2 /*2002*/);
529 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence, "", 3 /*2003*/);
530 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit, "", 4 /*2004*/);
531 /* Message decoding */
532 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/);
533 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength, "", 6 /*2006*/);
535 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/);
536 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules, "", 11 /*2011*/);
537 /* Message validation */
538 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/);
539 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags, "", 13 /*2013*/);
540 /* Level validation */
541 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule, "", 14 /*2014*/);
542 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality, "", 15 /*2015*/);
543 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded, "", 16 /*2016*/);
544 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded, "", 17 /*2017*/);
545 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/);
546 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified, "", 19 /*2019*/);
547 ///////////////////////////////////////////
548 // APPLICATION MESSAGE OAM MODULE SCOPES //
549 ///////////////////////////////////////////
550 // We will register a scope per stack id registered. The counters will be dynamically registered at count method.
551 anna::diameter::comm::ApplicationMessageOamModule & appMsgOamModule = anna::diameter::comm::ApplicationMessageOamModule::instantiate();
553 for (anna::diameter::stack::Engine::const_stack_iterator it = stackEngine.stack_begin(); it != stackEngine.stack_end(); it++) {
554 appMsgOamModule.createStackCounterScope(scope_id, it->first);
557 appMsgOamModule.enableCounters(); // this special module is disabled by default (the only)
560 /////////////////////////////////
561 // Counter recorder associated //
562 /////////////////////////////////
563 if(a_counterRecorderClock) {
564 oamDiameterComm.setCounterRecorder(a_counterRecorder);
565 oamDiameterCodec.setCounterRecorder(a_counterRecorder);
566 appMsgOamModule.setCounterRecorder(a_counterRecorder);
567 a_timeEngine->activate(a_counterRecorderClock); // start clock
571 // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
572 // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
573 if(cl.exists("integrationAndDebugging")) {
574 getCodecEngine()->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
575 getCodecEngine()->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
579 if(cl.exists("fixMode")) { // BeforeEncoding(default), AfterDecoding, Always, Never
580 std::string fixMode = cl.getValue("fixMode");
581 anna::diameter::codec::Engine::FixMode::_v fm;
582 if (fixMode == "BeforeEncoding") fm = anna::diameter::codec::Engine::FixMode::BeforeEncoding;
583 else if (fixMode == "AfterDecoding") fm = anna::diameter::codec::Engine::FixMode::AfterDecoding;
584 else if (fixMode == "Always") fm = anna::diameter::codec::Engine::FixMode::Always;
585 else if (fixMode == "Never") fm = anna::diameter::codec::Engine::FixMode::Never;
586 else LOGINFORMATION(anna::Logger::information("Unreconized command-line fix mode. Assumed default 'BeforeEncoding'", ANNA_FILE_LOCATION));
587 getCodecEngine()->setFixMode(fm);
590 getCodecEngine()->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
593 if(cl.exists("diameterServer"))
594 startDiameterServer(cl.exists("diameterServerSessions") ? cl.getIntegerValue("diameterServerSessions") : 1);
596 // Optional command line parameters ////////////////////////////////////////////////////////
597 checkTimeMeasure("allowedInactivityTime");
598 checkTimeMeasure("tcpConnectDelay");
599 checkTimeMeasure("answersTimeout");
600 checkTimeMeasure("ceaTimeout");
601 checkTimeMeasure("watchdogPeriod");
602 checkTimeMeasure("reconnectionPeriod");
603 int tcpConnectDelay = 200; // ms
604 anna::Millisecond answersTimeout = (anna::Millisecond)10000; // ms
605 anna::Millisecond ceaTimeout;
606 anna::Millisecond watchdogPeriod = (anna::Millisecond)30000; // ms
607 int reconnectionPeriod = 10000; // ms
609 if(cl.exists("tcpConnectDelay")) tcpConnectDelay = cl.getIntegerValue("tcpConnectDelay");
611 if(cl.exists("answersTimeout")) answersTimeout = cl.getIntegerValue("answersTimeout");
613 if(cl.exists("ceaTimeout")) ceaTimeout = cl.getIntegerValue("ceaTimeout");
614 else ceaTimeout = answersTimeout;
616 if(cl.exists("watchdogPeriod")) watchdogPeriod = cl.getIntegerValue("watchdogPeriod");
618 if(cl.exists("reconnectionPeriod")) reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod");
620 a_myDiameterEngine->setMaxConnectionDelay((anna::Millisecond)tcpConnectDelay);
621 a_myDiameterEngine->setWatchdogPeriod(watchdogPeriod);
622 std::string originHost = "";
623 std::string originRealm = "";
625 if(cl.exists("cer")) a_cerPathfile = cl.getValue("cer");
627 if(cl.exists("dwr")) a_dwrPathfile = cl.getValue("dwr");
629 if(cl.exists("originHost")) originHost = cl.getValue("originHost");
631 if(cl.exists("originRealm")) originRealm = cl.getValue("originRealm");
633 a_myDiameterEngine->setHost(originHost);
634 a_myDiameterEngine->setRealm(originRealm);
637 if(cl.exists("entity")) {
638 int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1;
640 if(entityServerSessions > 0) {
641 baseProtocolSetupAsClient(); // Same CER/CEA, DWR/DWA for all diameter servers
642 anna::socket_v servers = anna::functions::getSocketVectorFromString(cl.getValue("entity"));
643 a_myDiameterEngine->setNumberOfClientSessionsPerServer(entityServerSessions);
644 a_entity = (MyDiameterEntity*)(a_myDiameterEngine->createEntity(servers, "Launcher diameter entity"));
645 a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, ceaTimeout);
646 a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, answersTimeout);
647 a_entity->setProgrammedAnswersCodecEngine(getCodecEngine());
653 if(cl.exists("log")) a_logFile = cl.getValue("log");
655 if(cl.exists("splitLog")) a_splitLog = true;
657 if(cl.exists("detailedLog")) a_detailedLog = true;
659 if(cl.exists("dumpLog")) a_dumpLog = true;
661 if(cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog");
663 // Log statistics concepts
664 if(cl.exists("logStatisticSamples")) {
665 std::string list = cl.getValue("logStatisticSamples");
666 anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate();
669 if(statEngine.enableSampleLog(/* -1: all concepts */))
670 LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION));
673 lst.apply(cl.getValue("logStatisticSamples"), ",");
675 if(lst.size() >= 1) {
676 anna::Tokenizer::const_iterator tok_min(lst.begin());
677 anna::Tokenizer::const_iterator tok_max(lst.end());
678 anna::Tokenizer::const_iterator tok_iter;
681 for(tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
682 conceptId = atoi(anna::Tokenizer::data(tok_iter));
684 if(statEngine.enableSampleLog(conceptId))
685 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION));
691 a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod);
693 if(cl.exists("httpServer")) a_communicator->attach(a_httpServerSocket); // HTTP
695 a_communicator->accept();
698 bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBlock &db) const throw() {
700 static char buffer[8192];
701 std::ifstream infile(pathfile.c_str(), std::ifstream::in);
703 if(infile.is_open()) {
705 std::string hexString(buffer, strlen(buffer));
706 // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString':
707 hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end());
709 std::string msg = "Hex string (remove colons if exists): ";
711 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
713 anna::functions::fromHexString(hexString, db);
722 int Launcher::clearBurst() throw() {
723 int size = a_burstMessages.size();
726 std::map<int, anna::diameter::comm::Message*>::const_iterator it;
727 std::map<int, anna::diameter::comm::Message*>::const_iterator it_min(a_burstMessages.begin());
728 std::map<int, anna::diameter::comm::Message*>::const_iterator it_max(a_burstMessages.end());
730 for(it = it_min; it != it_max; it++) releaseCommMessage((*it).second);
732 a_burstMessages.clear();
734 std::string msg = "Burst list already empty. Nothing done";
735 std::cout << msg << std::endl;
736 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
739 a_burstActive = false;
741 a_burstDeliveryIt = a_burstMessages.begin();
745 int Launcher::loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException) {
746 anna::diameter::comm::Message *msg = createCommMessage();
748 a_burstMessages[a_burstLoadIndx++] = msg;
749 return (a_burstLoadIndx - 1);
752 int Launcher::stopBurst() throw() {
754 std::string msg = "Burst launch is already stopped. Nothing done";
755 std::cout << msg << std::endl;
756 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
760 a_burstActive = false;
761 // Remaining on cycle:
762 return (a_burstMessages.size() - (*a_burstDeliveryIt).first);
765 int Launcher::popBurst(int releaseAmount) throw() {
767 std::string msg = "Burst launch is stopped. Nothing done";
768 std::cout << msg << std::endl;
769 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
773 if(releaseAmount < 1) {
774 std::string msg = "No valid release amount is specified. Ignoring burst pop";
775 std::cout << msg << std::endl;
776 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
780 int currentOTArequests = a_entity->getOTARequests();
781 a_burstPopCounter = (releaseAmount > currentOTArequests) ? currentOTArequests : releaseAmount;
782 return a_burstPopCounter;
785 int Launcher::pushBurst(int loadAmount) throw() {
786 if(a_burstMessages.size() == 0) {
787 std::string msg = "Burst data not found (empty list). Ignoring burst launch";
788 std::cout << msg << std::endl;
789 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
794 std::string msg = "No valid load amount is specified. Ignoring burst push";
795 std::cout << msg << std::endl;
796 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
800 a_burstActive = true;
803 for(count = 0; count < loadAmount; count++)
804 if(!sendBurstMessage()) break;
809 int Launcher::sendBurst(int loadAmount) throw() {
810 if(a_burstMessages.size() == 0) {
811 std::string msg = "Burst data not found (empty list). Ignoring burst launch";
812 std::cout << msg << std::endl;
813 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
818 std::string msg = "No valid load amount is specified. Ignoring burst send";
819 std::cout << msg << std::endl;
820 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
826 for(count = 0; count < loadAmount; count++)
827 if(!sendBurstMessage(true /* anyway */)) break;
832 int Launcher::startBurst(int initialLoad) throw() {
833 if(initialLoad < 1) {
834 std::string msg = "No initial load is specified. Ignoring burst start";
835 std::cout << msg << std::endl;
836 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
840 a_burstActive = true;
842 a_burstDeliveryIt = a_burstMessages.begin();
843 return (pushBurst(initialLoad));
846 bool Launcher::sendBurstMessage(bool anyway) throw() {
847 if(!anyway && !burstActive()) return false;
849 if(a_burstPopCounter > 0) {
850 if(burstLogEnabled()) writeBurstLogFile("x");
856 if(a_burstDeliveryIt == a_burstMessages.end()) {
857 a_burstDeliveryIt = a_burstMessages.begin();
863 if(burstLogEnabled()) writeBurstLogFile(anna::functions::asString("\nCompleted burst cycle. Starting again (repeat mode) on cycle %d.\n", a_burstCycle));
865 if(burstLogEnabled()) writeBurstLogFile("\nCompleted burst cycle. Burst finished (repeat mode disabled).\n");
873 anna::diameter::comm::Message *msg = (*a_burstDeliveryIt).second;
874 int order = (*a_burstDeliveryIt).first + 1;
878 bool result = a_entity->send(msg, anna::CommandLine::instantiate().exists("balance"));
880 if(burstLogEnabled()) {
881 if(a_burstMessages.size() >= 100)
882 dot = (order % (a_burstMessages.size() / 100));
885 writeBurstLogFile(".");
887 writeBurstLogFile(anna::functions::asString(" %d", order));
888 int otaReqs = a_entity->getOTARequests();
890 if(result && (otaReqs != a_otaRequest)) {
891 // false if was a sending after an answer received (no OTA change in this case)
892 // true after push and pop operations
893 a_otaRequest = otaReqs;
894 writeBurstLogFile(anna::functions::asString("[OTA %d]", a_otaRequest));
901 anna::diameter::comm::Server *usedServer = a_entity->getLastUsedResource();
902 anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
903 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
904 writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail);
910 std::string Launcher::lookBurst(int order) const throw() {
911 std::string result = "No message found for order provided (";
912 result += anna::functions::asString(order);
914 std::map<int, anna::diameter::comm::Message*>::const_iterator it = a_burstMessages.find(order - 1);
916 if(it != a_burstMessages.end()) {
918 anna::diameter::codec::Message codecMsg;
919 try { codecMsg.decode((*it).second->getBody()); } catch(anna::RuntimeException &ex) { ex.trace(); }
920 result = codecMsg.asXMLString();
926 std::string Launcher::gotoBurst(int order) throw() {
927 std::string result = "Position not found for order provided (";
928 std::map<int, anna::diameter::comm::Message*>::iterator it = a_burstMessages.find(order - 1);
930 if(it != a_burstMessages.end()) {
931 a_burstDeliveryIt = it;
932 result = "Position updated for order provided (";
935 result += anna::functions::asString(order);
940 void Launcher::resetCounters() throw() {
941 anna::diameter::comm::OamModule::instantiate().resetCounters();
942 anna::diameter::comm::ApplicationMessageOamModule::instantiate().resetCounters();
943 anna::diameter::codec::OamModule::instantiate().resetCounters();
946 void Launcher::signalUSR2() throw(anna::RuntimeException) {
948 std::string msg = "Captured signal SIGUSR2. Reading tasks at '";
949 msg += SIGUSR2_TASKS_INPUT_FILENAME;
950 msg += "' (results will be written at '";
951 msg += SIGUSR2_TASKS_OUTPUT_FILENAME;
953 anna::Logger::notice(msg, ANNA_FILE_LOCATION);
957 std::string response_content;
958 std::ifstream in_file(SIGUSR2_TASKS_INPUT_FILENAME);
959 std::ofstream out_file(SIGUSR2_TASKS_OUTPUT_FILENAME);
961 if(!in_file.is_open()) throw RuntimeException("Unable to read tasks", ANNA_FILE_LOCATION);
963 if(!out_file.is_open()) throw RuntimeException("Unable to write tasks", ANNA_FILE_LOCATION);
965 while(getline(in_file, line)) {
967 std::string msg = "Processing line: ";
969 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
973 eventOperation(line, response_content);
974 } catch(RuntimeException &ex) {
978 out_file << response_content;
985 std::string Launcher::help() const throw() {
986 std::string result = "\n";
987 result += "\n ------------- HELP -------------\n";
989 result += "\nOVERVIEW";
990 result += "\n--------";
992 result += "\nThe ADL (ANNA Diameter Launcher) process is a complete diameter agent with client and server";
993 result += "\n capabilities as well as balancer (proxy) features. It could be used as diameter server";
994 result += "\n (i.e. to simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.),";
995 result += "\n and balancer systems to provide failover to external round-robin launchers. Also, auxiliary";
996 result += "\n encoder/decoder/loader function could be deployed to reinterpret certain external flow and";
997 result += "\n send it to another process.";
999 result += "\nThe ANNA::diameter_comm built-in module provides a great set of characteristics as multiple connections";
1000 result += "\n on both server and client side, definition for multiple-server entities (and not only two as standard";
1001 result += "\n establish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA";
1002 result += "\n generation, expiration control and many more features.";
1004 result += "\nProcess traces are dump on \"launcher.trace\" and could have any trace level (POSIX levels), usually";
1005 result += "\n 'debug' or 'warning'. See ANNA documentation for more details.";
1007 result += "\nAs any other ANNA process, context dump could be retrieved sending SIGUSR1 signal:";
1008 result += "\n kill -10 <pid>";
1010 result += "\n kill -s SIGUSR1 <pid>";
1011 result += "\n and then";
1012 result += "\n vi /var/tmp/anna.context.<pid>";
1014 result += "\nA complete xml report will show all the context information (counters, alarms, statistics,";
1015 result += "\n handlers, diameter dictionary, etc.), and a powerful log module could dump all the events";
1016 result += "\n processed and flow information. Statistics could be analized at context dump and optionally";
1017 result += "\n written to disk as sample files (useful for graphs and spreadsheet reports) with all the";
1018 result += "\n measurements.";
1020 result += "\nAlso SIGUSR2 is handled for management purposes. We will talk later about this.";
1023 result += "\nCOMMAND LINE";
1024 result += "\n------------";
1026 result += "\nStart the launcher process without arguments in order to see all the startup configuration";
1027 result += "\n posibilities, many of which could be modified on the air through the management interface";
1028 result += "\n (we will talk later about this great feature). Some of the more common parameters are:";
1030 result += "\nAs mandatory, the stack definition given through the xml dictionary:";
1031 result += "\n --dictionary <path to dictionary file>";
1033 result += "\nActing as a diameter server (accepting i.e. 10 connections), you would have:";
1034 result += "\n --diameterServer localhost:3868 --diameterServerSessions 10 --entityServerSessions 0";
1036 result += "\nActing as a diameter client (launching i.e. 10 connections to each entity server), you would have:";
1037 result += "\n --entity 192.168.12.11:3868,192.168.12.21:3868 --entityServerSessions 10 --diameterServerSessions 0";
1039 result += "\nIf you act as a proxy or a translation agent, you need to combine both former setups, and probably";
1040 result += "\n will need to program the answers to be replied through the operations interface. To balance the";
1041 result += "\n traffic at your client side you shall use '--balance' and '--sessionBasedModelsClientSocketSelection'";
1042 result += "\n arguments in order to define the balancing behaviour.";
1044 result += "\nThe process builds automatically CER and DWR messages as a client, but you could specify your own";
1045 result += "\n customized ones using '--cer <xml message file>' and '--dwr <xml message file>'.";
1046 result += "\nThe process builds automatically CEA and DWA messages as a server, but you could program your own";
1047 result += "\n customized ones using operations interface.";
1050 result += "\nDYNAMIC OPERATIONS";
1051 result += "\n------------------";
1053 result += "\nADL supports several operations which could be reconized via HTTP interface or SIGUSR2 caugh.";
1054 result += "\nAn operation is specified by mean a string containing the operation name and needed arguments";
1055 result += "\n separated by pipes. These are the available commands:";
1057 result += "\n--------------------------------------------------------------------------------------- General purpose";
1059 result += "\nhelp This help. Startup information-level traces also dump this help.";
1061 result += "\n------------------------------------------------------------------------------------ Parsing operations";
1063 result += "\ncode|<source_file>|<target_file> Encodes source file (pathfile) into target file (pathfile).";
1064 result += "\ndecode|<source_file>|<target_file> Decodes source file (pathfile) into target file (pathfile).";
1065 result += "\nloadxml|<source_file> Reinterpret xml source file (pathfile).";
1067 result += "\n------------------------------------------------------------------------------------------- Hot changes";
1069 result += "\ndiameterServerSessions|<integer> Updates the maximum number of accepted connections to diameter";
1070 result += "\n server socket.";
1071 result += "\ncontext|[target file] Application context could also be written by mean this operation,";
1072 result += "\n and not only through SIGUSR1. If optional path file is missing,";
1073 result += "\n default '/var/tmp/anna.context.<pid>' will be used.";
1074 result += "\ncollect Reset statistics and counters to start a new test stage of";
1075 result += "\n performance measurement. Context data can be written at";
1076 result += "\n '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'";
1077 result += "\n or sending operation 'context|[target file]'.";
1078 result += "\nforceCountersRecord Forces dump to file the current counters of the process.";
1080 result += "\n<visibility action>|[<address>:<port>]|[socket id]";
1082 result += "\n Actions: hide, show (update state) and hidden, shown (query state).";
1083 result += "\n Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A).";
1084 result += "\n If missing server (first parameter) all applications sockets will be affected.";
1085 result += "\n If missing socket (second parameter) for specific server, all its sockets will be affected.";
1087 result += "\n All application client sessions are shown on startup, but standard delivery only use primary";
1088 result += "\n server ones except if fails. Balance configuration use all the allowed sockets. You could also";
1089 result += "\n use command line 'sessionBasedModelsClientSocketSelection' to force traffic flow over certain";
1090 result += "\n client sessions, but for this, hide/show feature seems easier.";
1092 result += "\n--------------------------------------------------------------------------------------- Flow operations";
1094 result += "\nsendxml2e|<source_file> Sends xml source file (pathfile) through configured entity.";
1095 result += "\nsendxml2c|<source_file> Sends xml source file (pathfile) to client.";
1096 result += "\nsendxml|<source_file> Same as 'sendxml2e'.";
1097 result += "\nanswerxml2e|[source_file] Answer xml source file (pathfile) for incoming request with same code from entity.";
1098 result += "\n The answer is stored in a FIFO queue for a specific message code, then there are";
1099 result += "\n as many queues as different message codes have been programmed.";
1100 result += "\nanswerxml2c|[source_file] Answer xml source file (pathfile) for incoming request with same code from client.";
1101 result += "\n The answer is stored in a FIFO queue for a specific message code, then there are";
1102 result += "\n as many queues as different message codes have been programmed.";
1103 result += "\nanswerxml|[source_file] Same as 'answerxml2c'.";
1104 result += "\nanswerxml(2e/2c) List programmed answers (to entity/client) if no parameter provided.";
1105 result += "\nanswerxml(2e/2c)|dump Write programmed answers (to entity/client) to file 'programmed_answer.<message code>.<sequence>',";
1106 result += "\n where 'sequence' is the order of the answer in each FIFO code-queue of programmed answers.";
1107 result += "\nanswerxml(2e/2c)|clear Clear programmed answers (to entity/client).";
1108 result += "\nanswerxml(2e/2c)|exhaust Disable the corresponding queue rotation, which is the default behaviour.";
1109 result += "\nanswerxml(2e/2c)|rotate Enable the corresponding queue rotation, useful in performance tests.";
1110 result += "\n Rotation consists in add again to the queue, each element retrieved for answering.";
1112 result += "\nSend operations are available using hexadecimal content (hex formatted files) which also allow to test";
1113 result += "\nspecial scenarios (protocol errors):";
1115 result += "\nsendhex2e|<source_file> Sends hex source file (pathfile) through configured entity.";
1116 result += "\nsendhex2c|<source_file> Sends hex source file (pathfile) to client.";
1117 result += "\nsendhex|<source_file> Same as 'sendhex2e'.";
1119 result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also";
1120 result += "\n is intended to be used with decoded messages in order to replace things like hop by hop, end to end,";
1121 result += "\n subscriber id, session id, etc. Anyway you could use 'decode' operation and then program the xml created.";
1123 result += "\nIf a request is received, answer map (built with 'answerxml<[2c] or 2e>' operations) will be";
1124 result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,";
1125 result += "\n or answer message was received, the message is forwarded to the other side (entity or client),";
1126 result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when";
1127 result += "\n diameter server socket is configured, answer to entity have sense when entity does.";
1129 result += "\nIn the most complete situation (process with both client and server side) there are internally";
1130 result += "\n two maps with N FIFO queues, one for each different message code within programmed answers.";
1131 result += "\nOne map is for answers towards the client, and the other is to react entity requests. Then in";
1132 result += "\n each one we could program different answers corresponding to different request codes received.";
1134 result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored";
1135 result += "\n to the peer which sent the request. If user wants to test a specific answer without changing it,";
1136 result += "\n use sendxml/sendhex operations better than programming.";
1138 result += "\nBalance ('-balance' command line parameter) could be used to forward server socket receptions through";
1139 result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should";
1140 result += "\n have been configured, that is to say: launcher acts as client and server. If no balance is used, an";
1141 result += "\n standard delivery is performed: first primary entity server, secondary when fails, etc.";
1143 result += "\n--------------------------------------------------------------------------- Processing types (log tags)";
1145 result += "\nUsed as log file extensions (when '-splitLog' is provided on command line) and context preffixes on log";
1146 result += "\n details when unique log file is dumped:";
1148 result += "\n [sent2e/send2eError] Send to entity (success/error)";
1149 result += "\n [sent2c/send2cError] Send to client (success/error)";
1150 result += "\n [fwd2e/fwd2eError] Forward to entity a reception from client (success/error)";
1151 result += "\n [fwd2c/fwd2cError] Forward to client a reception from entity (success/error)";
1152 result += "\n [recvfc] Reception from client";
1153 result += "\n [recvfe] Reception from entity";
1154 result += "\n [req2c-expired] A request sent to client has been expired";
1155 result += "\n [req2e-expired] A request sent to entity has been expired";
1156 result += "\n [recvfc-ans-unknown] Reception from client of an unknown answer (probably former [req2c-expired]";
1157 result += "\n has been logged)";
1158 result += "\n [recvfe-ans-unknown] Reception from entity of an unknown answer (probably former [req2e-expired]";
1159 result += "\n has been logged)";
1161 result += "\n-------------------------------------------------------------------------------------------- Load tests";
1163 result += "\nburst|<action>|[parameter] Used for performance testing, we first program diameter requests";
1164 result += "\n messages in order to launch them from client side to the configured";
1165 result += "\n diameter entity. We could start the burst with an initial load";
1166 result += "\n (non-asynchronous sending), after this, a new request will be sent";
1167 result += "\n per answer received or expired context. There are 10 actions: clear,";
1168 result += "\n load, start, push, pop, stop, repeat, send, goto and look.";
1170 result += "\n burst|clear Clears all loaded burst messages.";
1171 result += "\n burst|load|<source_file> Loads the next diameter message into launcher burst.";
1172 result += "\n burst|start|<initial load> Starts (or restarts if already in progress) the message sending with";
1173 result += "\n a certain initial load.";
1174 result += "\n burst|push|<load amount> Sends specific non-aynchronous load.";
1175 result += "\n burst|pop|<release amount> Skip send burst messages in order to reduce over-the-air requests.";
1176 result += "\n Popping all OTA requests implies burst stop because no more answer";
1177 result += "\n will arrive to the process. Burst output file (-burstLog command";
1178 result += "\n line parameter) shows popped messages with crosses (x). Each cross";
1179 result += "\n represents one received answer for which no new request is sent.";
1180 result += "\n burst|stop Stops the burst cycle. You can resume pushing 1 load amount.";
1181 result += "\n burst|repeat|[[yes]|no] Restarts the burst launch when finish. If initial load or push load";
1182 result += "\n amount is greater than burst list size, they will be limited when";
1183 result += "\n the list is processed except when repeat mode is enabled.";
1184 result += "\n burst|send|<amount> Sends messages from burst list. The main difference with start/push";
1185 result += "\n operations is that burst won't be awaken. Externally we could control";
1186 result += "\n sending time (no request will be sent for answers).";
1187 result += "\n burst|goto|<order> Updates current burst pointer position.";
1188 result += "\n burst|look|<order> Show programmed burst message for order provided.";
1191 result += "\nUSING OPERATIONS INTERFACE";
1192 result += "\n--------------------------";
1194 result += "\n------------------------------------------------------------------------- Operations via HTTP interface";
1196 result += "\nAll the operations described above can be used through the optional HTTP interface. You only have";
1197 result += "\n to define the http server at the command line with something like: '-httpServer localhost:9000'.";
1198 result += "\nTo send the task, we shall build the http request body with the operation string. Some examples";
1199 result += "\n using curl client could be:";
1201 result += "\n curl -m 1 --data \"diameterServerSessions|4\" localhost:9000";
1202 result += "\n curl -m 1 --data \"code|ccr.xml\" localhost:9000";
1203 result += "\n curl -m 1 --data \"decode|ccr.hex\" localhost:9000";
1204 result += "\n curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000";
1205 result += "\n etc.";
1207 result += "\n------------------------------------------------------------------------- Operations via SIGUSR2 signal";
1209 result += "\nThe alternative using SIGUSR2 signal requires the creation of the task(s) file which will be read at";
1210 result += "\n signal event:";
1211 result += "\n echo \"<<operation>\" > "; result += SIGUSR2_TASKS_INPUT_FILENAME;
1212 result += "\n then";
1213 result += "\n kill -12 <pid>";
1215 result += "\n kill -s SIGUSR2 <pid>";
1216 result += "\n and then see the results:";
1217 result += "\n cat "; result += SIGUSR2_TASKS_OUTPUT_FILENAME;
1219 result += "\nYou could place more than one line (task) in the input file. Output reports will be appended in that";
1220 result += "\n case over the output file. Take into account that all the content of the task file will be executed";
1221 result += "\n sinchronously by the process. If you are planning traffic load, better use the asynchronous http";
1222 result += "\n interface.";
1228 void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
1229 LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION));
1230 CommandLine& cl(anna::CommandLine::instantiate());
1231 LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION));
1232 response_content = "Operation processed with exception. See traces\n"; // supposed
1233 std::string result = "";
1234 anna::DataBlock db_aux(true);
1235 anna::diameter::codec::Message codecMsg;
1237 ///////////////////////////////////////////////////////////////////
1238 // Simple operations without arguments:
1241 if(operation == "help") {
1242 std::string s_help = help();
1243 std::cout << s_help << std::endl;
1244 LOGINFORMATION(anna::Logger::information(s_help, ANNA_FILE_LOCATION));
1245 response_content = "Help dumped on stdout and information-level traces (launcher.trace file)\n";
1249 // Reset performance data:
1250 if(operation == "collect") {
1253 response_content = "All process counters & statistic information have been reset\n";
1257 // Counters dump on demand:
1258 if(operation == "forceCountersRecord") {
1259 forceCountersRecord();
1260 response_content = "Current counters have been dump to disk\n";
1264 ///////////////////////////////////////////////////////////////////
1265 // Tokenize operation
1267 params.apply(operation, "|");
1268 int numParams = params.size() - 1;
1270 // No operation has more than 2 arguments ...
1272 LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
1273 throw anna::RuntimeException("Wrong body content format on HTTP Request", ANNA_FILE_LOCATION);
1276 // Get the operation type:
1277 Tokenizer::const_iterator tok_iter = params.begin();
1278 std::string opType = Tokenizer::data(tok_iter);
1279 // Check the number of parameters:
1280 bool wrongBody = false;
1282 if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true;
1284 if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
1286 if((opType == "burst") && (numParams < 1)) wrongBody = true;
1288 if(((opType == "sendxml2c") || (opType == "sendhex2c") || (opType == "loadxml") || (opType == "diameterServerSessions")) && (numParams != 1)) wrongBody = true;
1292 std::string msg = "Wrong body content format on HTTP Request for '";
1294 msg += "' operation (missing parameter/s)";
1295 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1299 std::string param1, param2;
1301 if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
1303 if(numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
1306 if(opType == "context") {
1307 std::string contextFile = ((numParams == 1) ? param1 : anna::functions::asString("/var/tmp/anna.context.%05d", getPid()));
1308 writeContext(contextFile);
1309 response_content = anna::functions::asString("Context dumped on file '%s'\n", contextFile.c_str());
1313 if(opType == "code") {
1314 codecMsg.loadXML(param1);
1315 std::string hexString = anna::functions::asHexString(codecMsg.code());
1317 std::ofstream outfile(param2.c_str(), std::ifstream::out);
1318 outfile.write(hexString.c_str(), hexString.size());
1320 } else if(opType == "decode") {
1321 // Get DataBlock from file with hex content:
1322 if(!getDataBlockFromHexFile(param1, db_aux))
1323 throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1326 try { codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); }
1328 std::string xmlString = codecMsg.asXMLString();
1330 std::ofstream outfile(param2.c_str(), std::ifstream::out);
1331 outfile.write(xmlString.c_str(), xmlString.size());
1333 } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
1334 MyDiameterEntity *entity = getEntity();
1336 if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
1340 std::string key = param1;
1344 if(opType == "hide") getMyDiameterEngine()->findClientSession(key)->hide();
1346 if(opType == "show") getMyDiameterEngine()->findClientSession(key)->show();
1348 if(opType == "hidden") result = getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false";
1350 if(opType == "shown") result = getMyDiameterEngine()->findClientSession(key)->shown() ? "true" : "false";
1352 std::string address;
1354 anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
1356 if(opType == "hide") getMyDiameterEngine()->findServer(address, port)->hide();
1358 if(opType == "show") getMyDiameterEngine()->findServer(address, port)->show();
1360 if(opType == "hidden") result = getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false";
1362 if(opType == "shown") result = getMyDiameterEngine()->findServer(address, port)->shown() ? "true" : "false";
1365 if(opType == "hide") entity->hide();
1367 if(opType == "show") entity->show();
1369 if(opType == "hidden") result = entity->hidden() ? "true" : "false";
1371 if(opType == "shown") result = entity->shown() ? "true" : "false";
1373 } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
1374 MyDiameterEntity *entity = getEntity();
1376 if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
1377 anna::diameter::comm::Message *msg = createCommMessage();
1379 if((opType == "sendxml") || (opType == "sendxml2e")) {
1380 codecMsg.loadXML(param1);
1382 try { 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)
1384 msg->setBody(codecMsg.code());
1386 // Get DataBlock from file with hex content:
1387 if(!getDataBlockFromHexFile(param1, db_aux))
1388 throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1390 msg->setBody(db_aux);
1393 bool success = entity->send(msg, cl.exists("balance"));
1394 releaseCommMessage(msg);
1398 anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
1399 anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
1400 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
1401 writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail);
1403 } else if((opType == "burst")) {
1404 anna::diameter::comm::Entity *entity = getEntity();
1406 if(!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION);
1408 // burst|clear clears all loaded burst messages.
1409 // burst|load|<source_file> loads the next diameter message into launcher burst.
1410 // burst|start|<initial load> starts the message sending with a certain initial load.
1411 // burst|push|<load amount> sends specific non-aynchronous load.
1412 // burst|stop stops the burst cycle.
1413 // burst|repeat|[[yes]|no] restarts the burst launch when finish.
1414 // burst|send|<amount> send messages from burst list. The main difference with
1415 // start/push operations is that burst won't be awaken.
1416 // Externally we could control sending time (no request
1417 // will be sent for answers).
1418 // burst|goto|<order> Updates current burst pointer position.
1419 // burst|look|<order> Show programmed burst message for order provided.
1421 if(param1 == "clear") {
1422 result = "Removed ";
1423 result += anna::functions::asString(clearBurst());
1424 result += " elements.";
1425 } else if(param1 == "load") {
1426 if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
1428 codecMsg.loadXML(param2);
1430 if(codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
1431 try { 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)
1433 int position = loadBurstMessage(codecMsg.code());
1434 result = "Loaded '";
1436 result += "' file into burst list position ";
1437 result += anna::functions::asString(position);
1438 } else if(param1 == "start") {
1439 if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
1441 int initialLoad = atoi(param2.c_str());
1442 int processed = startBurst(initialLoad);
1445 result = "Initial load completed for ";
1446 result += anna::functions::entriesAsString(processed, "message");
1449 } else if(param1 == "push") {
1450 if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
1452 int pushed = pushBurst(atoi(param2.c_str()));
1456 result += anna::functions::entriesAsString(pushed, "message");
1459 } else if(param1 == "pop") {
1460 if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
1462 int releaseLoad = atoi(param2.c_str());
1463 int popped = popBurst(releaseLoad);
1466 result = "Burst popped for ";
1467 result += anna::functions::entriesAsString(popped, "message");
1470 } else if(param1 == "stop") {
1471 int left = stopBurst();
1474 result += anna::functions::entriesAsString(left, "message");
1475 result += " left to the end of the cycle.";
1477 } else if(param1 == "repeat") {
1478 if(param2 == "") param2 = "yes";
1480 bool repeat = (param2 == "yes");
1481 repeatBurst(repeat);
1482 result += (repeat ? "Mode on." : "Mode off.");
1483 } else if(param1 == "send") {
1484 if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
1486 int sent = sendBurst(atoi(param2.c_str()));
1490 result += anna::functions::entriesAsString(sent, "message");
1493 } else if(param1 == "goto") {
1494 if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
1496 result = gotoBurst(atoi(param2.c_str()));
1498 } else if(param1 == "look") {
1499 if(param2 == "") throw anna::RuntimeException("Missing order position for burst look operation", ANNA_FILE_LOCATION);
1502 result += lookBurst(atoi(param2.c_str()));
1505 throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
1507 } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
1508 MyLocalServer *localServer = getDiameterLocalServer();
1510 if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
1511 anna::diameter::comm::Message *msg = createCommMessage();
1513 if(opType == "sendxml2c") {
1514 codecMsg.loadXML(param1);
1516 try { 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)
1518 msg->setBody(codecMsg.code());
1520 // Get DataBlock from file with hex content:
1521 if(!getDataBlockFromHexFile(param1, db_aux))
1522 throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
1524 msg->setBody(db_aux);
1527 bool success = localServer->send(msg);
1528 releaseCommMessage(msg);
1532 anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
1533 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
1534 writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail);
1536 } else if(opType == "loadxml") {
1537 codecMsg.loadXML(param1);
1538 std::string xmlString = codecMsg.asXMLString();
1539 std::cout << xmlString << std::endl;
1540 } else if(opType == "diameterServerSessions") {
1541 int diameterServerSessions = atoi(param1.c_str());
1543 if(!getDiameterLocalServer())
1544 startDiameterServer(diameterServerSessions);
1546 getDiameterLocalServer()->setMaxConnections(diameterServerSessions);
1547 } else if((opType == "answerxml") || (opType == "answerxml2c")) {
1548 MyLocalServer *localServer = getDiameterLocalServer();
1551 throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
1553 if(param1 == "") { // programmed answers FIFO's to stdout
1554 std::cout << localServer->getReactingAnswers()->asString("ANSWERS TO CLIENT") << std::endl;
1555 response_content = "Programmed answers dumped on stdout\n";
1557 } else if (param1 == "rotate") {
1558 localServer->getReactingAnswers()->rotate(true);
1559 } else if (param1 == "exhaust") {
1560 localServer->getReactingAnswers()->rotate(false);
1561 } else if (param1 == "clear") {
1562 localServer->getReactingAnswers()->clear();
1563 } else if (param1 == "dump") {
1564 localServer->getReactingAnswers()->dump();
1566 anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1);
1569 anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
1572 if(message->isRequest())
1573 throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
1575 int code = message->getId().first;
1576 LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
1577 localServer->getReactingAnswers()->addMessage(code, message);
1579 } else if(opType == "answerxml2e") {
1580 MyDiameterEntity *entity = getEntity();
1583 throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
1585 if(param1 == "") { // programmed answers FIFO's to stdout
1586 std::cout << entity->getReactingAnswers()->asString("ANSWERS TO ENTITY") << std::endl;
1587 response_content = "Programmed answers dumped on stdout\n";
1589 } else if (param1 == "rotate") {
1590 entity->getReactingAnswers()->rotate(true);
1591 } else if (param1 == "exhaust") {
1592 entity->getReactingAnswers()->rotate(false);
1593 } else if (param1 == "clear") {
1594 entity->getReactingAnswers()->clear();
1595 } else if (param1 == "dump") {
1596 entity->getReactingAnswers()->dump();
1598 anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1);
1601 anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
1604 if(message->isRequest())
1605 throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
1607 int code = message->getId().first;
1608 LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
1609 entity->getReactingAnswers()->addMessage(code, message);
1612 LOGWARNING(anna::Logger::warning(help(), ANNA_FILE_LOCATION));
1613 throw anna::RuntimeException("Wrong body content format on HTTP Request. Unsupported/unrecognized operation type", ANNA_FILE_LOCATION);
1617 response_content = "Operation processed; ";
1619 if((opType == "decode") || (opType == "code")) {
1620 response_content += "File '";
1621 response_content += param2;
1622 response_content += "' created.";
1623 response_content += "\n";
1624 } else if((opType == "hide") || (opType == "show")) {
1625 response_content += "Resource '";
1626 response_content += ((param1 != "") ? param1 : "Entity");
1629 response_content += "|";
1630 response_content += param2;
1633 response_content += "' ";
1635 if(opType == "hide") response_content += "has been hidden.";
1637 if(opType == "show") response_content += "has been shown.";
1639 response_content += "\n";
1640 } else if((opType == "hidden") || (opType == "shown")) {
1641 response_content += "Result: ";
1642 response_content += result;
1643 response_content += "\n";
1644 } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
1645 response_content += "Message '";
1646 response_content += param1;
1647 response_content += "' sent to entity.";
1648 response_content += "\n";
1649 } else if(opType == "burst") {
1650 response_content += "Burst '";
1651 response_content += param1;
1652 response_content += "' executed. ";
1653 response_content += result;
1654 response_content += "\n";
1655 } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
1656 response_content += "Message '";
1657 response_content += param1;
1658 response_content += "' sent to client.";
1659 response_content += "\n";
1660 } else if(opType == "loadxml") {
1661 response_content += "Message '";
1662 response_content += param1;
1663 response_content += "' loaded.";
1664 response_content += "\n";
1665 } else if((opType == "answerxml") || (opType == "answerxml2c")) {
1666 response_content += "'";
1667 response_content += param1;
1668 response_content += "' applied on server FIFO queue";
1669 response_content += "\n";
1670 } else if(opType == "answerxml2e") {
1671 response_content += "'";
1672 response_content += param1;
1673 response_content += "' applied on client FIFO queue";
1674 response_content += "\n";
1675 } else if(opType == "diameterServerSessions") {
1676 response_content += "Maximum server socket connections updated to '";
1677 response_content += param1;
1678 response_content += "'.";
1679 response_content += "\n";
1683 int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() {
1684 CommandLine& cl(anna::CommandLine::instantiate());
1685 std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart");
1687 if(sessionBasedModelsType == "RoundRobin") return -1; // IEC also would return -1
1690 // Service-Context-Id:
1691 anna::diameter::helpers::dcca::ChargingContext::_v chargingContext;
1692 std::string scid = anna::diameter::helpers::dcca::functions::getServiceContextId(message->getBody(), chargingContext);
1694 switch(chargingContext) {
1695 case anna::diameter::helpers::dcca::ChargingContext::Data:
1696 case anna::diameter::helpers::dcca::ChargingContext::Voice:
1697 case anna::diameter::helpers::dcca::ChargingContext::Content: {
1698 // Session-Id: '<DiameterIdentity>;<high 32 bits>;<low 32 bits>[;<optional value>="">]'
1699 std::string sid = anna::diameter::helpers::base::functions::getSessionId(message->getBody());
1700 std::string diameterIdentity, optional;
1701 anna::U32 high, low;
1702 anna::diameter::helpers::base::functions::decodeSessionId(sid, diameterIdentity, high, low /* context-teid */, optional);
1704 if(sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions);
1706 if(sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions);
1708 if(sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions);
1710 //case anna::diameter::helpers::dcca::ChargingContext::SMS:
1711 //case anna::diameter::helpers::dcca::ChargingContext::MMS:
1713 // return -1; // IEC model and Unknown traffic types
1715 } catch(anna::RuntimeException &ex) {
1717 std::string msg = ex.getText();
1718 msg += " | Round-robin between sessions will be used to send";
1719 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
1726 anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
1728 anna::xml::Node* result = parent->createChild("launcher");
1729 anna::comm::Application::asXML(result);
1731 result->createAttribute("StartTime", a_start_time.asString());
1732 result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
1734 getCodecEngine()->asXML(result);
1736 anna::diameter::comm::OamModule::instantiate().asXML(result);
1737 anna::diameter::comm::ApplicationMessageOamModule::instantiate().asXML(result);
1738 anna::diameter::codec::OamModule::instantiate().asXML(result);
1740 anna::statistics::Engine::instantiate().asXML(result);