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 #ifndef anna_diameter_comm_Entity_hpp
10 #define anna_diameter_comm_Entity_hpp
17 #include <anna/config/defines.hpp>
19 #include <anna/core/RuntimeException.hpp>
20 #include <anna/core/util/Millisecond.hpp>
22 #include <anna/diameter.comm/ClassCode.hpp>
48 Generic diameter server list (N-servers entity)
52 std::vector<Server*> a_servers;
53 int a_maxServers; // -1 means "no limit to add servers"
54 std::string a_description;
56 std::vector<Server*>::iterator a_deliveryIterator;
57 Server *a_lastUsedResource;
63 bool a_available; // any of the servers must be bound
64 void availabilityLost() throw();
65 void availabilityRecovered() throw();
66 bool refreshAvailability() throw(); // return true if change
67 void assertReady() throw(anna::RuntimeException);
68 void initialize() throw();
69 void childIdle() const throw();
71 // Selected for remove
72 bool a_deprecated; // entity has been selected as deprecated (will be removed when idle)
75 std::string a_socketListLiteral; // ADDRESS:PORT space-separated list
76 std::string a_primarySocketLiteral; // ADDRESS:PORT for primary (used on standard entities)
77 std::string a_secondarySocketLiteral; // ADDRESS:PORT for primary (used on standard entities)
81 anna::Millisecond a_lastIncomingActivityTime; // last unix timestamp (in milliseconds) when message reception was managed over this entity
82 anna::Millisecond a_lastOutgoingActivityTime; // last unix timestamp (in milliseconds) when message sending was managed over this entity
83 void updateIncomingActivityTime() throw();
84 void updateOutgoingActivityTime() throw();
86 // Private close/destroy method
87 void close(bool destroy) throw(anna::RuntimeException);
94 * Default constructor. Entities should be create through diameter::comm::Engine
95 * @param maxServers Maximum number of servers managed by the entity. Default is 2 (standard/dual entity).
96 * The value -1, means no limit to add servers.
98 Entity(int maxServers = 2) : a_maxServers(maxServers) { initialize(); }
102 * Sets the maximum number of servers managed by the entity.
104 * @param maxServers Maximum number of servers managed by the entity.
106 void setMaxServers(int maxServers) throw() { a_maxServers = maxServers; }
109 * Gets the maximum number of servers managed by the entity.
111 * @return Maximum number of servers managed by the entity.
113 int getMaxServers() const throw() { return a_maxServers; }
117 * Sets the entity description.
119 * @param description Entity description. Empty by default.
121 void setDescription(const std::string &description) throw() { a_description = description; }
124 * Gets the entity description.
126 * @return Entity description.
128 const std::string & getDescription() const throw() { return a_description; }
132 * Sets the diameter::comm::Engine
133 * @param e Diameter::comm::Engine
135 void setEngine(Engine *e) throw() { a_engine = e; }
139 * Add a server to the entity and create all the servers configured at #setSocketsPerDiameterServer within that server.
141 * \param serverId Diameter server ip/port.
143 * @return Returns success on send operation over any server within the entity
145 void addServer(const socket_t & serverId) throw(anna::RuntimeException);
148 * Binds entity servers.
150 * @return Returns true if all client-session were successfully bound
152 bool bind() throw(anna::RuntimeException);
155 * Propagate auto recovery configuration to servers within entity
157 * @param autoRecovery Auto recovery indicator. True by default.
159 void raiseAutoRecovery(bool autoRecovery = true) throw(anna::RuntimeException);
162 Sets timeout for wait responses for any class code request for all entity servers
164 \param v Diameter request type.
165 \param millisecond Milliseconds for timeout
167 void setClassCodeTimeout(const ClassCode::_v v, const anna::Millisecond & millisecond) throw();
170 Sets entity category. Used by application in order to categorize or clasify.
172 @param category Entity category
174 void setCategory(int category) throw() { a_category = category; }
177 Gets entity category. Used by application in order to categorize or clasify.
179 @return Entity category
181 int getCategory() const throw() { return a_category; }
184 Gets the last used resource (server) during sending.
185 Broadcast doesn't updates this information.
187 Server *getLastUsedResource() const throw() { return (a_lastUsedResource); }
191 // SIMPLE BALANCE or STANDARD documentation version
193 // Sent a message to the entity. First uses primary server, secondary if fails and so on to the
194 // last defined resource (server) within entity. Another sending algorithm (non standard) could
195 // be enabled (balance boolean parameter): it consist in round-robin server selection without
196 // trying any one if fails (standard behaviour tries all servers from FIRST defined).
197 // Anyway, last used delivery resource could be known through #getLastUsedResource().
199 // When the message is a request, a timer will be set automatically to control the response time.
200 // If expires, the ResultCode Timeout will be finally notified on #Entity::eventResponse. This
201 // timeout value will be configured at #setClassCodeTimeout.
203 // \param message Message sent.
204 // \param balance False by default (standard beaviour), but useful to balance over servers within entity.
206 // @return Boolean about success in send operation. Standard behaviour (no balance) implies true result when any
207 // of the entity servers could send the message, and false when neither of the servers was available or fail to
208 // send the message. Broadcast try to send all over the resources in spite of any fail, and balanced sendings
209 // fails when next selected resource fail to send the message (and no alarm or error counter is generated in
210 // this case because it can't be understood/ensured as entity-sending fail.
213 // OJO: en el caso estandard, no se prueban todas las sessiones de un servidor si tiene mas de una, luego la alarma
214 // generada en caso de error, presupone que las sessiones no usadas, también darÃan error, lo cual no tiene porque
215 // ser cierto. En condiciones normales, los servidores tienen una session, con lo que lo anterior es cierto y el
216 // la practica es lo mas normal.
219 Sent a message to the entity. First uses primary server, secondary if fails and so on to the
220 last defined resource (server) within entity. Another sending algorithm (non standard) could
221 be enabled (balance boolean parameter): it consist in round-robin server selection to set the
222 first resource in a complete cycle (standard behaviour tries all servers from FIRST defined).
223 Anyway, last used delivery resource could be known through #getLastUsedResource().
225 When the message is a request, a timer will be set automatically to control the response time.
226 If expires, the ResultCode Timeout will be finally notified on #Entity::eventResponse. This
227 timeout value will be configured at #setClassCodeTimeout.
229 \param message Message sent.
230 \param balance False by default (standard beaviour), but useful to balance over servers within entity.
232 @return Boolean about success in send operation. Implies true result when any of the entity servers could
233 send the message, and false when neither of the servers was available or fail to send the message (an alarm
234 and error counter will be generated in this case). Broadcast try to send all over the resources in spite of
237 bool send(const Message *message, bool balance = false) throw(anna::RuntimeException);
238 bool send(const Message &message, bool balance = false) throw(anna::RuntimeException) { return send(&message, balance); }
242 Before sending a message over each entity server, socketId could be specified to select
243 which client session within such server will manage the message.
245 Default implementation has been focused on charging applications but any other kind of
246 application could re-implement this method and change the behaviour:
249 Charging involves two peers:
251 Charging Trigger Function (CTF): Makes decisions on how to charge the user for specific
252 services, issues requests to the server (OCF).
253 Online Charging Function (OCF): Performs actual charging based on received message type,
254 service logic and user profile information.
256 There are three main scenarios:
258 Immediate Event Charging (IEC): The CTF sends a one time request. This request contains
259 a predefined set of AVPs indicating which service has
260 been activated or how many units have been consumed
261 (this depends on application logic).
263 Event Charging with Unit Reservation (ECUR): The CTF issues a request which indicates the
264 desired unit count for reservation. On service
265 delivery, the CTF issues another request which
266 indicates how many units were actually consumed.
267 Units can be of any type, as they are application
270 Session Charging with Unit Reservation(SCUR): As above, however reservation can happen more than once.
272 In order to minimize race conditions within trasactions, default implementation will select the connection
273 fixed by an stickiness value (Session-Id will be used) for ECUR and SCUR models (Data, Voice and Content
274 traffic). IEC model, represented by SMS ans MMS traffic will use round-robin between sockets. The type
275 of traffic will be analyzed by mean Service-Context-Id AVP. If traffic type is not reconized, value of
276 '-1' will be returned doing round-robin socket selection within active server.
278 Diameter session-oriented load balancing enables to distribute Diameter signaling traffic across
279 multiple client sessions for the selected entity server. Application could re-implement different
280 load balancing policies, including support for session stickiness and business decisions, and
281 subscriber and service aware contextual load balancing strategies. By default, Session-Id avp
282 is used to select the resource. Session-Id is split into 4 sections: diameter identity, high
283 part, low part and optional part. Default implementation analizes 'low' part, returning its
284 value as reference for socket selection.
287 When server is configured as single client session (max client sessions equal to 1), entity will ignore
288 this method being more efficient, because former algorithms would not affect the session selection.
290 \param message Message which is being sent.
291 \param maxClientSessions Number of client-sessions on specific server prepared for send.
293 @return Socket-id used within range [0,maxClientSessions-1]. Value '-1' if round-robin is desired.
294 If socket-id is return out of range, send procedure will throw an exception.
296 virtual int readSocketId(const Message *message, int maxClientSessions) const throw();
300 Sent a message to all the entity servers.
301 It is used, i.e., in Disconnect-Peer-Request procedure over a certain entity.
303 \param message Message which is being sent.
305 @return Returns true (success) only when broadcast is success over all the entity servers. If any server fails,
306 then false is returned.
308 bool broadcast(const Message *message) throw(anna::RuntimeException);
309 bool broadcast(const Message &message) throw(anna::RuntimeException) { return broadcast(&message); }
313 Returns true when any of the entity servers is Bound. False when all not-bound.
315 bool isAvailable() const throw() { return a_available; }
318 Returns true when the entity has been selected as deprecated
320 bool isDeprecated() const throw() { return a_deprecated; }
323 Sets the entity deprecated state
325 void setDeprecated(bool deprecated = true) throw() { a_deprecated = deprecated; }
329 Gets the number of requests messages over-the-air.
331 @return OTA messages.
333 int getOTARequests() const throw();
336 Returns idle state (no pending answers).
340 bool idle() const throw() { return (getOTARequests() == 0); }
343 std::vector<Server*>::iterator begin() throw() { return a_servers.begin(); }
344 std::vector<Server*>::iterator end() throw() { return a_servers.end(); }
345 std::vector<Server*>::const_iterator begin() const throw() { return a_servers.begin(); }
346 std::vector<Server*>::const_iterator end() const throw() { return a_servers.end(); }
349 Close all the entity servers (close client-sessions within them). Depending on client-session configuration ('OnDisconnect' behaviour),
350 pending answers will be wait (graceful) or ignored (immediate-abrupt close).
351 Resources are not destroyed.
353 void close() throw(anna::RuntimeException) { close(false /* no destroy */); }
358 Number of currently configured servers
360 int getNumberOfServers() const throw() { return a_servers.size(); }
363 Number of maximum allowed servers
365 int getMaxServerss() const throw() { return a_maxServers; }
368 List of (address,port) pairs defining entity servers
370 socket_v getAddressPortList() const throw();
374 Deny resources for delivery restriction.
380 Allow resource for delivery permission.
381 Allow all its servers
386 Returns true when all its servers resources are hidden for application messages delivery
388 bool hidden() const throw();
391 Returns true when all its servers resources are shown for application messages delivery
393 bool shown() const throw();
397 Class string representation
398 \return String with relevant information for this instance.
400 std::string asString() const throw();
403 Class xml representation
404 \param parent Parent XML node on which hold this instance information.
405 \return XML document with relevant information for this instance.
407 anna::xml::Node* asXML(anna::xml::Node* parent) const throw();
412 Handler about event break connection from diameter server (server) over this entity.
413 When notified, ANNA.diameter.comm generates an diameter::comm::Entity::eventResponse for every request with pending answers.
414 Default implementation traces warning event
415 \param clientSession ClientSession from which shutdown has been received
417 virtual void eventPeerShutdown(const ClientSession* clientSession) throw();
420 Handler for diameter server (server) responses
422 \param response Answer container object for corresponding diameter request
424 virtual void eventResponse(const Response& response) throw(anna::RuntimeException) = 0;
427 Handler for diameter server (server) requests
429 \param clientSession ClientSession from which request has been received
430 \param request Diameter request message received
432 virtual void eventRequest(ClientSession* clientSession, const anna::DataBlock &request) throw(anna::RuntimeException) = 0;
433 //virtual void eventRequest(ClientSession* clientSession, const Message& request) throw(anna::RuntimeException) = 0;
436 Handler for diameter session responses out of context
438 \param clientSession ClientSession from which request has been received
439 \param response Answer data block object without context match
441 virtual void eventUnknownResponse(ClientSession *clientSession, const anna::DataBlock& response) throw(anna::RuntimeException) = 0;
444 Handler for diameter session Disconnect-Peer-Answer messages
446 \param clientSession ClientSession from which request has been received
447 \param response Answer data block object without context match
449 virtual void eventDPA(ClientSession *clientSession, const anna::DataBlock& response) throw(anna::RuntimeException) = 0;