1 // ANNA - Anna is Not 'N' Anymore
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
5 // https://bitbucket.org/testillano/anna
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 Google Inc. 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
38 Establece un manejador externo para controlar el teclado, recoge los parametros de la operacion
39 por este y envia la peticion al servidor.
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/diameter/stack/Engine.hpp>
61 #include <anna/diameter/codec/Engine.hpp>
62 #include <anna/diameter.comm/OamModule.hpp>
63 #include <anna/diameter.comm/ClientSession.hpp>
64 #include <anna/diameter.comm/LocalServer.hpp>
65 #include <anna/diameter.comm/Engine.hpp>
66 #include <anna/diameter.comm/Entity.hpp>
67 #include <anna/diameter.comm/Response.hpp>
68 #include <anna/diameter/functions.hpp>
69 #include <anna/diameter/codec/OamModule.hpp>
70 #include <anna/diameter/codec/functions.hpp>
71 #include <anna/time/functions.hpp>
72 #include <anna/time/Date.hpp>
73 #include <anna/diameter/helpers/base/defines.hpp>
74 #include <anna/diameter/helpers/base/functions.hpp>
75 #include <anna/diameter/helpers/dcca/defines.hpp>
76 #include <anna/diameter/helpers/dcca/functions.hpp>
77 #include <anna/statistics/Engine.hpp>
78 #include <anna/core/functions.hpp>
94 // Auxiliary message for sendings
95 anna::diameter::comm::Message G_commMsgSent2c, G_commMsgSent2e, G_commMsgFwd2c, G_commMsgFwd2e;
96 anna::diameter::comm::Message G_commMsg;
97 anna::diameter::codec::Message G_codecMsg, G_codecAnsMsg;
98 anna::Recycler<anna::diameter::comm::Message> G_commMessages; // create en el forward de requets sin answer programada
99 // realease en el forward de answers
102 // Auxiliary resources for answers programming
103 typedef std::map < int /* message code */, anna::diameter::codec::Message* > reacting_answers_container;
104 typedef std::map < int /* message code */, anna::diameter::codec::Message* >::iterator reacting_answers_iterator;
105 typedef std::map < int /* message code */, anna::diameter::codec::Message* >::const_iterator reacting_answers_const_iterator;
106 reacting_answers_container G_reactingAnswers2C, G_reactingAnswers2E;
110 class MyDiameterEntity : public anna::diameter::comm::Entity {
112 void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException);
113 void eventRequest(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException);
114 void eventUnknownResponse(anna::diameter::comm::ClientSession *, const anna::DataBlock&) throw(anna::RuntimeException);
117 int readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw();
120 class MyLocalServer : public anna::diameter::comm::LocalServer {
122 void eventResponse(const anna::diameter::comm::Response&) throw(anna::RuntimeException);
123 void eventRequest(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException);
124 void eventUnknownResponse(anna::diameter::comm::ServerSession *, const anna::DataBlock&) throw(anna::RuntimeException);
127 class MyDiameterEngine : public anna::diameter::comm::Engine {
130 static const char* getClassName() throw() { return "launcher::MyDiameterEngine"; }
131 MyDiameterEngine() {;}
133 // Default implementation is enough
134 // void readDPA(anna::DataBlock &dpa, const anna::DataBlock & dpr) throw() {;} // DPA is not replied
135 // void readCEA(anna::DataBlock &cea, const anna::DataBlock & cer) throw() {;} // CEA is not replied
136 // void readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw() {;} // DWA is not replied
139 anna::Recycler<MyDiameterEntity> a_entitiesRecycler;
141 anna::diameter::comm::Entity* allocateEntity() throw() { return a_entitiesRecycler.create(); }
143 void releaseEntity(anna::diameter::comm::Entity* entity) throw() {
144 MyDiameterEntity* aux = static_cast <MyDiameterEntity*>(entity);
145 a_entitiesRecycler.release(aux);
148 anna::Recycler<MyLocalServer> a_localServersRecycler;
150 anna::diameter::comm::LocalServer* allocateLocalServer() throw() { return a_localServersRecycler.create(); }
152 void releaseLocalServer(anna::diameter::comm::LocalServer* localServer) throw() {
153 MyLocalServer* aux = static_cast <MyLocalServer*>(localServer);
154 a_localServersRecycler.release(aux);
159 class MyHandler : public anna::http::Handler {
161 MyHandler() : anna::http::Handler("http_converter::MyHandler") {
162 allocateResponse()->createHeader(anna::http::Header::Type::Date);
167 void evRequest(anna::comm::ClientSocket&, const anna::http::Request& request) throw(anna::RuntimeException);
168 void evResponse(anna::comm::ClientSocket&, const anna::http::Response&) throw(anna::RuntimeException) {;}
169 void sendOperation(const std::string &, std::string &) throw(anna::RuntimeException);
172 class MyCommunicator : public anna::comm::Communicator {
174 MyCommunicator(const anna::comm::Communicator::WorkMode::_v acceptMode = anna::comm::Communicator::WorkMode::Single) : anna::comm::Communicator(acceptMode),
175 a_contexts("Contexts")
178 void prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw();
179 void terminate() throw();
182 anna::ThreadData <MyHandler> a_contexts;
183 void eventReceiveMessage(anna::comm::ClientSocket&, const anna::comm::Message&) throw(anna::RuntimeException);
184 void eventBreakConnection(Server* server) throw();
188 class MyCounterRecorder : public anna::oam::CounterRecorder {
190 // pure virtual definitions:
191 void open() throw(anna::RuntimeException) {;}
192 void apply(const anna::oam::Counter& counter) throw(anna::RuntimeException) {;}
193 void close() throw() {;}
194 std::string asString() const throw() { return "Physical dump not implemented: see memory accumulations writting context (kill -10 <pid>)"; }
198 class Launcher : public anna::comm::Application {
200 MyCommunicator *a_communicator;
201 MyDiameterEngine *a_myDiameterEngine;
202 anna::diameter::comm::Entity *a_entity;
203 std::string a_logFile, a_burstLogFile;
204 std::ofstream a_burstLogStream;
205 bool a_splitLog, a_detailedLog;
206 anna::time::Date a_start_time;
207 anna::timex::Engine* a_timeEngine;
208 MyCounterRecorder *a_counterRecorder;
209 std::string a_cerPathfile;
210 std::string a_dwrPathfile;
216 std::map < int /* dummy, p.e. used for order number */, anna::diameter::comm::Message* > a_burstMessages;
218 std::map<int, anna::diameter::comm::Message*>::const_iterator a_burstDeliveryIt;
220 int a_burstPopCounter;
222 anna::comm::ServerSocket* a_httpServerSocket; // HTTP
223 anna::diameter::comm::LocalServer* a_diameterLocalServer; // DIAMETER
224 void checkTimeMeasure(const char * commandLineParameter, bool optional = true) throw(anna::RuntimeException);
225 void initialize() throw(anna::RuntimeException); // HTTP
226 void run() throw(anna::RuntimeException);
231 MyCommunicator *getCommunicator() throw() { return a_communicator; }
232 MyDiameterEngine* getMyDiameterEngine() const throw() { return (a_myDiameterEngine); }
233 void baseProtocolSetupAsClient(void) throw(anna::RuntimeException);
234 anna::diameter::comm::Entity *getEntity() throw() { return a_entity; }
235 anna::diameter::comm::LocalServer* getDiameterLocalServer() throw() { return a_diameterLocalServer; }
236 bool logEnabled() const throw() { return (((a_logFile == "") || (a_logFile == "null")) ? false : true); }
237 void writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw();
238 void writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw();
239 void writeBurstLogFile(const std::string &buffer) throw();
240 bool burstLogEnabled() const throw() { return (((a_burstLogFile == "") || (a_burstLogFile == "null")) ? false : true); }
241 void startDiameterServer(int) throw(anna::RuntimeException);
243 anna::xml::Node* asXML(anna::xml::Node* parent) const throw();
244 void resetStatistics() throw() { a_myDiameterEngine->resetStatistics(); }
245 void resetCounters() throw();
246 std::string help() const throw();
247 std::string programmedAnswers2e() const throw();
248 std::string programmedAnswers2c() const throw();
251 int clearBurst() throw(); // returns removed
252 int loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException);
253 void repeatBurst(bool repeat) throw() { a_burstRepeat = repeat; }
254 int startBurst(int initialLoad) throw(); // return processed on start, or -1 if burst list is empty, -2 if invalid initial load (0 or negative)
255 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)
256 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)
257 int popBurst(int releaseAmount) throw(); // returns popped (perhaps is less than provided because of OTA request), or -1 if burst stopped
258 int stopBurst() throw(); // returns remaining on cycle, or -1 if burst already stopped
259 bool burstActive() const throw() { return a_burstActive; }
260 bool sendBurstMessage(bool anyway = false) throw();
261 std::string lookBurst(int order) const throw();
262 std::string gotoBurst(int order) throw();
265 int Launcher::clearBurst() throw() {
266 int size = a_burstMessages.size();
269 std::map<int, anna::diameter::comm::Message*>::const_iterator it;
270 std::map<int, anna::diameter::comm::Message*>::const_iterator it_min(a_burstMessages.begin());
271 std::map<int, anna::diameter::comm::Message*>::const_iterator it_max(a_burstMessages.end());
273 for (it = it_min; it != it_max; it++) G_commMessages.release((*it).second);
275 a_burstMessages.clear();
277 std::string msg = "Burst list already empty. Nothing done";
278 std::cout << msg << std::endl;
279 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
282 a_burstActive = false;
284 a_burstDeliveryIt = a_burstMessages.begin();
289 int Launcher::loadBurstMessage(const anna::DataBlock & db) throw(anna::RuntimeException) {
290 anna::diameter::comm::Message *msg = G_commMessages.create();
292 a_burstMessages[a_burstLoadIndx++] = msg;
293 return (a_burstLoadIndx - 1);
296 int Launcher::stopBurst() throw() {
297 if (!a_burstActive) {
298 std::string msg = "Burst launch is already stopped. Nothing done";
299 std::cout << msg << std::endl;
300 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
304 a_burstActive = false;
305 // Remaining on cycle:
306 return (a_burstMessages.size() - (*a_burstDeliveryIt).first);
309 int Launcher::popBurst(int releaseAmount) throw() {
310 if (!a_burstActive) {
311 std::string msg = "Burst launch is stopped. Nothing done";
312 std::cout << msg << std::endl;
313 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
317 if (releaseAmount < 1) {
318 std::string msg = "No valid release amount is specified. Ignoring burst pop";
319 std::cout << msg << std::endl;
320 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
324 int currentOTArequests = a_entity->getOTARequests();
325 a_burstPopCounter = (releaseAmount > currentOTArequests) ? currentOTArequests : releaseAmount;
326 return a_burstPopCounter;
329 int Launcher::pushBurst(int loadAmount) throw() {
330 if (a_burstMessages.size() == 0) {
331 std::string msg = "Burst data not found (empty list). Ignoring burst launch";
332 std::cout << msg << std::endl;
333 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
337 if (loadAmount < 1) {
338 std::string msg = "No valid load amount is specified. Ignoring burst push";
339 std::cout << msg << std::endl;
340 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
344 a_burstActive = true;
347 for (count = 0; count < loadAmount; count++)
348 if (!sendBurstMessage()) break;
354 int Launcher::sendBurst(int loadAmount) throw() {
355 if (a_burstMessages.size() == 0) {
356 std::string msg = "Burst data not found (empty list). Ignoring burst launch";
357 std::cout << msg << std::endl;
358 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
362 if (loadAmount < 1) {
363 std::string msg = "No valid load amount is specified. Ignoring burst send";
364 std::cout << msg << std::endl;
365 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
371 for (count = 0; count < loadAmount; count++)
372 if (!sendBurstMessage(true /* anyway */)) break;
379 int Launcher::startBurst(int initialLoad) throw() {
380 if (initialLoad < 1) {
381 std::string msg = "No initial load is specified. Ignoring burst start";
382 std::cout << msg << std::endl;
383 LOGWARNING(anna::Logger::warning(msg, ANNA_FILE_LOCATION));
387 a_burstActive = true;
389 a_burstDeliveryIt = a_burstMessages.begin();
390 return (pushBurst(initialLoad));
393 bool Launcher::sendBurstMessage(bool anyway) throw() {
394 if (!anyway && !burstActive()) return false;
396 if (a_burstPopCounter > 0) {
397 if (burstLogEnabled()) writeBurstLogFile("x");
403 if (a_burstDeliveryIt == a_burstMessages.end()) {
404 a_burstDeliveryIt = a_burstMessages.begin();
410 if (burstLogEnabled()) writeBurstLogFile(anna::functions::asString(("\nCompleted burst cycle. Starting again (repeat mode) on cycle %d.\n", a_burstCycle)));
412 if (burstLogEnabled()) writeBurstLogFile("\nCompleted burst cycle. Burst finished (repeat mode disabled).\n");
420 anna::diameter::comm::Message *msg = (*a_burstDeliveryIt).second;
421 int order = (*a_burstDeliveryIt).first + 1;
425 bool result = a_entity->send(msg, anna::CommandLine::instantiate().exists("balance"));
427 if (burstLogEnabled()) {
428 if (a_burstMessages.size() >= 100)
429 dot = (order % (a_burstMessages.size() / 100));
432 writeBurstLogFile(".");
434 writeBurstLogFile(anna::functions::asString(" %d", order));
435 int otaReqs = a_entity->getOTARequests();
437 if (result && (otaReqs != a_otaRequest)) {
438 // false if was a sending after an answer received (no OTA change in this case)
439 // true after push and pop operations
440 a_otaRequest = otaReqs;
441 writeBurstLogFile(anna::functions::asString("[OTA %d]", a_otaRequest));
448 anna::diameter::comm::Server *usedServer = a_entity->getLastUsedResource();
449 anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
450 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
451 writeLogFile(msg->getBody(), (result ? "sent2e" : "send2eError"), detail);
458 std::string Launcher::lookBurst(int order) const throw() {
459 std::string result = "No message found for order provided (";
460 result += anna::functions::asString(order);
462 std::map<int, anna::diameter::comm::Message*>::const_iterator it = a_burstMessages.find(order - 1);
464 if (it != a_burstMessages.end()) {
466 try { G_codecMsg.decode((*it).second->getBody()); } catch (anna::RuntimeException &ex) { ex.trace(); }
468 result = G_codecMsg.asXMLString();
474 std::string Launcher::gotoBurst(int order) throw() {
475 std::string result = "Position not found for order provided (";
476 std::map<int, anna::diameter::comm::Message*>::iterator it = a_burstMessages.find(order - 1);
478 if (it != a_burstMessages.end()) {
479 a_burstDeliveryIt = it;
480 result = "Position updated for order provided (";
483 result += anna::functions::asString(order);
488 ////////////////////////////////////////////////////
491 void Launcher::resetCounters() throw() {
492 // Diameter::comm module:
493 anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
494 oamDiameterComm.resetCounters();
497 std::string Launcher::help() const throw() {
498 std::string result = "\n";
499 result += "\n ------------- HELP -------------\n";
500 result += "\nThe Diameter Launcher process is a complete diameter agent with client and server";
501 result += "\ncapabilities as well as balancer (proxy) features. It could be used as diameter server";
502 result += "\n(i.e. to simulate PCRF nodes, OCS systems, etc.), as diameter client (GGSNs, DPIs, etc.)";
503 result += "\nand balancer systems to provide failover to external round-robin launchers). Also, auxiliary";
504 result += "\nencoder/decoder/loader function could be deployed to reinterpret certain external flow and";
505 result += "\nsend it to another process.";
507 result += "\nAs any other ANNA process, context dump could be retrieved sending -10 signal:";
508 result += "\n kill -10 <pid> ; vi /var/tmp/anna.context.<pid>";
510 result += "\nA complete xml report will show all the context information (counters, alarms, statistics,";
511 result += "\nhandlers, diameter dictionary, etc.), and a powerful log module could dump all the events";
512 result += "\nprocessed and flow information. Statistics could be analized at context dump and optionally";
513 result += "\nwritten to disk as sample files with all the events measurements.";
515 result += "\nProcess traces are dump on \"launcher.traces\" and could have any trace level (POSIX levels):";
516 result += "\nusually 'debug' or 'warning'. See ANNA documentation.";
518 result += "\nThe ANNA::diameter built-in module provide a great set of characteristics as multiple connections";
519 result += "\non both server and client side, definition for multiple-server entities (and not only two as standard";
520 result += "\nestablish as minimum), separate statistics analyzer per each resource, automatic CER/CEA and DWR/DWA";
521 result += "\ngeneration, expiration control and many more features";
523 result += "\nOPERATIONS INTERFACE";
525 result += "\nNDL supports several operations via HTTP interface. The HTTP request body content will";
526 result += "\nbe an string with a command:";
528 result += "\nFor example, we could launch an operation via curl:";
530 result += "\n curl -m 1 --data \"diameterServerSessions|4\" localhost:9000";
531 result += "\n curl -m 1 --data \"code|ccr.xml\" localhost:9000";
532 result += "\n curl -m 1 --data \"decode|ccr.hex\" localhost:9000";
533 result += "\n curl -m 1 --data \"sendxml2e|ccr.xml\" localhost:9000";
536 result += "\nThese are the available commands:";
539 result += "\nGeneral -----------------------------";
541 result += "\nhelp This help. Startup information-level traces also dump this help.";
543 result += "\nParsing operations ------------------";
545 result += "\ncode|<source_file>|<target_file> Encodes source file (pathfile) into target file (pathfile).";
546 result += "\ndecode|<source_file>|<target_file> Decodes source file (pathfile) into target file (pathfile).";
547 result += "\nloadxml|<source_file> Reinterpret xml source file (pathfile).";
549 result += "\nHot changes -------------------------";
551 result += "\ndiameterServerSessions|<integer> Updates the maximum number of accepted connections to diameter server socket.";
552 result += "\ncollect Reset statistics and counters to start a new test stage of performance measurement.";
553 result += "\n Context data is written at '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'.";
555 result += "\n<visibility action>|[<address>:<port>]|[socket id]";
557 result += "\n Actions: hide, show (update state) and hidden, shown (query state).";
558 result += "\n Acts over a client session for messages delivery (except CER/A, DWR/A, DPR/A).";
559 result += "\n If missing server (first parameter) all applications sockets will be affected.";
560 result += "\n If missing socket (second parameter) for specific server, all its sockets will be affected.";
562 result += "\n All application client sessions are shown on startup, but standard delivery only use primary server ones except if fails.";
563 result += "\n Balance configuration use all the allowed sockets. You could also use command line 'sessionBasedModelsClientSocketSelection'";
564 result += "\n to force traffic flow over certain client sessions, but for this, hide/show feature seems easier.";
566 result += "\nFlow operations ---------------------";
568 result += "\nsendxml2e|<source_file> Sends xml source file (pathfile) through configured diameter entity.";
569 result += "\nsendxml2c|<source_file> Sends xml source file (pathfile) to diameter client.";
570 result += "\nsendxml|<source_file> Same as 'sendxml2e'.";
571 result += "\nanswerxml2e|[source_file] Answer xml source file (pathfile) for corresponding request from diameter entity.";
572 result += "\nanswerxml2c|[source_file] Answer xml source file (pathfile) for corresponding request from diameter client.";
573 result += "\nanswerxml|[source_file] Same as 'answerxml2c'.";
574 result += "\n List programmed answers if no parameter provided.";
576 result += "\nIf a request is received, answer map (built with 'answerxml<[2c] or 2e>' operations) will be checked to find";
577 result += "\na corresponding programmed answer to be replied(*). If no ocurrence is found, or answer message was received,";
578 result += "\nthe message is forwarded to the other side (entity or client), or nothing but trace when no peer at that side";
579 result += "\nis configured. Answer to client have sense when diameter server socket is configured, answer to entity have";
580 result += "\nsense when entity does.";
582 result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored to the";
583 result += "\n peer which sent the request. If user wants to test a specific answer without changing it, use sendxml";
584 result += "\n operations better than programming.";
586 result += "\nBalance ('-balance' command line parameter) could be used to forward server socket receptions through entity servers";
587 result += "\nby mean a round-robin algorithm. Both diameter server socket and entity targets should have been configured, that is";
588 result += "\nto say: launcher acts as client and server. If no balance is used, an standard delivery is performed: first primary";
589 result += "\nentity server, secondary when fails, etc.";
591 result += "\nProcessing types --------------------";
593 result += "\nUsed as log file extensions (when '-splitLog' is provided on command line) and context preffixes on log details when";
594 result += "\nunique log file is dumped:";
596 result += "\n [sent2e/send2eError] Send to entity (success/error)";
597 result += "\n [sent2c/send2cError] Send to client (success/error)";
598 result += "\n [fwd2e/fwd2eError] Forward to entity a reception from client (success/error)";
599 result += "\n [fwd2c/fwd2cError] Forward to client a reception from entity (success/error)";
600 result += "\n [recvfc] Reception from client";
601 result += "\n [recvfe] Reception from entity";
602 result += "\n [req2c-expired] A request sent to client has been expired";
603 result += "\n [req2e-expired] A request sent to entity has been expired";
604 result += "\n [recvfc-ans-unknown] Reception from client of an unknown answer (probably former [req2c-expired] has been logged)";
605 result += "\n [recvfe-ans-unknown] Reception from entity of an unknown answer (probably former [req2e-expired] has been logged)";
607 result += "\nLoad tests --------------------------";
609 result += "\nburst|<action>|[parameter] Used for performance testing, we first program diameter requests messages in order";
610 result += "\n to launch them from client side to the configured diameter entity. We could start";
611 result += "\n the burst with an initial load (non-asynchronous sending), after this, a new request";
612 result += "\n will be sent per answer received or expired context. There are 10 actions: clear, load";
613 result += "\n start, push, pop, stop, repeat, send, goto and look.";
615 result += "\n burst|clear clears all loaded burst messages.";
616 result += "\n burst|load|<source_file> loads the next diameter message into launcher burst.";
617 result += "\n burst|start|<initial load> starts (or restarts if already in progress) the message sending with a certain initial load.";
618 result += "\n burst|push|<load amount> sends specific non-aynchronous load.";
619 result += "\n burst|pop|<release amount> skip send burst messages in order to reduce over-the-air requests. Popping all OTA requests";
620 result += "\n implies burst stop because no more answer will arrive to the process. Burst output file";
621 result += "\n (-burstLog command line parameter) shows popped messages with crosses (x). Each cross";
622 result += "\n represents one received answer for which no new request is sent.";
623 result += "\n burst|stop stops the burst cycle. You can resume pushing 1 load amount.";
624 result += "\n burst|repeat|[[yes]|no] restarts the burst launch when finish. If initial load or push load amount is";
625 result += "\n greater than burst list size, they will be limited when the list is processed";
626 result += "\n except when repeat mode is enabled.";
627 result += "\n burst|send|<amount> send messages from burst list. The main difference with start/push operations is that burst";
628 result += "\n won't be awaken. Externally we could control sending time (no request will be sent for answers).";
629 result += "\n burst|goto|<order> Updates current burst pointer position.";
630 result += "\n burst|look|<order> Show programmed burst message for order provided.";
637 std::string Launcher::programmedAnswers2c() const throw() {
638 std::string result = "\n";
639 result += "\n ------------- CURRENT PROGRAMMED ANSWERS TO CLIENT -------------\n\n";
641 if (G_reactingAnswers2C.size() == 0) {
642 result += "No ocurrences found\n\n";
644 for (reacting_answers_const_iterator it = G_reactingAnswers2C.begin(); it != G_reactingAnswers2C.end(); it++) {
645 result += (*it).second->asXMLString();
654 std::string Launcher::programmedAnswers2e() const throw() {
655 std::string result = "\n";
656 result += "\n\n ------------- CURRENT PROGRAMMED ANSWERS TO ENTITY -------------\n\n";
658 if (G_reactingAnswers2E.size() == 0) {
659 result += "No ocurrences found\n\n";
661 for (reacting_answers_const_iterator it = G_reactingAnswers2E.begin(); it != G_reactingAnswers2E.end(); it++) {
662 result += (*it).second->asXMLString();
670 void MyCommunicator::prepareAnswer(anna::diameter::codec::Message *answer, const anna::DataBlock &request) const throw() {
671 // Sequence values (hop-by-hop and end-to-end), session-id and subscription-id avps, are mirrored to the peer which sent the request.
672 // If user wants to test a specific answer without changing it, use send operations better than programming.
673 // Sequence substitution:
674 answer->setHopByHop(anna::diameter::codec::functions::getHopByHop(request));
675 answer->setEndToEnd(anna::diameter::codec::functions::getEndToEnd(request));
677 // Session-Id substitution:
679 std::string sessionId = anna::diameter::helpers::base::functions::getSessionId(request);
681 std::string msg = "Extracted Session-Id: ";
683 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
685 answer->getAvp("Session-Id")->getUTF8String()->setValue(sessionId);
686 } catch (anna::RuntimeException &ex) {
690 // Subscription-Id substitution: is not usual to carry Subscription-Id on answer messages, but if programmed answer have this information,
691 // then it will be adapted with the received data at request.
692 if (answer->countAvp("Subscription-Id") > 0) {
693 std::string msisdn = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
694 std::string imsi = anna::diameter::helpers::dcca::functions::getSubscriptionIdData(request, anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
696 if ((msisdn != "") || (imsi != "")) { // Both request & answer have SID: replace answer one with the request information:
697 answer->removeAvp("Subscription-Id", 0 /* remove all */);
702 anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id");
703 sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_E164);
704 sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(msisdn);
708 anna::diameter::codec::Avp *sid = answer->addAvp("Subscription-Id"); // another
709 sid->addAvp("Subscription-Id-Type")->getEnumerated()->setValue(anna::diameter::helpers::dcca::AVPVALUES__Subscription_Id_Type::END_USER_IMSI);
710 sid->addAvp("Subscription-Id-Data")->getUTF8String()->setValue(imsi);
716 void MyCommunicator::eventReceiveMessage(anna::comm::ClientSocket& clientSocket, const anna::comm::Message& message)
717 throw(anna::RuntimeException) {
718 LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventReceiveMessage", ANNA_FILE_LOCATION));
720 if (clientSocket.support(anna::http::Transport::className()) == false)
723 MyHandler& httpHandler = a_contexts.get();
724 httpHandler.apply(clientSocket, message);
728 using namespace anna::diameter;
730 int main(int argc, const char** argv) {
731 anna::Logger::setLevel(anna::Logger::Warning);
732 anna::Logger::initialize("launcher", new TraceWriter("launcher.traces", 2048000));
733 anna::time::functions::initialize(); // before application instantiation (it have a anna::time object)
734 anna::time::functions::setControlPoint(); // start control point (application lifetime)
736 anna::http::functions::initialize();
739 CommandLine& commandLine(anna::CommandLine::instantiate());
741 commandLine.add("trace", anna::CommandLine::Argument::Optional, "Trace level (emergency, alert, critical, error, warning, notice, information, debug, local0..local7)");
742 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)");
743 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);
744 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);
745 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).");
746 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.");
748 commandLine.add("httpServer", anna::CommandLine::Argument::Mandatory, "HTTP Management interface address (using i.e. curl tool) in '<address>:<port>' format. For example: 10.20.30.40:8080");
749 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);
750 commandLine.add("diameterServer", anna::CommandLine::Argument::Optional, "Diameter own server address in '<address>:<port>' format. For example: 10.20.30.40:3868");
751 commandLine.add("diameterServerSessions", anna::CommandLine::Argument::Optional, "Diameter own server available connections (0: diameter server disabled). Default value of 1");
752 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");
753 commandLine.add("entityServerSessions", anna::CommandLine::Argument::Optional, "Diameter entity server sessions (0: diameter entity disabled). Default value of 1");
754 commandLine.add("balance", anna::CommandLine::Argument::Optional, "Balance over entity servers instead of doing standard behaviour (first primary, secondary if fails, etc.)", false);
755 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'.");
756 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");
757 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);
758 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);
759 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");
760 commandLine.add("tcpConnectDelay", anna::CommandLine::Argument::Optional, "Milliseconds to wait TCP connect to any server. If missing, default value of 200 will be assigned");
761 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");
762 commandLine.add("ceaTimeout", anna::CommandLine::Argument::Optional, "Milliseconds to wait CEA from diameter server. If missing, default value of 'answersTimeout' will be assigned");
763 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");
764 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");
765 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");
766 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");
767 commandLine.add("originHost", anna::CommandLine::Argument::Optional, "Diameter application host name (system name). If missing, process sets o.s. hostname");
768 commandLine.add("originRealm", anna::CommandLine::Argument::Optional, "Diameter application node realm name. If missing, process sets domain name");
769 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);
770 // commandLine.add("clone", anna::CommandLine::Argument::Optional, "Enables fork mode for request processing", false);
771 commandLine.initialize(argv, argc);
772 commandLine.verify();
773 std::cout << commandLine.asString() << std::endl;
775 } catch (Exception& ex) {
776 cout << ex.asString() << endl;
782 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
783 a_myDiameterEngine = new MyDiameterEngine();
784 a_myDiameterEngine->setRealm("NDL.ericsson.com");
785 a_myDiameterEngine->setAutoBind(false); // allow to create client-sessions without binding them, in order to set timeouts.
786 //a_myDiameterEngine->setFreezeEndToEndOnSending();
787 a_logFile = "launcher.log";
788 a_burstLogFile = "launcher.burst";
790 a_detailedLog = false;
792 a_counterRecorder = NULL;
794 a_diameterLocalServer = NULL;
795 a_cerPathfile = "cer.xml";
796 a_dwrPathfile = "dwr.xml";
799 a_burstRepeat = false;
800 a_burstActive = false;
801 //a_burstMessages.clear();
803 a_burstDeliveryIt = a_burstMessages.begin();
805 a_burstPopCounter = 0;
808 void Launcher::baseProtocolSetupAsClient(void) throw(anna::RuntimeException) {
810 // <CER> ::= < Diameter Header: 257, REQ >
811 // { Origin-Host } 264 diameterIdentity
812 // { Origin-Realm } 296 idem
813 // 1* { Host-IP-Address } 257, address
814 // { Vendor-Id } 266 Unsigned32
815 // { Product-Name } 269 UTF8String
816 // [Origin-State-Id] 278 Unsigned32
817 // * [ Supported-Vendor-Id ] 265 Unsigned32
818 // * [ Auth-Application-Id ] 258 Unsigned32
819 // * [Acct-Application-Id] 259 Unsigned32
820 anna::diameter::codec::Message diameterCER;
821 int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
822 std::string OH = a_myDiameterEngine->getHost();
823 std::string OR = a_myDiameterEngine->getRealm();
824 std::string hostIP = anna::functions::getHostnameIP(); // Address
825 int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
826 std::string productName = "ANNA Diameter Launcher"; // UTF8String
827 bool loadingError = false;
830 diameterCER.loadXML(a_cerPathfile);
831 } catch (anna::RuntimeException &ex) {
837 LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
838 diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
839 diameterCER.setApplicationId(applicationId);
840 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
841 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
842 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>"
843 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
844 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
845 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
849 // <DWR> ::= < Diameter Header: 280, REQ >
852 anna::diameter::codec::Message diameterDWR;
853 loadingError = false;
856 diameterDWR.loadXML(a_dwrPathfile);
857 } catch (anna::RuntimeException &ex) {
863 LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
864 diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
865 diameterDWR.setApplicationId(applicationId);
866 diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
867 diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
870 //////////////////////////
871 // IDEM FOR CEA AND DWA //
872 //////////////////////////
874 // // <CER> ::= < Diameter Header: 257, REQ >
875 // // { Origin-Host } 264 diameterIdentity
876 // // { Origin-Realm } 296 idem
877 // // 1* { Host-IP-Address } 257, address
878 // // { Vendor-Id } 266 Unsigned32
879 // // { Product-Name } 269 UTF8String
880 // // [Origin-State-Id] 278 Unsigned32
881 // // * [ Supported-Vendor-Id ] 265 Unsigned32
882 // // * [ Auth-Application-Id ] 258 Unsigned32
883 // // * [Acct-Application-Id] 259 Unsigned32
884 // anna::diameter::codec::Message diameterCER;
885 // int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
886 // std::string OH = a_myDiameterEngine->getHost();
887 // std::string OR = a_myDiameterEngine->getRealm();
888 // std::string hostIP = anna::functions::getHostnameIP(); // Address
889 // int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
890 // std::string productName = "ANNA Diameter Launcher"; // UTF8String
891 // bool loadingError = false;
894 // diameterCER.loadXML("cer.xml");
895 // } catch (anna::RuntimeException &ex) {
897 // loadingError = true;
900 // if (loadingError) {
901 // LOGWARNING(anna::Logger::warning("CER file not found. Get harcoded.", ANNA_FILE_LOCATION));
902 // diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
903 // diameterCER.setApplicationId(applicationId);
904 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
905 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
906 // 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>"
907 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
908 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
909 // diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
913 // // <DWR> ::= < Diameter Header: 280, REQ >
914 // // { Origin-Host }
915 // // { Origin-Realm }
916 // anna::diameter::codec::Message diameterDWR;
917 // loadingError = false;
920 // diameterDWR.loadXML("dwr.xml");
921 // } catch (anna::RuntimeException &ex) {
923 // loadingError = true;
926 // if (loadingError) {
927 // LOGWARNING(anna::Logger::warning("DWR file not found. Get harcoded.", ANNA_FILE_LOCATION));
928 // diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
929 // diameterDWR.setApplicationId(applicationId);
930 // diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
931 // diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
933 // Assignment for CER/DWR and CEA/DWA:
934 a_myDiameterEngine->setCERandDWR(diameterCER.code(), diameterDWR.code());
935 //a_myDiameterEngine->setCEAandDWA(diameterCEA.code(), diameterDWA.code());
938 void Launcher::writeLogFile(const anna::DataBlock & db, const std::string &logExtension, const std::string &detail) const throw() {
939 // if (!logEnabled()) return;
942 try { G_codecMsg.decode(db); } catch (anna::RuntimeException &ex) { ex.trace(); }
944 writeLogFile(G_codecMsg, logExtension, detail);
948 // Si ya lo tengo decodificado:
949 void Launcher::writeLogFile(const anna::diameter::codec::Message & decodedMessage, const std::string &logExtension, const std::string &detail) const throw() {
950 // if (!logEnabled()) return;
952 std::string targetFile = a_logFile;
956 targetFile += logExtension;
959 ofstream out(targetFile.c_str(), ifstream::out | ifstream::app);
961 std::string title = "[";
962 title += logExtension;
964 // Build complete log:
965 std::string log = "\n";
968 anna::time::Date now;
971 title += now.asString();
972 log += anna::functions::highlight(title, anna::functions::TextHighlightMode::OverAndUnderline);
973 log += decodedMessage.asXMLString();
975 log += anna::functions::highlight("Used resource");
981 log += decodedMessage.asXMLString();
986 out.write(log.c_str(), log.size());
991 void Launcher::writeBurstLogFile(const std::string &buffer) throw() {
992 ofstream out(a_burstLogFile.c_str(), ifstream::out | ifstream::app);
993 out.write(buffer.c_str(), buffer.size());
994 out.close(); // close() will be called when the object is destructed (i.e., when it goes out of scope).
995 // you'd call close() only if you indeed for some reason wanted to close the filestream
996 // earlier than it goes out of scope.
1000 void Launcher::checkTimeMeasure(const char * commandLineParameter, bool optional) throw(anna::RuntimeException) {
1001 CommandLine& cl(anna::CommandLine::instantiate());
1003 if (!cl.exists(commandLineParameter) && optional) return; // si fuese obligatorio daria error de arranque.
1005 std::string parameter = cl.getValue(commandLineParameter);
1007 if (anna::functions::isLike("^[0-9]+$", parameter)) { // para incluir numeros decimales: ^[0-9]+(.[0-9]+)?$
1008 int msecs = cl.getIntegerValue(commandLineParameter);
1010 if (msecs > a_timeEngine->getMaxTimeout()) {
1011 std::string msg = "Commandline parameter '";
1012 msg += commandLineParameter;
1013 msg += "' is greater than allowed max timeout for timming engine: ";
1014 msg += anna::functions::asString(a_timeEngine->getMaxTimeout());
1015 throw RuntimeException(msg, ANNA_FILE_LOCATION);
1018 if (msecs <= a_timeEngine->getResolution()) {
1019 std::string msg = "Commandline parameter '";
1020 msg += commandLineParameter;
1021 msg += "' (and in general, all time measures) must be greater than timming engine resolution: ";
1022 msg += anna::functions::asString(a_timeEngine->getResolution());
1023 throw RuntimeException(msg, ANNA_FILE_LOCATION);
1029 // Excepcion (por no ser entero):
1030 std::string msg = "Error at commandline parameter '";
1031 msg += commandLineParameter;
1034 msg += "': must be a non-negative integer number";
1035 throw RuntimeException(msg, ANNA_FILE_LOCATION);
1039 void Launcher::startDiameterServer(int diameterServerSessions) throw(anna::RuntimeException) {
1040 if (diameterServerSessions <= 0) return;
1042 std::string address;
1044 CommandLine& cl(anna::CommandLine::instantiate());
1045 anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("diameterServer"), address, port);
1046 //ServerSocket *createServerSocket(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, int category = 1, const std::string & description = "")
1047 a_diameterLocalServer = a_myDiameterEngine->createLocalServer(address, port, diameterServerSessions);
1048 a_diameterLocalServer->setDescription("Launcher diameter local server");
1049 int allowedInactivityTime = 90000; // ms
1051 if (cl.exists("allowedInactivityTime")) allowedInactivityTime = cl.getIntegerValue("allowedInactivityTime");
1053 a_diameterLocalServer->setAllowedInactivityTime((anna::Millisecond)allowedInactivityTime);
1057 void Launcher::initialize()
1058 throw(anna::RuntimeException) {
1059 anna::comm::Application::initialize();
1060 CommandLine& cl(anna::CommandLine::instantiate());
1061 anna::comm::Communicator::WorkMode::_v workMode(anna::comm::Communicator::WorkMode::Single);
1062 // if (cl.exists ("clone"))
1063 // workMode = anna::comm::Communicator::WorkMode::Clone;
1064 a_communicator = new MyCommunicator(workMode);
1065 a_timeEngine = new anna::timex::Engine((anna::Millisecond)300000, (anna::Millisecond)150);
1066 a_counterRecorder = new MyCounterRecorder();
1069 void Launcher::run()
1070 throw(anna::RuntimeException) {
1071 LOGMETHOD(anna::TraceMethod tm("Launcher", "run", ANNA_FILE_LOCATION));
1072 CommandLine& cl(anna::CommandLine::instantiate());
1074 a_start_time.setCurrent();
1076 anna::statistics::Engine::instantiate().enable();
1077 ///////////////////////////////
1078 // Diameter library COUNTERS //
1079 ///////////////////////////////
1080 anna::diameter::comm::OamModule & oamDiameterComm = anna::diameter::comm::OamModule::instantiate();
1081 oamDiameterComm.initializeCounterScope(1); // 1000 - 1999
1082 anna::diameter::codec::OamModule & oamDiameterCodec = anna::diameter::codec::OamModule::instantiate();
1083 oamDiameterCodec.initializeCounterScope(2); // 2000 - 2999
1088 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceived, "" /* get defaults for enum type*/, 0 /*1000*/);
1089 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceived, "", 1 /*1001*/);
1090 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnClientSession, "", 2 /*1002*/);
1091 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSession, "", 3 /*1003*/);
1092 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestReceivedOnServerSession, "", 4 /* etc. */);
1093 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSession, "", 5);
1094 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOK, "", 6);
1095 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentNOK, "", 7);
1096 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOK, "", 8);
1097 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentNOK, "", 9);
1098 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionOK, "", 10);
1099 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionNOK, "", 11);
1100 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionOK, "", 12);
1101 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnClientSessionNOK, "", 13);
1102 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionOK, "", 14);
1103 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionNOK, "", 15);
1104 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionOK, "", 16);
1105 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerSentOnServerSessionNOK, "", 17);
1106 /* Diameter Base (capabilities exchange & keep alive) */
1108 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentOK, "", 18);
1109 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERSentNOK, "", 19);
1110 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEAReceived, "", 20);
1111 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentOK, "", 21);
1112 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRSentNOK, "", 22);
1113 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWAReceived, "", 23);
1114 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentOK, "", 24);
1115 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRSentNOK, "", 25);
1116 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPAReceived, "", 26);
1118 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CERReceived, "", 27);
1119 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentOK, "", 28);
1120 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CEASentNOK, "", 29);
1121 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWRReceived, "", 30);
1122 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentOK, "", 31);
1123 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DWASentNOK, "", 32);
1124 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPRReceived, "", 33);
1125 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentOK, "", 34);
1126 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::DPASentNOK, "", 35);
1127 /* server socket operations (enable/disable listening port for any local server) */
1128 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsOpened, "", 36);
1129 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::ServerSocketsClosed, "", 37);
1132 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverOverEntity, "", 38);
1133 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverClientSession, "", 39);
1134 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverClientSession, "", 40);
1135 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverServer, "", 41);
1136 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverServer, "", 42);
1137 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEntity, "", 43);
1138 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEntity, "", 44);
1139 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForEntities, "", 45);
1140 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForEntities, "", 46);
1142 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnableToDeliverToClient, "", 47);
1143 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostConnectionForServerSession, "", 48);
1144 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::UnbindConnectionForServerSessionDueToInactivityTimeAnomaly, "", 49);
1145 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::CreatedConnectionForServerSession, "", 50);
1146 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverLocalServer, "", 51);
1147 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverLocalServer, "", 52);
1148 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::LostAvailabilityOverEngineForLocalServers, "", 53);
1149 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers, "", 54);
1150 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentExpired, "", 55);
1151 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnClientSessionExpired, "", 56);
1152 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::RequestSentOnServerSessionExpired, "", 57);
1153 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedUnknown, "", 58);
1154 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnClientSessionUnknown, "", 59);
1155 oamDiameterComm.registerCounter(anna::diameter::comm::OamModule::Counter::AnswerReceivedOnServerSessionUnknown, "", 60);
1160 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__NotEnoughBytesToCoverAvpHeaderLength, "", 0 /*2000*/);
1161 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncoherenceBetweenActivatedVBitAndZeroedVendorIDValueReceived, "", 1 /*2001*/);
1162 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__IncorrectLength, "", 2 /*2002*/);
1163 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__DataPartInconsistence, "", 3 /*2003*/);
1164 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpDecode__UnknownAvpWithMandatoryBit, "", 4 /*2004*/);
1165 /* Message decoding */
1166 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageHeaderLength, "", 5 /*2005*/);
1167 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageDecode__NotEnoughBytesToCoverMessageLength, "", 6 /*2006*/);
1168 /* Avp validation */
1169 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__EnumeratedAvpWithValueDoesNotComplyRestriction, "", 10 /*2010*/);
1170 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::AvpValidation__AvpFlagsDoesNotFulfillTheDefinedFlagRules, "", 11 /*2011*/);
1171 /* Message validation */
1172 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__UnknownOperationUnableToValidate, "", 12 /*2012*/);
1173 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::MessageValidation__OperationHaveIncoherentFlags, "", 13 /*2013*/);
1174 /* Level validation */
1175 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__MissingFixedRule, "", 14 /*2014*/);
1176 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinality, "", 15 /*2015*/);
1177 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityLessThanNeeded, "", 16 /*2016*/);
1178 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedRuleForCardinalityMoreThanNeeded, "", 17 /*2017*/);
1179 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FailedGenericAvpRuleForCardinalityFoundDisregardedItem, "", 18 /*2018*/);
1180 oamDiameterCodec.registerCounter(anna::diameter::codec::OamModule::Counter::LevelValidation__FoundDisregardedItemsAndGenericAVPWasNotSpecified, "", 19 /*2019*/);
1181 anna::oam::CounterManager& cm = anna::oam::CounterManager::instantiate();
1182 cm.setEngine(a_timeEngine);
1183 cm.setRecordPeriod(Millisecond(300000));
1184 cm.setCounterRecorder(static_cast<anna::oam::CounterRecorder*>(a_counterRecorder));
1186 // Checking command line parameters
1187 if (cl.exists("sessionBasedModelsClientSocketSelection")) {
1188 std::string type = cl.getValue("sessionBasedModelsClientSocketSelection");
1190 if ((type != "SessionIdHighPart") && (type != "SessionIdOptionalPart") && (type != "RoundRobin")) {
1191 throw anna::RuntimeException("Commandline option '-sessionBasedModelsClientSocketSelection' only accepts 'SessionIdHighPart'/'SessionIdOptionalPart'/'RoundRobin' as parameter values", ANNA_FILE_LOCATION);
1196 if (cl.exists("trace"))
1197 anna::Logger::setLevel(anna::Logger::asLevel(cl.getValue("trace")));
1200 // Help on startup traces:
1201 anna::Logger::information(help(), ANNA_FILE_LOCATION);
1202 // Test messages dtd:
1203 std::string msg = "\n ------------- TESTMESSAGES DTD -------------\n";
1204 msg += anna::diameter::codec::MessageDTD;
1205 anna::Logger::information(msg, ANNA_FILE_LOCATION);
1208 anna::comm::Network& network = anna::comm::Network::instantiate();
1209 std::string address;
1211 anna::functions::getAddressAndPortFromSocketLiteral(cl.getValue("httpServer"), address, port);
1212 // const anna::comm::Device* device = network.find(Device::asAddress(address)); // aqui hay que proporcionar una IP !
1213 const anna::comm::Device* device = *((network.resolve(address)->device_begin())); // Artimaña para resolver (IP o hostname)
1214 a_httpServerSocket = new anna::comm::ServerSocket(anna::comm::INetAddress(device, port), cl.exists("httpServerShared") /* shared bind */, &anna::http::Transport::getFactory());
1216 anna::diameter::codec::Engine *codecEngine = new anna::diameter::codec::Engine();
1217 anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
1220 anna::diameter::stack::Dictionary * d = stackEngine.createDictionary(0 /* stack id */);
1221 // Analyze comma-separated list:
1222 anna::Tokenizer lst;
1223 std::string dictionaryParameter = cl.getValue("dictionary");
1224 lst.apply(dictionaryParameter, ",");
1226 if (lst.size() >= 1) { // always true (at least one, because -dictionary is mandatory)
1227 anna::Tokenizer::const_iterator tok_min(lst.begin());
1228 anna::Tokenizer::const_iterator tok_max(lst.end());
1229 anna::Tokenizer::const_iterator tok_iter;
1230 std::string pathFile;
1233 for (tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
1234 pathFile = anna::Tokenizer::data(tok_iter);
1239 codecEngine->setDictionary(d);
1240 LOGDEBUG(anna::Logger::debug(codecEngine->asString(), ANNA_FILE_LOCATION));
1241 } catch (anna::RuntimeException &ex) {
1245 // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
1246 // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
1247 if (cl.exists("integrationAndDebugging")) {
1248 codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
1249 codecEngine->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
1252 codecEngine->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
1255 if (cl.exists("diameterServer"))
1256 startDiameterServer(cl.exists("diameterServerSessions") ? cl.getIntegerValue("diameterServerSessions") : 1);
1258 // Optional command line parameters ////////////////////////////////////////////////////////
1259 checkTimeMeasure("allowedInactivityTime");
1260 checkTimeMeasure("tcpConnectDelay");
1261 checkTimeMeasure("answersTimeout");
1262 checkTimeMeasure("ceaTimeout");
1263 checkTimeMeasure("watchdogPeriod");
1264 checkTimeMeasure("reconnectionPeriod");
1265 int tcpConnectDelay = 200; // ms
1266 anna::Millisecond answersTimeout = (anna::Millisecond)10000; // ms
1267 anna::Millisecond ceaTimeout;
1268 anna::Millisecond watchdogPeriod = (anna::Millisecond)30000; // ms
1269 int reconnectionPeriod = 10000; // ms
1271 if (cl.exists("tcpConnectDelay")) tcpConnectDelay = cl.getIntegerValue("tcpConnectDelay");
1273 if (cl.exists("answersTimeout")) answersTimeout = cl.getIntegerValue("answersTimeout");
1275 if (cl.exists("ceaTimeout")) ceaTimeout = cl.getIntegerValue("ceaTimeout");
1276 else ceaTimeout = answersTimeout;
1278 if (cl.exists("watchdogPeriod")) watchdogPeriod = cl.getIntegerValue("watchdogPeriod");
1280 if (cl.exists("reconnectionPeriod")) reconnectionPeriod = cl.getIntegerValue("reconnectionPeriod");
1282 a_myDiameterEngine->setMaxConnectionDelay((anna::Millisecond)tcpConnectDelay);
1283 a_myDiameterEngine->setWatchdogPeriod(watchdogPeriod);
1284 std::string originHost = "";
1285 std::string originRealm = "";
1287 if (cl.exists("cer")) a_cerPathfile = cl.getValue("cer");
1289 if (cl.exists("dwr")) a_dwrPathfile = cl.getValue("dwr");
1291 if (cl.exists("originHost")) originHost = cl.getValue("originHost");
1293 if (cl.exists("originRealm")) originRealm = cl.getValue("originRealm");
1295 a_myDiameterEngine->setHost(originHost);
1296 a_myDiameterEngine->setRealm(originRealm);
1299 if (cl.exists("entity")) {
1300 int entityServerSessions = cl.exists("entityServerSessions") ? cl.getIntegerValue("entityServerSessions") : 1;
1302 if (entityServerSessions > 0) {
1303 baseProtocolSetupAsClient(); // Same CER/CEA, DWR/DWA for all diameter servers
1304 anna::socket_v servers = anna::functions::getSocketVectorFromString(cl.getValue("entity"));
1305 a_myDiameterEngine->setNumberOfClientSessionsPerServer(entityServerSessions);
1306 a_entity = a_myDiameterEngine->createEntity(servers, "Launcher diameter entity");
1307 a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::Bind, ceaTimeout);
1308 a_entity->setClassCodeTimeout(anna::diameter::comm::ClassCode::ApplicationMessage, answersTimeout);
1314 if (cl.exists("log")) a_logFile = cl.getValue("log");
1316 if (cl.exists("splitLog")) a_splitLog = true;
1318 if (cl.exists("detailedLog")) a_detailedLog = true;
1320 if (cl.exists("burstLog")) a_burstLogFile = cl.getValue("burstLog");
1322 // Log statistics concepts
1323 if (cl.exists("logStatisticSamples")) {
1324 std::string list = cl.getValue("logStatisticSamples");
1325 anna::statistics::Engine &statEngine = anna::statistics::Engine::instantiate();
1327 if (list == "all") {
1328 if (statEngine.enableSampleLog(/* -1: all concepts */))
1329 LOGDEBUG(anna::Logger::debug("Sample log activation for all statistic concepts", ANNA_FILE_LOCATION));
1331 anna::Tokenizer lst;
1332 lst.apply(cl.getValue("logStatisticSamples"), ",");
1334 if (lst.size() >= 1) {
1335 anna::Tokenizer::const_iterator tok_min(lst.begin());
1336 anna::Tokenizer::const_iterator tok_max(lst.end());
1337 anna::Tokenizer::const_iterator tok_iter;
1340 for (tok_iter = tok_min; tok_iter != tok_max; tok_iter++) {
1341 conceptId = atoi(anna::Tokenizer::data(tok_iter));
1343 if (statEngine.enableSampleLog(conceptId))
1344 LOGDEBUG(anna::Logger::debug(anna::functions::asString("Sample log activation for statistic concept id = %d", conceptId), ANNA_FILE_LOCATION));
1350 a_communicator->setRecoveryTime((const anna::Millisecond)reconnectionPeriod);
1351 a_communicator->attach(a_httpServerSocket); // HTTP
1352 a_communicator->accept();
1355 void MyCommunicator::eventBreakConnection(Server* server)
1357 LOGMETHOD(anna::TraceMethod tm("MyCommunicator", "eventBreakConnection", ANNA_FILE_LOCATION));
1359 anna::comm::Communicator::eventBreakConnection(server);
1362 void MyCommunicator::terminate()
1364 if (hasRequestedStop() == true)
1370 void MyHandler::evRequest(anna::comm::ClientSocket& clientSocket, const anna::http::Request& request)
1371 throw(anna::RuntimeException) {
1372 const anna::DataBlock& body = request.getBody();
1374 if (body.getSize() == 0)
1375 throw anna::RuntimeException("Missing operation parameters on HTTP request", ANNA_FILE_LOCATION);
1378 string msg("Received body: ");
1379 msg += anna::functions::asString(body);
1380 anna::Logger::information(msg, ANNA_FILE_LOCATION);
1382 std::string body_content;
1383 body_content.assign(body.getData(), body.getSize());
1385 std::string response_content;
1388 sendOperation(body_content, response_content);
1389 } catch (RuntimeException &ex) {
1393 anna::http::Response* response = allocateResponse();
1394 response->setStatusCode(200); // http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
1395 anna::DataBlock db_content(true);
1396 db_content = response_content;
1397 response->setBody(db_content);
1398 // response->find(anna::http::Header::Type::Date)->setValue("Mon, 30 Jan 2006 14:36:18 GMT");
1399 // anna::http::Header* keepAlive = response->find("Keep-Alive");
1401 // if (keepAlive == NULL)
1402 // keepAlive = response->createHeader("Keep-Alive");
1404 // keepAlive->setValue("Verificacion del cambio 1.0.7");
1407 clientSocket.send(*response);
1408 } catch (Exception& ex) {
1413 void MyHandler::sendOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
1414 LOGMETHOD(anna::TraceMethod tm("MyHandler", "sendOperation", ANNA_FILE_LOCATION));
1415 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
1416 CommandLine& cl(anna::CommandLine::instantiate());
1417 LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION));
1418 response_content = "Operation processed with exception. See traces\n"; // supposed
1419 std::string result = "";
1422 if (operation == "help") {
1423 std::cout << my_app.help() << std::endl;
1424 response_content = "Help dumped on stdout and information-level traces (launcher.traces file)\n";
1428 // Reset performance data:
1429 if (operation == "collect") {
1430 my_app.resetCounters();
1431 my_app.resetStatistics();
1432 response_content = "All process counters & statistic information have been reset\n";
1436 // Tokenize operation
1438 params.apply(operation, "|");
1439 int numParams = params.size() - 1;
1440 //LOGDEBUG(anna::Logger::debug(anna::functions::asString("Number of operation parameters: %d", numParams), ANNA_FILE_LOCATION));
1442 if (numParams > 2) {
1443 LOGWARNING(anna::Logger::warning(my_app.help(), ANNA_FILE_LOCATION));
1444 throw anna::RuntimeException("Wrong body content format on HTTP Request", ANNA_FILE_LOCATION);
1447 Tokenizer::const_iterator tok_iter = params.begin();
1448 std::string opType = Tokenizer::data(tok_iter);
1449 std::string param1, param2;
1451 if (numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
1453 if (numParams == 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
1455 if (opType == "code") {
1457 throw anna::RuntimeException("Wrong body content format on HTTP Request for 'code' operation (missing parameter/s)", ANNA_FILE_LOCATION);
1459 G_codecMsg.loadXML(param1);
1460 std::string hexString = anna::functions::asHexString(G_codecMsg.code());
1462 ofstream outfile(param2.c_str(), ifstream::out);
1463 outfile.write(hexString.c_str(), hexString.size());
1465 } else if (opType == "decode") {
1467 throw anna::RuntimeException("Wrong body content format on HTTP Request for 'decode' operation (missing parameter/s)", ANNA_FILE_LOCATION);
1470 ifstream infile(param1.c_str(), ifstream::in);
1472 std::string hexString(buffer, strlen(buffer));
1473 anna::DataBlock db(true);
1474 anna::functions::fromHexString(hexString, db);
1477 try { G_codecMsg.decode(db); } catch (anna::RuntimeException &ex) { ex.trace(); }
1479 std::string xmlString = G_codecMsg.asXMLString();
1481 ofstream outfile(param2.c_str(), ifstream::out);
1482 outfile.write(xmlString.c_str(), xmlString.size());
1485 } else if ((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
1486 anna::diameter::comm::Entity *entity = my_app.getEntity();
1488 if (!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
1492 std::string key = param1;
1496 if (opType == "hide") my_app.getMyDiameterEngine()->findClientSession(key)->hide();
1498 if (opType == "show") my_app.getMyDiameterEngine()->findClientSession(key)->show();
1500 if (opType == "hidden") result = my_app.getMyDiameterEngine()->findClientSession(key)->hidden() ? "true" : "false";
1502 if (opType == "shown") result = my_app.getMyDiameterEngine()->findClientSession(key)->shown() ? "true" : "false";
1504 std::string address;
1506 anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
1508 if (opType == "hide") my_app.getMyDiameterEngine()->findServer(address, port)->hide();
1510 if (opType == "show") my_app.getMyDiameterEngine()->findServer(address, port)->show();
1512 if (opType == "hidden") result = my_app.getMyDiameterEngine()->findServer(address, port)->hidden() ? "true" : "false";
1514 if (opType == "shown") result = my_app.getMyDiameterEngine()->findServer(address, port)->shown() ? "true" : "false";
1517 if (opType == "hide") entity->hide();
1519 if (opType == "show") entity->show();
1521 if (opType == "hidden") result = entity->hidden() ? "true" : "false";
1523 if (opType == "shown") result = entity->shown() ? "true" : "false";
1525 } else if ((opType == "sendxml") || (opType == "sendxml2e")) {
1527 throw anna::RuntimeException("Wrong body content format on HTTP Request for 'sendxml/sendxml2e' operation (missing parameter)", ANNA_FILE_LOCATION);
1529 anna::diameter::comm::Entity *entity = my_app.getEntity();
1531 if (!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
1533 G_codecMsg.loadXML(param1);
1534 G_commMsgSent2e.clearBody();
1535 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)
1537 G_commMsgSent2e.setBody(G_codecMsg.code());
1538 bool success = entity->send(G_commMsgSent2e, cl.exists("balance"));
1541 if (my_app.logEnabled()) {
1542 anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
1543 anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
1544 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
1545 my_app.writeLogFile(G_codecMsg, (success ? "sent2e" : "send2eError"), detail);
1547 } else if ((opType == "burst")) {
1549 throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (missing action parameter)", ANNA_FILE_LOCATION);
1551 anna::diameter::comm::Entity *entity = my_app.getEntity();
1553 if (!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION);
1555 // burst|clear clears all loaded burst messages.
1556 // burst|load|<source_file> loads the next diameter message into launcher burst.
1557 // burst|start|<initial load> starts the message sending with a certain initial load.
1558 // burst|push|<load amount> sends specific non-aynchronous load.
1559 // burst|stop stops the burst cycle.
1560 // burst|repeat|[[yes]|no] restarts the burst launch when finish.
1561 // burst|send|<amount> send messages from burst list. The main difference with
1562 // start/push operations is that burst won't be awaken.
1563 // Externally we could control sending time (no request
1564 // will be sent for answers).
1565 // burst|goto|<order> Updates current burst pointer position.
1566 // burst|look|<order> Show programmed burst message for order provided.
1568 if (param1 == "clear") {
1569 result = "Removed ";
1570 result += anna::functions::asString(my_app.clearBurst());
1571 result += " elements.";
1572 } else if (param1 == "load") {
1573 if (param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
1575 G_codecMsg.loadXML(param2);
1577 if (G_codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
1578 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)
1580 int position = my_app.loadBurstMessage(G_codecMsg.code());
1581 result = "Loaded '";
1583 result += "' file into burst list position ";
1584 result += anna::functions::asString(position);
1585 } else if (param1 == "start") {
1586 if (param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
1588 int initialLoad = atoi(param2.c_str());
1589 int processed = my_app.startBurst(initialLoad);
1591 if (processed > 0) {
1592 result = "Initial load completed for ";
1593 result += anna::functions::entriesAsString(processed, "message");
1596 } else if (param1 == "push") {
1597 if (param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
1599 int pushed = my_app.pushBurst(atoi(param2.c_str()));
1603 result += anna::functions::entriesAsString(pushed, "message");
1606 } else if (param1 == "pop") {
1607 if (param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
1609 int releaseLoad = atoi(param2.c_str());
1610 int popped = my_app.popBurst(releaseLoad);
1613 result = "Burst popped for ";
1614 result += anna::functions::entriesAsString(popped, "message");
1617 } else if (param1 == "stop") {
1618 int left = my_app.stopBurst();
1621 result += anna::functions::entriesAsString(left, "message");
1622 result += " left to the end of the cycle.";
1624 } else if (param1 == "repeat") {
1625 if (param2 == "") param2 = "yes";
1627 bool repeat = (param2 == "yes");
1628 my_app.repeatBurst(repeat);
1629 result += (repeat ? "Mode on." : "Mode off.");
1630 } else if (param1 == "send") {
1631 if (param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
1633 int sent = my_app.sendBurst(atoi(param2.c_str()));
1637 result += anna::functions::entriesAsString(sent, "message");
1640 } else if (param1 == "goto") {
1641 if (param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
1643 result = my_app.gotoBurst(atoi(param2.c_str()));
1645 } else if (param1 == "look") {
1646 if (param2 == "") throw anna::RuntimeException("Missing order position for burst look operation", ANNA_FILE_LOCATION);
1649 result += my_app.lookBurst(atoi(param2.c_str()));
1652 throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
1654 } else if (opType == "sendxml2c") {
1656 throw anna::RuntimeException("Wrong body content format on HTTP Request for 'sendxml2c' operation (missing parameter)", ANNA_FILE_LOCATION);
1658 anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
1660 if (!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
1662 G_codecMsg.loadXML(param1);
1663 G_commMsgSent2c.clearBody();
1664 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)
1666 G_commMsgSent2c.setBody(G_codecMsg.code());
1667 bool success = localServer->send(G_commMsgSent2c);
1670 if (my_app.logEnabled()) {
1671 anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
1672 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
1673 my_app.writeLogFile(G_codecMsg, (success ? "sent2c" : "send2cError"), detail);
1675 } else if (opType == "loadxml") {
1677 throw anna::RuntimeException("Wrong body content format on HTTP Request for 'loadxml' operation (missing parameter)", ANNA_FILE_LOCATION);
1679 G_codecMsg.loadXML(param1);
1680 std::string xmlString = G_codecMsg.asXMLString();
1681 std::cout << xmlString << std::endl;
1682 } else if (opType == "diameterServerSessions") {
1684 throw anna::RuntimeException("Wrong body content format on HTTP Request for 'diameterServerSessions' operation (missing parameter)", ANNA_FILE_LOCATION);
1686 int diameterServerSessions = atoi(param1.c_str());
1688 if (!my_app.getDiameterLocalServer())
1689 my_app.startDiameterServer(diameterServerSessions);
1691 my_app.getDiameterLocalServer()->setMaxConnections(diameterServerSessions);
1692 } else if ((opType == "answerxml") || (opType == "answerxml2c")) {
1693 anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
1696 throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
1699 anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
1700 anna::diameter::codec::Message *message = engine->createMessage(param1);
1703 anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
1706 if (message->isRequest())
1707 throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
1709 int code = message->getId().first;
1710 reacting_answers_const_iterator it = G_reactingAnswers2C.find(code);
1712 if (it != G_reactingAnswers2C.end()) { // found: replace
1713 LOGDEBUG(anna::Logger::debug("Replacing formerly programed answer...", ANNA_FILE_LOCATION));
1714 engine->releaseMessage((*it).second);
1717 G_reactingAnswers2C[code] = message;
1718 } else { // answers query on stdout
1719 std::cout << my_app.programmedAnswers2c() << std::endl;
1720 response_content = "Programmed answers dumped on stdout\n";
1723 } else if ((opType == "answerxml2e")) {
1724 anna::diameter::comm::Entity *entity = my_app.getEntity();
1727 throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
1730 anna::diameter::codec::Engine *engine = anna::functions::component <Engine> (ANNA_FILE_LOCATION);
1731 anna::diameter::codec::Message *message = engine->createMessage(param1);
1734 anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
1737 if (message->isRequest())
1738 throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
1740 int code = message->getId().first;
1741 reacting_answers_const_iterator it = G_reactingAnswers2E.find(code);
1743 if (it != G_reactingAnswers2E.end()) { // found: replace
1744 LOGDEBUG(anna::Logger::debug("Replacing formerly programed answer...", ANNA_FILE_LOCATION));
1745 engine->releaseMessage((*it).second);
1748 G_reactingAnswers2E[code] = message;
1749 } else { // answers query on stdout
1750 std::cout << my_app.programmedAnswers2e() << std::endl;
1751 response_content = "Programmed answers dumped on stdout\n";
1755 LOGWARNING(anna::Logger::warning(my_app.help(), ANNA_FILE_LOCATION));
1756 throw anna::RuntimeException("Wrong body content format on HTTP Request. Unsupported/unrecognized operation type", ANNA_FILE_LOCATION);
1760 response_content = "Operation processed; ";
1762 if ((opType == "decode") || (opType == "code")) {
1763 response_content += "File '";
1764 response_content += param2;
1765 response_content += "' created.";
1766 response_content += "\n";
1767 } else if ((opType == "hide") || (opType == "show")) {
1768 response_content += "Resource '";
1769 response_content += ((param1 != "") ? param1 : "Entity");
1772 response_content += "|";
1773 response_content += param2;
1776 response_content += "' ";
1778 if (opType == "hide") response_content += "has been hidden.";
1780 if (opType == "show") response_content += "has been shown.";
1782 response_content += "\n";
1783 } else if ((opType == "hidden") || (opType == "shown")) {
1784 response_content += "Result: ";
1785 response_content += result;
1786 response_content += "\n";
1787 } else if ((opType == "sendxml") || (opType == "sendxml2e")) {
1788 response_content += "Message '";
1789 response_content += param1;
1790 response_content += "' sent to entity.";
1791 response_content += "\n";
1792 } else if (opType == "burst") {
1793 response_content += "Burst '";
1794 response_content += param1;
1795 response_content += "' executed. ";
1796 response_content += result;
1797 response_content += "\n";
1798 } else if (opType == "sendxml2c") {
1799 response_content += "Message '";
1800 response_content += param1;
1801 response_content += "' sent to client.";
1802 response_content += "\n";
1803 } else if (opType == "loadxml") {
1804 response_content += "Message '";
1805 response_content += param1;
1806 response_content += "' loaded.";
1807 response_content += "\n";
1808 } else if ((opType == "answerxml") || (opType == "answerxml2c")) {
1809 response_content += "Answer to client '";
1810 response_content += param1;
1811 response_content += "' programmed.";
1812 response_content += "\n";
1813 } else if ((opType == "answerxml2e")) {
1814 response_content += "Answer to entity '";
1815 response_content += param1;
1816 response_content += "' programmed.";
1817 response_content += "\n";
1818 } else if (opType == "diameterServerSessions") {
1819 response_content += "Maximum server socket connections updated to '";
1820 response_content += param1;
1821 response_content += "'.";
1822 response_content += "\n";
1827 int MyDiameterEntity::readSocketId(const anna::diameter::comm::Message* message, int maxClientSessions) const throw() {
1828 CommandLine& cl(anna::CommandLine::instantiate());
1829 std::string sessionBasedModelsType = (cl.exists("sessionBasedModelsClientSocketSelection") ? cl.getValue("sessionBasedModelsClientSocketSelection") : "SessionIdLowPart");
1831 if (sessionBasedModelsType == "RoundRobin") return -1; // IEC also would return -1
1834 // Service-Context-Id:
1835 anna::diameter::helpers::dcca::ChargingContext::_v chargingContext;
1836 std::string scid = anna::diameter::helpers::dcca::functions::getServiceContextId(message->getBody(), chargingContext);
1838 switch (chargingContext) {
1839 case anna::diameter::helpers::dcca::ChargingContext::Data:
1840 case anna::diameter::helpers::dcca::ChargingContext::Voice:
1841 case anna::diameter::helpers::dcca::ChargingContext::Content: {
1842 // Session-Id: '<DiameterIdentity>;<high 32 bits>;<low 32 bits>[;<optional value>="">]'
1843 std::string sid = anna::diameter::helpers::base::functions::getSessionId(message->getBody());
1844 std::string diameterIdentity, optional;
1845 anna::U32 high, low;
1846 anna::diameter::helpers::base::functions::decodeSessionId(sid, diameterIdentity, high, low /* context-teid */, optional);
1848 if (sessionBasedModelsType == "SessionIdLowPart") return (low % maxClientSessions);
1850 if (sessionBasedModelsType == "SessionIdHighPart") return (high % maxClientSessions);
1852 if (sessionBasedModelsType == "SessionIdOptionalPart") return (atoi(optional.c_str()) % maxClientSessions);
1854 //case anna::diameter::helpers::dcca::ChargingContext::SMS:
1855 //case anna::diameter::helpers::dcca::ChargingContext::MMS:
1857 // return -1; // IEC model and Unknown traffic types
1859 } catch (anna::RuntimeException &ex) {
1861 std::string msg = ex.getText();
1862 msg += " | Round-robin between sessions will be used to send";
1863 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
1871 void MyDiameterEntity::eventRequest(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
1872 throw(anna::RuntimeException) {
1873 LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventRequest", ANNA_FILE_LOCATION));
1874 // Performance stats:
1875 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
1876 CommandLine& cl(anna::CommandLine::instantiate());
1878 anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
1881 std::string msg = "Request received: ";
1882 msg += anna::diameter::functions::commandIdAsPairString(cid);
1883 msg += " | DiameterServer: ";
1884 msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
1885 msg += " | EventTime: ";
1886 msg += anna::time::functions::currentTimeAsString();
1887 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
1891 if (my_app.logEnabled()) my_app.writeLogFile(message, "recvfe", clientSession->asString());
1893 // Lookup reacting answers list:
1894 int code = cid.first;
1895 reacting_answers_const_iterator it = G_reactingAnswers2E.find(code);
1897 if (it != G_reactingAnswers2E.end()) {
1898 anna::diameter::codec::Message *answer_message = (*it).second;
1900 my_app.getCommunicator()->prepareAnswer(answer_message, message);
1903 G_commMsgSent2e.setBody(answer_message->code());
1904 /* response = NULL =*/clientSession->send(&G_commMsgSent2e);
1906 if (my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2e", clientSession->asString());
1907 } catch (anna::RuntimeException &ex) {
1910 if (my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2eError", clientSession->asString());
1912 } else { // not found: forward to client (if exists)
1913 // Forward to client:
1914 anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
1916 if (localServer && (cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CER */) {
1918 anna::diameter::comm::Message *msg = G_commMessages.create();
1919 msg->setBody(message);
1920 msg->setRequestClientSessionKey(clientSession->getKey());
1921 bool success = localServer->send(msg);
1924 if (my_app.logEnabled()) {
1925 anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
1926 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
1927 my_app.writeLogFile(message, (success ? "fwd2c" : "fwd2cError"), detail);
1929 } catch (anna::RuntimeException &ex) {
1937 void MyDiameterEntity::eventResponse(const anna::diameter::comm::Response &response)
1938 throw(anna::RuntimeException) {
1939 LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventResponse", ANNA_FILE_LOCATION));
1940 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
1941 CommandLine& cl(anna::CommandLine::instantiate());
1942 anna::diameter::comm::ClassCode::_v code = response.getClassCode();
1943 anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
1944 anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
1945 const anna::DataBlock* message = response.getMessage();
1946 const anna::diameter::comm::ClientSession *clientSession = static_cast<const anna::diameter::comm::ClientSession *>(response.getSession());
1947 bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind);
1948 bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage);
1949 bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout);
1950 bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable);
1951 bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success);
1953 anna::diameter::CommandId request_cid = request->getCommandId();
1956 std::string msg = "Response received for original diameter request: ";
1957 msg += anna::diameter::functions::commandIdAsPairString(request_cid);
1958 msg += " | Response: ";
1959 msg += response.asString();
1960 msg += " | DiameterServer: ";
1961 msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
1962 msg += " | EventTime: ";
1963 msg += anna::time::functions::currentTimeAsString();
1964 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
1967 if (isUnavailable) {
1968 //if (isApplicationMessage)
1969 LOGWARNING(anna::Logger::warning("Diameter entity unavailable for Diameter Request", ANNA_FILE_LOCATION));
1972 if (contextExpired) {
1973 //if (isApplicationMessage)
1974 LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the entity", ANNA_FILE_LOCATION));
1976 if (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
1977 if (my_app.logEnabled()) my_app.writeLogFile(*request, "req2e-expired", clientSession->asString());
1983 std::string msg = "Received response for diameter message: ";
1984 msg += anna::diameter::functions::commandIdAsPairString(request_cid);
1985 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
1988 bool alreadyDecodedOnG_codecMsg = false;
1990 if (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
1991 if (my_app.logEnabled()) {
1992 my_app.writeLogFile(*message, "recvfe", clientSession->asString());
1993 alreadyDecodedOnG_codecMsg = true;
1997 // Forward to client:
1998 anna::diameter::comm::LocalServer *localServer = my_app.getDiameterLocalServer();
2000 if (localServer && (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) /* don't forward CEA */) {
2002 G_commMsgFwd2c.setBody(*message);
2003 bool success = localServer->send(&G_commMsgFwd2c, request->getRequestServerSessionKey());
2004 G_commMessages.release(request);
2006 anna::diameter::comm::ServerSession *usedServerSession = my_app.getMyDiameterEngine()->findServerSession(request->getRequestServerSessionKey());
2007 std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // esto no deberia ocurrir
2009 if (my_app.logEnabled()) {
2010 if (alreadyDecodedOnG_codecMsg)
2011 my_app.writeLogFile(G_codecMsg, (success ? "fwd2c" : "fwd2cError"), detail);
2013 my_app.writeLogFile(*message, (success ? "fwd2c" : "fwd2cError"), detail);
2015 } catch (anna::RuntimeException &ex) {
2021 // Triggering burst:
2022 if (isOK || contextExpired) my_app.sendBurstMessage();
2026 void MyDiameterEntity::eventUnknownResponse(anna::diameter::comm::ClientSession *clientSession, const anna::DataBlock &message)
2027 throw(anna::RuntimeException) {
2028 LOGMETHOD(anna::TraceMethod tm("launcher::MyDiameterEntity", "eventUnknownResponse", ANNA_FILE_LOCATION));
2029 // Performance stats:
2030 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2032 anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2035 std::string msg = "Out-of-context response received from entity: ";
2036 msg += anna::diameter::functions::commandIdAsPairString(cid);
2037 msg += " | DiameterServer: ";
2038 msg += anna::functions::socketLiteralAsString(clientSession->getAddress(), clientSession->getPort());
2039 msg += " | EventTime: ";
2040 msg += anna::time::functions::currentTimeAsString();
2041 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2045 if (my_app.logEnabled()) my_app.writeLogFile(message, "recvfe-ans-unknown", clientSession->asString());
2051 void MyLocalServer::eventRequest(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
2052 throw(anna::RuntimeException) {
2053 LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventRequest", ANNA_FILE_LOCATION));
2054 // Performance stats:
2055 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2056 CommandLine& cl(anna::CommandLine::instantiate());
2058 anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2061 std::string msg = "Request received: ";
2062 msg += anna::diameter::functions::commandIdAsPairString(cid);
2063 msg += " | DiameterServer: ";
2064 msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2065 msg += " | EventTime: ";
2066 msg += anna::time::functions::currentTimeAsString();
2067 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2071 if (my_app.logEnabled()) my_app.writeLogFile(message, "recvfc", serverSession->asString());
2073 // If no answer is programmed and entity is configured, the failed request would be forwarded even being wrong (delegates at the end point)
2074 int code = cid.first;
2075 reacting_answers_const_iterator it = G_reactingAnswers2C.find(code);
2076 bool programmed = (it != G_reactingAnswers2C.end());
2077 anna::diameter::comm::Entity *entity = my_app.getEntity();
2079 if (!programmed && entity) { // forward condition (no programmed answer + entity available)
2080 anna::diameter::comm::Message *msg = G_commMessages.create();
2081 msg->setBody(message);
2082 msg->setRequestServerSessionKey(serverSession->getKey());
2083 bool success = entity->send(msg, cl.exists("balance"));
2086 if (my_app.logEnabled()) {
2087 anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
2088 anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
2089 std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
2090 my_app.writeLogFile(message, (success ? "fwd2e" : "fwd2eError"), detail); // forwarded
2097 bool analysisOK = true; // by default
2098 anna::diameter::codec::Message *answer_message = NULL;
2100 if (!cl.exists("ignoreErrors")) { // Error analysis
2101 answer_message = (anna::diameter::codec::Message*) & G_codecAnsMsg;
2102 answer_message->clear();
2105 try { G_codecMsg.decode(message, answer_message); } catch (anna::RuntimeException &ex) { ex.trace(); }
2107 answer_message->setStandardToAnswer(G_codecMsg, my_app.getMyDiameterEngine()->getHost(), my_app.getMyDiameterEngine()->getRealm());
2108 analysisOK = (answer_message->getResultCode() == anna::diameter::helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
2111 // Programmed answer only when all is ok
2114 answer_message = (*it).second;
2116 my_app.getCommunicator()->prepareAnswer(answer_message, message);
2117 } else return; // nothing done
2120 anna::diameter::codec::Engine *codecEngine = (anna::functions::component <anna::diameter::codec::Engine> (ANNA_FILE_LOCATION));
2121 anna::diameter::codec::Engine::ValidationMode::_v backupVM = codecEngine->getValidationMode();
2124 codecEngine->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Never);
2127 G_commMsgSent2c.setBody(answer_message->code());
2128 /* response = NULL =*/serverSession->send(&G_commMsgSent2c);
2130 if (my_app.logEnabled()) my_app.writeLogFile(*answer_message, "sent2c", serverSession->asString());
2131 } catch (anna::RuntimeException &ex) {
2134 if (my_app.logEnabled()) my_app.writeLogFile(*answer_message, "send2cError", serverSession->asString());
2137 // Restore validation mode
2138 codecEngine->setValidationMode(backupVM);
2141 void MyLocalServer::eventResponse(const anna::diameter::comm::Response &response)
2142 throw(anna::RuntimeException) {
2143 LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventResponse", ANNA_FILE_LOCATION));
2144 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2145 CommandLine& cl(anna::CommandLine::instantiate());
2146 anna::diameter::comm::ClassCode::_v code = response.getClassCode();
2147 anna::diameter::comm::Response::ResultCode::_v result = response.getResultCode();
2148 anna::diameter::comm::Message* request = const_cast<anna::diameter::comm::Message*>(response.getRequest());
2149 const anna::DataBlock* message = response.getMessage();
2150 const anna::diameter::comm::ServerSession *serverSession = static_cast<const anna::diameter::comm::ServerSession *>(response.getSession());
2151 bool isBindResponse = (code == anna::diameter::comm::ClassCode::Bind);
2152 bool isApplicationMessage = (code == anna::diameter::comm::ClassCode::ApplicationMessage);
2153 bool contextExpired = (result == anna::diameter::comm::Response::ResultCode::Timeout);
2154 bool isUnavailable = (result == anna::diameter::comm::Response::ResultCode::DiameterUnavailable);
2155 bool isOK = (result == anna::diameter::comm::Response::ResultCode::Success);
2157 anna::diameter::CommandId request_cid = request->getCommandId();
2160 std::string msg = "Response received for original diameter request: ";
2161 msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2162 msg += " | Response: ";
2163 msg += response.asString();
2164 msg += " | LocalServer: ";
2165 msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2166 msg += " | EventTime: ";
2167 msg += anna::time::functions::currentTimeAsString();
2168 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2171 if (isUnavailable) {
2172 //if (isApplicationMessage)
2173 LOGWARNING(anna::Logger::warning("Diameter client unavailable for Diameter Request", ANNA_FILE_LOCATION));
2176 if (contextExpired) {
2177 //if (isApplicationMessage)
2178 LOGWARNING(anna::Logger::warning("Context Expired for Diameter Request which was sent to the client", ANNA_FILE_LOCATION));
2180 if (request_cid != anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request) { // don't trace CEA
2181 if (my_app.logEnabled()) my_app.writeLogFile(*request, "req2c-expired", serverSession->asString());
2187 std::string msg = "Received response for diameter message: ";
2188 msg += anna::diameter::functions::commandIdAsPairString(request_cid);
2189 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2193 if (my_app.logEnabled()) my_app.writeLogFile(*message, "recvfc", serverSession->asString());
2195 // This is not very usual, but answers could arrive from clients:
2196 anna::diameter::comm::Entity *entity = my_app.getEntity();
2199 anna::diameter::comm::ClientSession *usedClientSession = my_app.getMyDiameterEngine()->findClientSession(request->getRequestClientSessionKey());
2202 if (my_app.logEnabled()) detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // esto no deberia ocurrir
2205 G_commMsgFwd2e.setBody(*message);
2208 if (usedClientSession) /* response = NULL =*/usedClientSession->send(&G_commMsgFwd2e);
2211 //G_commMsgFwd2e.setRequestClientSessionKey(request->getRequestClientSessionKey());
2212 //bool success = entity->send(G_commMsgFwd2e);
2213 G_commMessages.release(request);
2215 if (my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2e", detail); // forwarded
2216 } catch (anna::RuntimeException &ex) {
2219 if (my_app.logEnabled()) my_app.writeLogFile(*message, "fwd2eError", detail); // forwarded
2225 void MyLocalServer::eventUnknownResponse(anna::diameter::comm::ServerSession *serverSession, const anna::DataBlock &message)
2226 throw(anna::RuntimeException) {
2227 LOGMETHOD(anna::TraceMethod tm("launcher::MyLocalServer", "eventUnknownResponse", ANNA_FILE_LOCATION));
2228 // Performance stats:
2229 Launcher& my_app = static_cast <Launcher&>(anna::app::functions::getApp());
2231 anna::diameter::CommandId cid = anna::diameter::codec::functions::getCommandId(message);
2234 std::string msg = "Out-of-context response received from client: ";
2235 msg += anna::diameter::functions::commandIdAsPairString(cid);
2236 msg += " | DiameterServer: ";
2237 msg += anna::functions::socketLiteralAsString(serverSession->getAddress(), serverSession->getPort());
2238 msg += " | EventTime: ";
2239 msg += anna::time::functions::currentTimeAsString();
2240 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
2243 if (my_app.logEnabled()) my_app.writeLogFile(message, "recvfc-ans-unknown", serverSession->asString());
2247 anna::xml::Node* Launcher::asXML(anna::xml::Node* parent) const
2249 anna::xml::Node* result = parent->createChild("launcher");
2250 anna::comm::Application::asXML(result);
2252 result->createAttribute("StartTime", a_start_time.asString());
2253 result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
2255 (anna::functions::component <anna::diameter::codec::Engine> (ANNA_FILE_LOCATION))->asXML(result);
2257 anna::diameter::comm::OamModule::instantiate().asXML(result);
2258 anna::diameter::codec::OamModule::instantiate().asXML(result);
2260 anna::statistics::Engine::instantiate().asXML(result);