1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
9 #include <stdlib.h> // rand()
12 #include <anna/diameter.comm/Engine.hpp>
13 #include <anna/core/tracing/Logger.hpp>
14 #include <anna/core/tracing/TraceMethod.hpp>
15 #include <anna/xml/Node.hpp>
16 #include <anna/comm/Network.hpp>
17 #include <anna/comm/Host.hpp>
18 #include <anna/comm/ClientSocket.hpp>
19 #include <anna/diameter.comm/Transport.hpp>
20 #include <anna/diameter.comm/Engine.hpp>
21 #include <anna/diameter.comm/Entity.hpp>
22 #include <anna/diameter.comm/Server.hpp>
23 #include <anna/diameter.comm/ClientSession.hpp>
24 #include <anna/diameter.comm/LocalServer.hpp>
25 #include <anna/core/functions.hpp>
26 #include <anna/diameter/internal/sccs.hpp>
27 #include <anna/diameter.comm/OamModule.hpp>
28 #include <anna/diameter/codec/functions.hpp>
29 #include <anna/diameter/helpers/base/functions.hpp>
30 #include <anna/diameter/helpers/helpers.hpp>
31 #include <anna/diameter/codec/Message.hpp>
32 #include <anna/diameter/codec/Avp.hpp>
33 #include <anna/diameter.comm/Response.hpp>
39 using namespace anna::diameter;
50 comm::Engine::Engine(const char *className, const stack::Dictionary *baseProtocolDictionary) :
51 anna::app::Component(className),
53 a_availableForEntities(false),
54 a_availableForLocalServers(false),
59 a_watchdogPeriod(ClientSession::DefaultWatchdogPeriod),
60 a_maxConnectionDelay(anna::comm::ClientSocket::DefaultMaxConnectionDelay /* 200 ms*/),
61 a_numberOfClientSessionsPerServer(1),
62 a_baseProtocolCodecEngine((std::string("baseProtocolCodecEngine_for_") + std::string(className)).c_str(), baseProtocolDictionary)
64 anna::diameter::sccs::activate();
65 a_originRealm = anna::functions::getDomainname();
66 a_originHost = anna::functions::getHostname();
69 // Internal base protocol codec engine:
70 a_baseProtocolCodecEngine.setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always); // default was: after decoding
74 void comm::Engine::assertBaseProtocolHealth() throw(anna::RuntimeException) {
75 if (!getBaseProtocolCodecEngine()->getDictionary())
76 throw anna::RuntimeException("Invalid diameter::comm::Engine object: base protocol dictionary provided on constructor was NULL", ANNA_FILE_LOCATION);
77 // it would be interesting to check and identify certain base protocol elements in the dictionary ...
78 // but these things will be checked in runtime and will fail if they should.
82 comm::Server* comm::Engine::allocateServer() throw() { return a_serversRecycler.create(); }
83 void comm::Engine::releaseServer(Server *server) throw() { a_serversRecycler.release(server); }
84 comm::ClientSession* comm::Engine::allocateClientSession() throw() { return a_clientSessionsRecycler.create(); }
85 void comm::Engine::releaseClientSession(ClientSession *clientSession) throw() { a_clientSessionsRecycler.release(clientSession); }
88 void comm::Engine::setClientCERandDWR(const anna::DataBlock & cer, const anna::DataBlock & dwr) throw(anna::RuntimeException) {
89 if(codec::functions::getCommandId(cer) != helpers::base::COMMANDID__Capabilities_Exchange_Request) {
90 throw anna::RuntimeException("The message provided as 'CER' is not a Capabilities-Exchange-Request", ANNA_FILE_LOCATION);
93 if(codec::functions::getCommandId(dwr) != helpers::base::COMMANDID__Device_Watchdog_Request) {
94 throw anna::RuntimeException("The message provided as 'DWR' is not a Device-Watchdog-Request", ANNA_FILE_LOCATION);
101 void comm::Engine::setClientCERandDWR(const std::string & cer, const std::string & dwr) throw(anna::RuntimeException) {
103 // Check for base protocol codec engine health:
104 assertBaseProtocolHealth();
107 // <CER> ::= < Diameter Header: 257, REQ >
108 // { Origin-Host } 264 diameterIdentity
109 // { Origin-Realm } 296 idem
110 // 1* { Host-IP-Address } 257, address
111 // { Vendor-Id } 266 Unsigned32
112 // { Product-Name } 269 UTF8String
113 // [Origin-State-Id] 278 Unsigned32
114 // * [ Supported-Vendor-Id ] 265 Unsigned32
115 // * [ Auth-Application-Id ] 258 Unsigned32
116 // * [Acct-Application-Id] 259 Unsigned32
117 anna::diameter::codec::Message diameterCER(getBaseProtocolCodecEngine());
118 int applicationId = 0 /*anna::diameter::helpers::APPID__3GPP_Rx*/; // Unsigned32
119 std::string OH = getOriginHostName();
120 std::string OR = getOriginRealmName();
121 std::string hostIP = anna::functions::getHostnameIP(); // Address
122 int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
123 std::string productName = "ANNA Diameter Client"; // UTF8String
124 bool encodeDefault = false;
128 diameterCER.loadXMLFile(cer);
129 } catch(anna::RuntimeException &ex) {
131 encodeDefault = true;
132 LOGWARNING(anna::Logger::warning("CER file not found or unable to parse. Encoding harcoded default version ...", ANNA_FILE_LOCATION));
136 encodeDefault = true;
140 diameterCER.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Request);
141 diameterCER.setApplicationId(applicationId);
142 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
143 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
144 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>"
145 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
146 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
147 diameterCER.addAvp(anna::diameter::helpers::base::AVPID__Auth_Application_Id)->getUnsigned32()->setValue(applicationId);
151 // <DWR> ::= < Diameter Header: 280, REQ >
154 anna::diameter::codec::Message diameterDWR(getBaseProtocolCodecEngine());
155 encodeDefault = false;
159 diameterDWR.loadXMLFile(dwr);
160 } catch(anna::RuntimeException &ex) {
162 encodeDefault = true;
163 LOGWARNING(anna::Logger::warning("DWR file not found or unable to parse. Encoding harcoded default version ...", ANNA_FILE_LOCATION));
167 encodeDefault = true;
171 diameterDWR.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Request);
172 diameterDWR.setApplicationId(applicationId);
173 diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->setValue(OH);
174 diameterDWR.addAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->setValue(OR);
177 // Assignment for internal encoded versions:
178 setClientCERandDWR(diameterCER.code(), diameterDWR.code());
181 void comm::Engine::setWatchdogPeriod(const anna::Millisecond & wp) throw(anna::RuntimeException) {
182 if(wp < ClientSession::DefaultWatchdogPeriod) {
183 throw anna::RuntimeException(anna::functions::asString("Please set watchdog period over %s", ClientSession::DefaultWatchdogPeriod.asString().c_str()), ANNA_FILE_LOCATION);
186 a_watchdogPeriod = wp;
189 void comm::Engine::checkEntityCollision(const socket_v &v) throw(anna::RuntimeException) {
190 socket_v::const_iterator it;
191 socket_v::const_iterator it_min(v.begin());
192 socket_v::const_iterator it_max(v.end());
194 for(it = it_min; it != it_max; it++) {
195 server_iterator ii = server_find(*it);
197 if(ii != server_end())
198 throw anna::RuntimeException("diameter::comm::Engine::checkEntityCollision: Server is already reserved by a former created entity. Use another", ANNA_FILE_LOCATION);
201 // Check repetitions:
202 std::map < socket_t, int/*dummy*/ > auxMap;
204 for(it = it_min; it != it_max; it++) auxMap[(*it)] = 0;
206 if(auxMap.size() != v.size())
207 throw anna::RuntimeException("diameter::comm::Engine::checkEntityCollision: Provided addresses list (sockets) must have all items different", ANNA_FILE_LOCATION);
210 comm::Entity* comm::Engine::createEntity(const socket_v & socketList, const std::string &description)
211 throw(anna::RuntimeException) {
212 Entity* result(NULL);
213 anna::Guard guard(this, "anna::diameter::comm::Engine::createEntity");
215 if(socketList.size() == 0)
216 throw anna::RuntimeException("diameter::comm::Engine::createEntity Address/Port server list provided is empty", ANNA_FILE_LOCATION);
218 // Proteccion antes de reservar memoria para una entidad (allocateEntity):
219 checkEntityCollision(socketList);
221 if((result = allocateEntity()) == NULL)
222 throw anna::RuntimeException("diameter::comm::Engine::allocateEntity returns NULL (perhaps virtual method was not implemented)", ANNA_FILE_LOCATION);
225 result->initialize(); // warning: recycler does not initialize its objects and at least, is important to empty servers vector.
226 // Assignments (it could be done at allocate):
227 result->setEngine(this); // lo podia haber asignado en el allocateEntity (no importa)
228 result->setMaxServers(socketList.size());
229 result->setDescription(description);
230 entity_key key(getEntityKey(socketList));
231 result->a_socketListLiteral = key;
232 // Create associated servers:
233 socket_v::const_iterator it;
234 socket_v::const_iterator it_min(socketList.begin());
235 socket_v::const_iterator it_max(socketList.end());
238 for(it = it_min; it != it_max; it++) {
239 result->addServer(*it);
241 if(count == 1) result->a_primarySocketLiteral = anna::functions::socketLiteralAsString((*it).first, (*it).second);
243 if(count == 2) result->a_secondarySocketLiteral = anna::functions::socketLiteralAsString((*it).first, (*it).second);
248 a_entities.insert(entity_value_type(key, result));
250 string msg("diameter::comm::Engine::createEntity | ");
251 msg += result->asString();
252 msg += anna::functions::asText(" | AutoBind: ", a_autoBind);
253 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
259 comm::LocalServer *comm::Engine::createLocalServer(const std::string & addr, int port, int maxConnections, const anna::Millisecond & allowedInactivityTime, int category, const std::string & description)
260 throw(anna::RuntimeException) {
261 LocalServer* result(NULL);
262 anna::Guard guard(this, "anna::diameter::comm::Engine::createLocalServer");
263 // Proteccion antes de reservar memoria para un LocalServer
264 socket_t key(addr, port);
266 if(a_localServers.find(key) != a_localServers.end())
267 throw anna::RuntimeException("LocalServer is already reserved by a former created access point. Cannot create again", ANNA_FILE_LOCATION);
269 if((result = allocateLocalServer()) == NULL)
270 throw anna::RuntimeException("diameter::comm::Engine::allocateLocalServer returns NULL (perhaps virtual method was not implemented)", ANNA_FILE_LOCATION);
272 result->setEngine(this); // lo podia haber asignado en el allocateLocalServer (no importa)
274 result->setCategory(category);
275 result->setDescription(description);
276 result->setAllowedInactivityTime(allowedInactivityTime);
277 result->initializeStatisticResources();
278 // Los saco con metodos virtuales readXXX del motor:
279 // if ((a_cea.isEmpty()) || (a_dwa.isEmpty()))
280 // throw anna::RuntimeException("Must define valid CEA and DWA messages by mean setCEAandDWA()", ANNA_FILE_LOCATION);
281 a_localServers.insert(localServer_value_type(key, result));
283 string msg("diameter::comm::Engine::createLocalServer | ");
284 msg += result->asString();
285 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
288 // /*if (a_autoListen) */result->enable(); // creates server socket
289 result->setMaxConnections(maxConnections); // (*) this enables the listen port ... or not
294 comm::Entity* comm::Engine::createEntity(const std::string & addr1, int port1, const std::string & addr2, int port2, const std::string &description)
295 throw(anna::RuntimeException) {
297 dualList.push_back(socket_t(addr1, port1));
298 dualList.push_back(socket_t(addr2, port2));
299 return (createEntity(dualList, description));
303 comm::Server* comm::Engine::createServer(Entity *entity, const socket_t & socket)
304 throw(anna::RuntimeException) {
305 Server* result(NULL);
306 anna::Guard guard(this, "anna::diameter::comm::Engine::createServer");
308 if((result = allocateServer()) == NULL)
309 throw anna::RuntimeException("diameter::comm::Engine::allocateServer returns NULL", ANNA_FILE_LOCATION);
312 result->initialize(); // warning: recycler does not initialize its objects and at least, is important to empty client-sessions vector.
313 // Assignments (it could be done at allocate):
314 result->a_parent = entity;
315 result->a_socket = socket;
316 result->setMaxClientSessions(a_numberOfClientSessionsPerServer /* engine */);
317 result->a_engine = this;
318 result->initializeStatisticResources();
320 for(int k = 0; k < a_numberOfClientSessionsPerServer; k++)
321 result->addClientSession(k);
323 a_servers.insert(server_value_type(socket, result));
324 // LOGDEBUG( Lo comento, porque ya se tracea en el createEntity
325 // string msg("diameter::comm::Engine::resolveServer | ");
326 // msg += result->asString();
327 // msg += anna::functions::asText(" | AutoBind: ", a_autoBind);
328 // anna::Logger::debug(msg, ANNA_FILE_LOCATION);
335 comm::ClientSession* comm::Engine::createClientSession(Server *server, int socketId)
336 throw(anna::RuntimeException) {
337 ClientSession* result(NULL);
338 anna::Guard guard(this, "anna::diameter::comm::Engine::createClientSession");
340 if((result = allocateClientSession()) == NULL)
341 throw anna::RuntimeException("diameter::comm::Engine::allocateClientSession returns NULL", ANNA_FILE_LOCATION);
344 result->initialize(); // warning: recycler does not initialize its objects and at least...
345 // Assignments (it could be done at allocate):
347 if((a_cer.isEmpty()) || (a_dwr.isEmpty()))
348 throw anna::RuntimeException("Must define valid CER and DWR messages by mean setClientCERandDWR()", ANNA_FILE_LOCATION);
350 result->a_cer.setBody(a_cer);
351 result->a_dwr.setBody(a_dwr);
352 result->setWatchdogPeriod(a_watchdogPeriod);
353 result->a_parent = server;
354 result->a_socketId = socketId;
355 result->initializeSequences(); // despues de asignar el server y el socketId (sequences are seed-based by mean exclusive hash)
356 result->a_engine = this;
357 clientSession_key key = ClientSession::getKey(server->getAddress(), server->getPort(), socketId);
358 a_clientSessions.insert(clientSession_value_type(key, result));
359 // LOGDEBUG( Lo comento, porque ya se tracea en el createEntity
360 // string msg("diameter::comm::Engine::createClientSession | ");
361 // msg += result->asString();
362 // msg += anna::functions::asText(" | AutoBind: ", a_autoBind);
363 // anna::Logger::debug(msg, ANNA_FILE_LOCATION);
366 anna::comm::Network& network = anna::comm::Network::instantiate();
367 result->a_server = network.resolveServer(server->getAddress().c_str(), server->getPort(), true /* autoRecovery */,
368 result->a_receiverFactory, &anna::diameter::comm::Transport::getFactory(),
369 anna::comm::Network::Port::Multiple, anna::comm::Network::DoConnect::No /* (*) */);
370 // Delay time on tcp connect:
371 result->a_server->setMaxConnectionDelay(a_maxConnectionDelay); // (*)
374 if(a_autoBind) result->bind();
380 bool comm::Engine::broadcastEntities(const Message* message) throw(anna::RuntimeException) {
381 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "broadcastEntities", ANNA_FILE_LOCATION));
385 for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
387 ok = entity(it)->broadcast(message);
389 if(!ok) allok = false;
390 } catch(anna::RuntimeException &ex) {
399 bool comm::Engine::broadcastLocalServers(const Message* message) throw(anna::RuntimeException) {
400 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "broadcastLocalServers", ANNA_FILE_LOCATION));
404 for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++) {
406 ok = localServer(it)->broadcast(message);
408 if(!ok) allok = false;
409 } catch(anna::RuntimeException &ex) {
418 bool comm::Engine::bind() throw(anna::RuntimeException) {
419 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "bind", ANNA_FILE_LOCATION));
420 bool result = true; // all OK return
422 for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
425 } catch(anna::RuntimeException &ex) {
434 comm::ClientSession* comm::Engine::findClientSession(const std::string & addr, int port, int socketId, anna::Exception::Mode::_v emode)
435 throw(anna::RuntimeException) {
436 return findClientSession(ClientSession::getKey(addr, port, socketId), emode);
439 comm::ClientSession* comm::Engine::findClientSession(const std::string & key, anna::Exception::Mode::_v emode)
440 throw(anna::RuntimeException) {
441 anna::Guard guard(this, "anna::diameter::comm::Engine::findClientSession");
442 clientSession_iterator ii = clientSession_find(key);
444 if(ii != clientSession_end())
445 return clientSession(ii);
447 if(emode != anna::Exception::Mode::Ignore) {
448 string msg("diameter::comm::Engine::findClientSession | [addr:port|socketId] = ");
450 msg += " | ClientSession not found";
451 anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
453 if(emode == anna::Exception::Mode::Throw)
463 comm::Server* comm::Engine::findServer(const std::string & addr, int port, anna::Exception::Mode::_v emode)
464 throw(anna::RuntimeException) {
465 anna::Guard guard(this, "anna::diameter::comm::Engine::findServer");
466 server_iterator ii = server_find(server_key(addr, port));
468 if(ii != server_end())
471 if(emode != anna::Exception::Mode::Ignore) {
472 string msg("diameter::comm::Engine::findServer | addr: ");
474 msg += anna::functions::asText(" | port: ", port);
475 msg += " | Server not found";
476 anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
478 if(emode == anna::Exception::Mode::Throw)
487 comm::Entity* comm::Engine::findEntity(const socket_v & socketList, anna::Exception::Mode::_v emode)
488 throw(anna::RuntimeException) {
489 anna::Guard guard(this, "anna::diameter::comm::Engine::findEntity");
490 entity_key key(getEntityKey(socketList));
491 entity_iterator ii = entity_find(key);
493 if(ii != entity_end())
496 if(emode != anna::Exception::Mode::Ignore) {
497 string msg("diameter::comm::Engine::findEntity | socket list: ");
499 msg += " | Entity not found";
500 anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
502 if(emode == anna::Exception::Mode::Throw)
511 comm::Entity* comm::Engine::findEntity(const std::string & addr1, int port1, const std::string & addr2, int port2, anna::Exception::Mode::_v emode)
512 throw(anna::RuntimeException) {
514 dualList.push_back(socket_t(addr1, port1));
515 dualList.push_back(socket_t(addr2, port2));
516 return (findEntity(dualList, emode));
520 //Entity* Engine::findEntity(int category, anna::Exception::Mode::_v emode)
521 //throw(anna::RuntimeException) {
525 // for (entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
526 // entity = entity(it);
527 // if (entity->getCategory() == category) return entity;
534 comm::LocalServer* comm::Engine::findLocalServer(const std::string & addr, int port, anna::Exception::Mode::_v emode)
535 throw(anna::RuntimeException) {
536 anna::Guard guard(this, "anna::diameter::comm::Engine::findLocalServer");
537 socket_t key(addr, port);
538 localServer_iterator ii = localServer_find(key);
540 if(ii != localServer_end())
541 return localServer(ii);
543 if(emode != anna::Exception::Mode::Ignore) {
544 string msg("diameter::comm::Engine::findLocalServer | addr: ");
546 msg += anna::functions::asText(" | port: ", port);
547 msg += " | LocalServer not found";
548 anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
550 if(emode == anna::Exception::Mode::Throw)
560 comm::ServerSession* comm::Engine::findServerSession(int socketId, anna::Exception::Mode::_v emode) throw(anna::RuntimeException) {
561 anna::Guard guard(this, "anna::diameter::comm::Engine::findServerSession");
562 ServerSession *result;
564 // Search at each local server:
565 for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++) {
566 result = localServer(it)->findServerSession(socketId, anna::Exception::Mode::Ignore);
568 if(result) return result;
571 if(emode != anna::Exception::Mode::Ignore) {
572 string msg("diameter::comm::Engine::findServerSession | socketId: ");
573 msg += anna::functions::asString(socketId);
574 msg += " | ServerSession not found";
575 anna::RuntimeException ex(msg, ANNA_FILE_LOCATION);
577 if(emode == anna::Exception::Mode::Throw)
587 void comm::Engine::closeClientSession(comm::ClientSession* clientSession, bool destroy)
588 throw(anna::RuntimeException) {
589 if(clientSession == NULL)
593 string msg("diameter::comm::Engine::closeClientSession | ");
594 msg += clientSession->asString();
595 msg += " | Destroy: ";
596 msg += (destroy ? "yes" : "no");
597 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
599 anna::Guard guard(this, "anna::diameter::comm::Engine::closeClientSession");
600 clientSession_iterator ii = clientSession_find(clientSession->getKey());
602 if(ii == clientSession_end())
606 clientSession->setState(ClientSession::State::Closing);
608 if(destroy) clientSession->setAutoRecovery(false);
610 clientSession->unbind(destroy /* destroy needs to perform immediate close */);
614 releaseClientSession(clientSession);
615 } catch(anna::RuntimeException& ex) {
619 a_clientSessions.erase(ii);
625 void comm::Engine::closeServer(comm::Server* server, bool destroy)
626 throw(anna::RuntimeException) {
631 string msg("diameter::comm::Engine::closeServer | ");
632 msg += server->asString();
633 msg += " | Destroy: ";
634 msg += (destroy ? "yes" : "no");
635 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
637 anna::Guard guard(this, "anna::diameter::comm::Engine::closeServer");
638 server_iterator ii = server_find(server->a_socket);
640 if(ii == server_end())
644 server->close(destroy);
648 releaseServer(server);
649 } catch(anna::RuntimeException& ex) {
657 void comm::Engine::closeEntity(comm::Entity* entity, bool destroy)
658 throw(anna::RuntimeException) {
663 string msg("diameter::comm::Engine::closeEntity | ");
664 msg += entity->asString();
665 msg += " | Destroy: ";
666 msg += (destroy ? "yes" : "no");
667 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
669 anna::Guard guard(this, "anna::diameter::comm::Engine::closeEntity");
670 entity_iterator ii = entity_find(entity->a_socketListLiteral);
672 if(ii == entity_end())
676 entity->close(destroy);
680 if(!entity->idle()) { entity->setDeprecated(true); return; }
682 releaseEntity(entity);
683 } catch(anna::RuntimeException& ex) {
687 a_entities.erase(ii);
692 void comm::Engine::closeLocalServer(comm::LocalServer* localServer, bool destroy)
693 throw(anna::RuntimeException) {
694 if(localServer == NULL)
698 string msg("diameter::comm::Engine::closeLocalServer | ");
699 msg += localServer->asString();
700 msg += " | Destroy: ";
701 msg += (destroy ? "yes" : "no");
702 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
704 anna::Guard guard(this, "anna::diameter::comm::Engine::closeLocalServer");
705 localServer_iterator ii = localServer_find(localServer->getKey());
707 if(ii == localServer_end())
711 localServer->close();
715 releaseLocalServer(localServer);
716 } catch(anna::RuntimeException& ex) {
720 a_localServers.erase(ii);
725 void comm::Engine::closeEntities(bool destroy) throw(anna::RuntimeException) {
726 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "closeEntities", ANNA_FILE_LOCATION));
727 anna::Guard guard(this, "anna::diameter::comm::Engine::closeEntities");
729 for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++)
730 closeEntity(entity(it), destroy);
733 void comm::Engine::closeLocalServers(bool destroy) throw(anna::RuntimeException) {
734 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "closeLocalServers", ANNA_FILE_LOCATION));
735 anna::Guard guard(this, "anna::diameter::comm::Engine::closeLocalServers");
737 for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++)
738 closeLocalServer(localServer(it), destroy);
741 void comm::Engine::eraseDeprecatedIdleEntities() throw() {
742 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "eraseDeprecatedIdleEntities", ANNA_FILE_LOCATION));
745 for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++) {
748 if(et->isDeprecated() && et->idle()) closeEntity(et, true /* destroy */);
752 int comm::Engine::getOTARequestsForEntities() const throw() {
755 for(const_entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++)
756 result += entity(it)->getOTARequests();
761 int comm::Engine::getOTARequestsForLocalServers() const throw() {
764 for(const_localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++)
765 result += localServer(it)->getOTARequests();
771 void comm::Engine::setOriginRealmName(const std::string & originRealmName) throw() {
772 a_originRealm = ((originRealmName != "") ? originRealmName : anna::functions::getDomainname());
776 void comm::Engine::setOriginHostName(const std::string & originHostName) throw() {
777 a_originHost = ((originHostName != "") ? originHostName : anna::functions::getHostname());
782 void comm::Engine::raiseAutoRecovery(bool autoRecovery) throw(anna::RuntimeException) {
783 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "raiseAutoRecovery", ANNA_FILE_LOCATION));
785 for(entity_iterator it = entity_begin(), maxii = entity_end(); it != maxii; it ++)
786 entity(it)->raiseAutoRecovery(autoRecovery);
789 void comm::Engine::do_stop()
791 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "do_stop", ANNA_FILE_LOCATION));
792 close(true /* destroy */);
795 std::string comm::Engine::asString(void) const throw() {
797 trace = "\n================================";
798 trace += "\nDiameter comm Engine information";
799 trace += "\n================================";
800 trace += "\nAutoBind: ";
801 trace += a_autoBind ? "yes" : "no";
802 trace += "\nMaxConnectionDelay: ";
803 trace += a_maxConnectionDelay.asString();
804 trace += "\nAvailable for entities: ";
805 trace += a_availableForEntities ? "yes" : "no";
806 trace += "\nAvailable for local servers: ";
807 trace += a_availableForLocalServers ? "yes" : "no";
808 trace += "\nOTA requests: ";
809 trace += anna::functions::asString("%d%s", getOTARequests(), idle() ? " (idle)" : "");
810 trace += "\nOTA requests for entities: ";
811 trace += anna::functions::asString("%d%s", getOTARequestsForEntities(), idleForEntities() ? " (idle)" : "");
812 trace += "\nOTA requests for local servers: ";
813 trace += anna::functions::asString("%d%s", getOTARequestsForLocalServers(), idleForLocalServers() ? " (idle)" : "");
815 trace += "\nNumber of entities: ";
816 trace += anna::functions::asString(a_entities.size());
818 for(const_entity_iterator it = entity_begin(); it != entity_end(); it++) {
820 trace += entity(it)->asString();
824 trace += "\nNumber of LocalServers: ";
825 trace += anna::functions::asString(a_localServers.size());
827 for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++) {
829 trace += localServer(it)->asString();
836 anna::xml::Node* comm::Engine::asXML(anna::xml::Node* parent) const
838 parent = anna::app::Component::asXML(parent);
839 anna::xml::Node* result = parent->createChild("diameter.comm.Engine");
840 result->createAttribute("AutoBind", a_autoBind ? "yes" : "no");
841 result->createAttribute("MaxConnectionDelay", a_maxConnectionDelay.asString());
842 result->createAttribute("AvailableForEntities", a_availableForEntities ? "yes" : "no");
843 result->createAttribute("AvailableForLocalServers", a_availableForLocalServers ? "yes" : "no");
844 result->createAttribute("OTArequests", anna::functions::asString("%d%s", getOTARequests(), idle() ? " (idle)" : ""));
845 result->createAttribute("OTArequestsForEntities", anna::functions::asString("%d%s", getOTARequestsForEntities(), idleForEntities() ? " (idle)" : ""));
846 result->createAttribute("OTArequestsForLocalServers", anna::functions::asString("%d%s", getOTARequestsForLocalServers(), idleForLocalServers() ? " (idle)" : ""));
847 result->createAttribute("NumberOfEntities", a_entities.size());
848 anna::xml::Node* entities = result->createChild("Engine.Entities");
850 for(const_entity_iterator it = entity_begin(); it != entity_end(); it++)
851 entity(it)->asXML(entities);
853 result->createAttribute("NumberOfLocalServers", a_localServers.size());
854 anna::xml::Node* localServers = result->createChild("Engine.LocalServers");
856 for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++)
857 localServer(it)->asXML(localServers);
861 // <Engine.RemoteRealm Name="afNodeHostRealm.com">
862 // <Engine.RemoteRealmHost Name="afNodeHostname.afNodeHostRealm.com" ServerSession="localhost:3868|ServerSessionId:4"/>
863 // </Engine.RemoteRealm>
864 // <Engine.RemoteRealm Name="ggsnNodeHostRealm.com">
865 // <Engine.RemoteRealmHost Name="ggsnNodeHostname.ggsnNodeHostRealm.com" ServerSession="localhost:3868|ServerSessionId:6"/>
866 // </Engine.RemoteRealm>
867 for (dr_dh_server_sessions_it_t drit = a_dr_dh_server_sessions.begin(); drit != a_dr_dh_server_sessions.end(); drit++) {
868 anna::xml::Node* remoteRealm = result->createChild("Engine.RemoteRealm");
869 remoteRealm->createAttribute("Name", drit->first);
870 dh_server_sessions_map_t *dhServerSessions = (dh_server_sessions_map_t *)&(drit->second);
871 for (dh_server_sessions_it_t dhit = dhServerSessions->begin(); dhit != dhServerSessions->end(); dhit++) {
872 anna::xml::Node* remoteRealmHost = remoteRealm->createChild("Engine.RemoteRealmHost");
873 remoteRealmHost->createAttribute("Name", dhit->first);
874 server_sessions_vector_t *serverSessions = (server_sessions_vector_t *)&(dhit->second);
875 for (server_sessions_it_t ssit = serverSessions->begin(); ssit != serverSessions->end(); ssit++) {
876 std::string socket = anna::functions::socketLiteralAsString((*ssit)->getAddress(), (*ssit)->getPort());
877 std::string ss_desc = socket + anna::functions::asString("|ServerSessionId:%d", (*ssit)->getSocketId());
878 remoteRealmHost->createAttribute("ServerSession", ss_desc);
886 comm::Engine::clientSession_iterator comm::Engine::clientSession_find(const clientSession_key &key) throw() {
887 return a_clientSessions.find(key);
890 comm::Engine::server_iterator comm::Engine::server_find(const server_key &key) throw() {
891 return a_servers.find(key);
894 comm::Engine::entity_iterator comm::Engine::entity_find(const entity_key &key) throw() {
895 return a_entities.find(key);
898 comm::Engine::localServer_iterator comm::Engine::localServer_find(const socket_t &key) throw() {
899 return a_localServers.find(key);
902 comm::Engine::entity_key comm::Engine::getEntityKey(const std::string & addr1, int port1, const std::string & addr2, int port2) const throw() {
904 dualList.push_back(socket_t(addr1, port1));
905 dualList.push_back(socket_t(addr2, port2));
906 return (getEntityKey(dualList));
909 comm::Engine::entity_key comm::Engine::getEntityKey(const socket_v &v) const throw() {
911 socket_v::const_iterator it;
912 socket_v::const_iterator it_min(v.begin());
913 socket_v::const_iterator it_max(v.end());
915 for(it = it_min; it != it_max; it++) {
916 result += anna::functions::socketLiteralAsString((*it).first, (*it).second);
920 result.erase(result.size() - 1, 1); // remove last space
925 void comm::Engine::availabilityLostForEntities() throw() {
926 a_availableForEntities = false;
928 std::string msg = "diameter::comm::Engine { Origin-Realm: ";
929 msg += getOriginRealmName();
930 msg += " | Origin-Host: ";
931 msg += getOriginHostName();
932 msg += " } has lost its availability for entities";
933 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
936 OamModule &oamModule = OamModule::instantiate();
937 oamModule.activateAlarm(OamModule::Alarm::c_LostAvailabilityOverEntitiesForEngineWithClassName__s__, getClassName());
938 oamModule.count(OamModule::Counter::LostAvailabilityOverEngineForEntities);
940 availabilityLostForEntities(this);
944 void comm::Engine::availabilityRecoveredForEntities() throw() {
945 a_availableForEntities = true;
947 std::string msg = "diameter::comm::Engine { Origin-Realm: ";
948 msg += getOriginRealmName();
949 msg += " | Origin-Host: ";
950 msg += getOriginHostName();
951 msg += " } has recovered its availability for entities";
952 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
955 OamModule &oamModule = OamModule::instantiate();
956 oamModule.cancelAlarm(OamModule::Alarm::c_LostAvailabilityOverEntitiesForEngineWithClassName__s__, getClassName());
957 oamModule.count(OamModule::Counter::RecoveredAvailabilityOverEngineForEntities);
959 availabilityRecoveredForEntities(this);
963 void comm::Engine::availabilityLostForLocalServers() throw() {
964 a_availableForLocalServers = false;
966 std::string msg = "diameter::comm::Engine { Origin-Realm: ";
967 msg += getOriginRealmName();
968 msg += " | Origin-Host: ";
969 msg += getOriginHostName();
970 msg += " } has lost its availability for local servers";
971 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
974 OamModule &oamModule = OamModule::instantiate();
975 oamModule.activateAlarm(OamModule::Alarm::c_LostAvailabilityOverLocalServersForEngineWithClassName__s__, getClassName());
976 oamModule.count(OamModule::Counter::LostAvailabilityOverEngineForLocalServers);
978 availabilityLostForLocalServers(this);
982 void comm::Engine::availabilityRecoveredForLocalServers() throw() {
983 a_availableForLocalServers = true;
985 std::string msg = "diameter::comm::Engine { Origin-Realm: ";
986 msg += getOriginRealmName();
987 msg += " | Origin-Host: ";
988 msg += getOriginHostName();
989 msg += " } has recovered its availability for local servers";
990 anna::Logger::debug(msg, ANNA_FILE_LOCATION);
993 OamModule &oamModule = OamModule::instantiate();
994 oamModule.cancelAlarm(OamModule::Alarm::c_LostAvailabilityOverLocalServersForEngineWithClassName__s__, getClassName());
995 oamModule.count(OamModule::Counter::RecoveredAvailabilityOverEngineForLocalServers);
997 availabilityRecoveredForLocalServers(this);
1001 bool comm::Engine::refreshAvailabilityForEntities() throw() {
1003 if(a_availableForEntities) { // check not-bound state for all client-sessions:
1004 bool isolate = true;
1006 for(const_entity_iterator it = entity_begin(); it != entity_end(); it++)
1007 if(entity(it)->isAvailable()) { isolate = false; break; }
1010 availabilityLostForEntities();
1017 // Here not available
1018 for(const_entity_iterator it = entity_begin(); it != entity_end(); it++)
1019 if(entity(it)->isAvailable()) {
1020 availabilityRecoveredForEntities();
1027 bool comm::Engine::refreshAvailabilityForLocalServers() throw() {
1029 if(a_availableForLocalServers) { // check not-bound state for all client-sessions:
1030 bool isolate = true;
1032 for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++)
1033 if(localServer(it)->isAvailable()) { isolate = false; break; }
1036 availabilityLostForLocalServers();
1043 // Here not available
1044 for(const_localServer_iterator it = localServer_begin(); it != localServer_end(); it++)
1045 if(localServer(it)->isAvailable()) {
1046 availabilityRecoveredForLocalServers();
1054 void comm::Engine::readDPA(anna::DataBlock &dpa, const anna::DataBlock & dpr) throw() {
1056 // Check for base protocol codec engine health:
1058 assertBaseProtocolHealth();
1060 catch(anna::RuntimeException &ex) {
1065 // Default DPA implementation:
1067 // 'Disconnect-Peer-Answer' (282,answer)
1068 // {Result-Code}...................................(268,0)
1069 // {Origin-Host}...................................(264,0)
1070 // {Origin-Realm}..................................(296,0)
1071 // [Error-Message].................................(281,0)
1072 // *[Failed-AVP]....................................(279,0)
1074 anna::diameter::codec::Message diameterDPA(getBaseProtocolCodecEngine());
1075 anna::diameter::codec::Avp avpRC(getBaseProtocolCodecEngine());
1076 anna::diameter::codec::Avp avpOH(getBaseProtocolCodecEngine());
1077 anna::diameter::codec::Avp avpOR(getBaseProtocolCodecEngine());
1079 diameterDPA.setId(anna::diameter::helpers::base::COMMANDID__Disconnect_Peer_Answer);
1080 diameterDPA.setVersion(1);
1081 diameterDPA.setApplicationId(codec::functions::getApplicationId(dpr));
1082 diameterDPA.setHopByHop(codec::functions::getHopByHop(dpr));
1083 diameterDPA.setEndToEnd(codec::functions::getEndToEnd(dpr));
1085 avpRC.setId(anna::diameter::helpers::base::AVPID__Result_Code);
1086 avpRC.setMandatoryBit();
1087 avpRC.getUnsigned32()->setValue(helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
1089 avpOH.setId(anna::diameter::helpers::base::AVPID__Origin_Host);
1090 avpOH.setMandatoryBit();
1091 avpOH.getDiameterIdentity()->fromPrintableString(a_originHost.c_str());
1093 avpOR.setId(anna::diameter::helpers::base::AVPID__Origin_Realm);
1094 avpOR.setMandatoryBit();
1095 avpOR.getDiameterIdentity()->fromPrintableString(a_originRealm.c_str());
1096 diameterDPA.addAvp(&avpRC);
1097 diameterDPA.addAvp(&avpOH);
1098 diameterDPA.addAvp(&avpOR);
1100 dpa = diameterDPA.code();
1101 } catch(anna::RuntimeException &ex) {
1102 std::string msg = ex.getText();
1103 msg += " | Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow internal base protocol messages encoding (unable to answer with DPA)";
1104 anna::Logger::error(msg, ANNA_FILE_LOCATION);
1105 //throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1110 void comm::Engine::readCEA(anna::DataBlock &cea, const anna::DataBlock &cer) throw() {
1112 // Check for base protocol codec engine health:
1113 assertBaseProtocolHealth();
1115 if (a_ceaPathfile != "") {
1116 anna::diameter::codec::Message diameterCEA(getBaseProtocolCodecEngine());
1119 diameterCEA.loadXMLFile(a_ceaPathfile);
1120 diameterCEA.setHopByHop(anna::diameter::codec::functions::getHopByHop(cer));
1121 diameterCEA.setEndToEnd(anna::diameter::codec::functions::getEndToEnd(cer));
1122 cea = diameterCEA.code();
1124 } catch(anna::RuntimeException &ex) {
1126 LOGWARNING(anna::Logger::warning("CEA file not found or unable to parse. Encoding harcoded default version ...", ANNA_FILE_LOCATION));
1127 //return anna::diameter::comm::Engine::readCEA(cea, cer);
1128 // will fail with empty cea
1134 // Default CEA implementation:
1136 // 'Capabilities-Exchange-Answer' (257,answer)
1137 // {Result-Code}...................................(268,0)
1138 // {Origin-Host}...................................(264,0)
1139 // {Origin-Realm}..................................(296,0)
1140 // 1*{Host-IP-Address}...............................(257,0)
1141 // {Vendor-Id}.....................................(266,0)
1142 // {Product-Name}..................................(269,0)
1143 // [Origin-State-Id]...............................(278,0)
1144 // [Error-Message].................................(281,0)
1145 // *[Failed-AVP]....................................(279,0)
1146 // *[Supported-Vendor-Id]...........................(265,0)
1147 // *[Auth-Application-Id]...........................(258,0)
1148 // *[Inband-Security-Id]............................(299,0)
1149 // *[Acct-Application-Id]...........................(259,0)
1150 // [Vendor-Specific-Application-Id]................(260,0)
1151 // [Firmware-Revision].............................(267,0)
1152 // *[AVP]...........................................(0,0)
1154 anna::diameter::codec::Message diameterCEA(getBaseProtocolCodecEngine());
1155 anna::diameter::codec::Avp avpRC(getBaseProtocolCodecEngine());
1156 anna::diameter::codec::Avp avpOH(getBaseProtocolCodecEngine());
1157 anna::diameter::codec::Avp avpOR(getBaseProtocolCodecEngine());
1159 diameterCEA.setId(anna::diameter::helpers::base::COMMANDID__Capabilities_Exchange_Answer);
1160 diameterCEA.setVersion(1);
1161 diameterCEA.setApplicationId(codec::functions::getApplicationId(cer));
1162 diameterCEA.setHopByHop(codec::functions::getHopByHop(cer));
1163 diameterCEA.setEndToEnd(codec::functions::getEndToEnd(cer));
1165 avpRC.setId(anna::diameter::helpers::base::AVPID__Result_Code);
1166 avpRC.setMandatoryBit();
1167 avpRC.getUnsigned32()->setValue(helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS); // re-implementations could analyze CER to accept or not
1169 avpOH.setId(anna::diameter::helpers::base::AVPID__Origin_Host);
1170 avpOH.setMandatoryBit();
1171 avpOH.getDiameterIdentity()->fromPrintableString(a_originHost.c_str());
1173 avpOR.setId(anna::diameter::helpers::base::AVPID__Origin_Realm);
1174 avpOR.setMandatoryBit();
1175 avpOR.getDiameterIdentity()->fromPrintableString(a_originRealm.c_str());
1176 diameterCEA.addAvp(&avpRC);
1177 diameterCEA.addAvp(&avpOH);
1178 diameterCEA.addAvp(&avpOR);
1180 std::string hostIP = anna::functions::getHostnameIP(); // Address
1181 diameterCEA.addAvp(anna::diameter::helpers::base::AVPID__Host_IP_Address)->getAddress()->fromPrintableString(hostIP.c_str());
1183 int vendorId = anna::diameter::helpers::VENDORID__tgpp; // Unsigned32
1184 diameterCEA.addAvp(anna::diameter::helpers::base::AVPID__Vendor_Id)->getUnsigned32()->setValue(vendorId);
1186 std::string productName = "Diameter Server"; // UTF8String
1187 diameterCEA.addAvp(anna::diameter::helpers::base::AVPID__Product_Name)->getUTF8String()->setValue(productName);
1189 cea = diameterCEA.code();
1190 } catch(anna::RuntimeException &ex) {
1191 std::string msg = ex.getText();
1192 msg += " | Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow internal base protocol messages encoding (unable to answer with CEA)";
1193 anna::Logger::error(msg, ANNA_FILE_LOCATION);
1194 //throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1198 void comm::Engine::manageDrDhServerSession(ServerSession *ss, bool register_or_desregister) throw() {
1200 // Decode CER (TODO: use raw buffer helpers)
1201 std::string destinationRealm, destinationHost;
1202 codec::Message codecMsg(getBaseProtocolCodecEngine());
1204 codecMsg.decode(ss->a_cer);
1205 destinationRealm = codecMsg.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue();
1206 destinationHost = codecMsg.getAvp(anna::diameter::helpers::base::AVPID__Origin_Host)->getDiameterIdentity()->getValue();
1208 catch(anna::RuntimeException &ex) {
1213 dr_dh_server_sessions_nc_it_t drit = a_dr_dh_server_sessions.find(destinationRealm);
1214 if (drit != a_dr_dh_server_sessions.end()) { // found
1215 dh_server_sessions_map_t *dhServerSessions = (dh_server_sessions_map_t *)&(drit->second);
1216 dh_server_sessions_nc_it_t dhit = dhServerSessions->find(destinationHost);
1217 if (dhit != dhServerSessions->end()) { // found
1218 server_sessions_vector_t *serverSessions = (server_sessions_vector_t *)&(dhit->second);
1219 if (register_or_desregister) { // REGISTER
1220 serverSessions->push_back(ss);
1222 else { // DESREGISTER
1223 // Sequential search the specific server session:
1224 for (server_sessions_nc_it_t ssit = serverSessions->begin(); ssit != serverSessions->end(); ssit++) {
1225 if ((*ssit)->getAddress() != ss->getAddress()) continue;
1226 if ((*ssit)->getPort() != ss->getPort()) continue;
1227 if ((*ssit)->getSocketId() != ss->getSocketId()) continue;
1228 serverSessions->erase(ssit); // if it is the last server session removed in DR-DH path, the XML will show this tree empty
1229 // (it could be a hint for past registerings):
1230 // <Engine.RemoteRealm Name="afNodeHostRealm.com">
1231 // <Engine.RemoteRealmHost Name="afNodeHostname.afNodeHostRealm.com"/>
1232 // </Engine.RemoteRealm>
1233 // <Engine.RemoteRealm Name="ggsnNodeHostRealm.com">
1234 // <Engine.RemoteRealmHost Name="ggsnNodeHostname.ggsnNodeHostRealm.com"/>
1235 // </Engine.RemoteRealm>
1242 if (!register_or_desregister) return; // strange (host not found)
1243 server_sessions_vector_t ssVector;
1244 ssVector.push_back(ss);
1245 (*dhServerSessions)[destinationHost] = ssVector;
1249 if (!register_or_desregister) return; // strange (realm not found)
1250 server_sessions_vector_t ssVector;
1251 ssVector.push_back(ss);
1252 dh_server_sessions_map_t dhServerSessions;
1253 dhServerSessions[destinationHost] = ssVector;
1254 a_dr_dh_server_sessions[destinationRealm] = dhServerSessions;
1258 void comm::Engine::readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw() {
1260 // Check for base protocol codec engine health:
1261 assertBaseProtocolHealth();
1263 // Default DWA implementation:
1265 // 'Device-Watchdog-Answer' (280,answer)
1266 // {Result-Code}...................................(268,0)
1267 // {Origin-Host}...................................(264,0)
1268 // {Origin-Realm}..................................(296,0)
1269 // [Error-Message].................................(281,0)
1270 // *[Failed-AVP]....................................(279,0)
1271 // [Origin-State-Id]...............................(278,0)
1273 anna::diameter::codec::Message diameterDWA(getBaseProtocolCodecEngine());
1274 anna::diameter::codec::Avp avpRC(getBaseProtocolCodecEngine());
1275 anna::diameter::codec::Avp avpOH(getBaseProtocolCodecEngine());
1276 anna::diameter::codec::Avp avpOR(getBaseProtocolCodecEngine());
1278 diameterDWA.setId(anna::diameter::helpers::base::COMMANDID__Device_Watchdog_Answer);
1279 diameterDWA.setVersion(1);
1280 diameterDWA.setApplicationId(codec::functions::getApplicationId(dwr));
1281 diameterDWA.setHopByHop(codec::functions::getHopByHop(dwr));
1282 diameterDWA.setEndToEnd(codec::functions::getEndToEnd(dwr));
1284 avpRC.setId(anna::diameter::helpers::base::AVPID__Result_Code);
1285 avpRC.setMandatoryBit();
1286 avpRC.getUnsigned32()->setValue(helpers::base::AVPVALUES__Result_Code::DIAMETER_SUCCESS);
1288 avpOH.setId(anna::diameter::helpers::base::AVPID__Origin_Host);
1289 avpOH.setMandatoryBit();
1290 avpOH.getDiameterIdentity()->fromPrintableString(a_originHost.c_str());
1292 avpOR.setId(anna::diameter::helpers::base::AVPID__Origin_Realm);
1293 avpOR.setMandatoryBit();
1294 avpOR.getDiameterIdentity()->fromPrintableString(a_originRealm.c_str());
1295 diameterDWA.addAvp(&avpRC);
1296 diameterDWA.addAvp(&avpOH);
1297 diameterDWA.addAvp(&avpOR);
1299 dwa = diameterDWA.code();
1300 } catch(anna::RuntimeException &ex) {
1301 std::string msg = ex.getText();
1302 msg += " | Use diameter::comm::Engine::setBaseProtocolCodecEngine() to allow internal base protocol messages encoding (unable to answer with DWA)";
1303 anna::Logger::error(msg, ANNA_FILE_LOCATION);
1304 //throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1308 void comm::Engine::resetStatistics() throw() {
1309 for(server_iterator it = server_begin(), maxii = server_end(); it != maxii; it ++)
1310 server(it)->resetStatistics();
1312 for(localServer_iterator it = localServer_begin(), maxii = localServer_end(); it != maxii; it ++)
1313 localServer(it)->resetStatistics();
1316 void comm::Engine::do_initialize() throw(RuntimeException) {
1317 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "do_initialize", ANNA_FILE_LOCATION));
1318 LOGDEBUG(anna::Logger::debug("Nothing special done on component initialization", ANNA_FILE_LOCATION));
1321 void comm::Engine::lazyInitialize() throw(RuntimeException) {
1322 LOGMETHOD(anna::TraceMethod tttm("diameter::comm::Engine", "lazyInitialize", ANNA_FILE_LOCATION));
1323 anna::app::Component::initialize(); // this will invoke do_initialize
1327 const comm::Response* comm::Engine::sendRealmHost(const Message* message, const std::string &destinationRealm, const std::string &destinationHost) throw(anna::RuntimeException) {
1329 if (destinationRealm == "")
1330 throw anna::RuntimeException("Unable to resolve the destination: empty provided Destination-Realm name", ANNA_FILE_LOCATION);
1332 // Get the server sessions which fulfill the restrictions:
1333 dr_dh_server_sessions_it_t drit = a_dr_dh_server_sessions.find(destinationRealm);
1334 if (drit == a_dr_dh_server_sessions.end())
1335 throw anna::RuntimeException(anna::functions::asString("Unable to resolve the destination: Destination-Realm name is not registered (no remote clients have been connected to '%s')", destinationRealm.c_str()), ANNA_FILE_LOCATION);
1337 dh_server_sessions_map_t *dhServerSessions = (dh_server_sessions_map_t *)&(drit->second);
1338 // randomize between all server sessions for all hosts:
1339 dh_server_sessions_nc_it_t dhit;
1340 int hostsN = dhServerSessions->size();
1341 if (hostsN == 0) // avoids next division by cero (rand() % 0)
1342 throw anna::RuntimeException(anna::functions::asString("Unable to resolve the destination: neither Destination-Host currently connected to Destination-Realm '%s'", destinationRealm.c_str()), ANNA_FILE_LOCATION);
1344 if (destinationHost == "") {
1345 // in this case, randomize the host:
1346 dhit = dhServerSessions->begin();
1347 int randomHostIndx = rand() % hostsN; // number between 0 and the number of hosts - 1
1348 std::advance (dhit, randomHostIndx);
1351 dhit = dhServerSessions->find(destinationHost);
1352 if (dhit == dhServerSessions->end())
1353 throw anna::RuntimeException(anna::functions::asString("Unable to resolve the destination: Destination-Host '%s' is not registered for Destination-Realm '%s'", destinationHost.c_str(), destinationRealm.c_str()), ANNA_FILE_LOCATION);
1356 // Now, randomize the available server sessions:
1357 server_sessions_vector_t *serverSessions = (server_sessions_vector_t *)&(dhit->second);
1358 int serverSessionN = serverSessions->size();
1359 if (serverSessionN == 0) { // avoids next division by cero (rand() % 0)
1360 std::string aux = "";
1361 if (destinationHost != "") { aux = "to Destination-Host '"; aux += destinationHost; aux += "'"; }
1362 std::string msg = anna::functions::asString("Unable to resolve the destination: neither server session currently connected%s within Destination-Realm '%s'", aux.c_str(), destinationRealm.c_str());
1363 throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
1366 server_sessions_nc_it_t ssit = serverSessions->begin();
1367 int randomServerSessionIndx = rand() % serverSessionN; // number between 0 and the number of server sessions - 1
1368 std::advance (ssit, randomServerSessionIndx);
1369 return (*ssit)->send(message);