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_LocalServer_hpp
10 #define anna_diameter_comm_LocalServer_hpp
13 #include <anna/core/RuntimeException.hpp>
14 #include <anna/core/util/Millisecond.hpp>
15 #include <anna/core/util/Recycler.hpp>
23 #include <anna/config/defines.hpp>
24 #include <anna/diameter.comm/ServerSession.hpp>
25 #include <anna/diameter/defines.hpp>
26 #include <anna/diameter.comm/MessageStatistics.hpp>
35 //class LocalConnection;
53 Diameter server socket
59 std::string a_description;
61 int a_currentConnections; // deberia coincidir en todo momento con el numero de local connections del server socket
62 anna::Millisecond a_allowedInactivityTime;
63 ServerSocket *a_serverSocket;
71 MessageStatistics a_messageStatistics;
72 void initializeStatisticResources() throw();
73 void resetStatistics() throw();
75 // void eraseServerSession(const anna::comm::ClientSocket& clientSocket) throw();
76 // void eraseServerSession(const serverSession_iterator &it) throw();
77 void lostConnection() throw();
78 void newConnection() throw(anna::RuntimeException);
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();
87 bool a_available; // any of the server-sessions must be bound
88 void availabilityLost() throw();
89 void availabilityRecovered() throw();
90 bool refreshAvailability() throw(); // return true if change
92 void attach() throw(); // attach server socket to the communicator
93 void attachPlanning() throw(); // used when attach fails (socket already in use, etc.)
95 typedef int serverSession_key;
96 serverSession_key getServerSessionKey(const anna::comm::ClientSocket&) const throw(); // hash for Client Socket INetAddress serialization
97 typedef std::map <serverSession_key, ServerSession*> serverSession_container;
98 typedef serverSession_container::value_type serverSession_value_type;
99 typedef serverSession_container::iterator serverSession_iterator;
100 typedef serverSession_container::const_iterator const_serverSession_iterator;
101 serverSession_container a_serverSessions;
102 anna::Recycler<ServerSession> a_serverSessionsRecycler;
103 serverSession_iterator serverSession_find(const serverSession_key&) throw();
104 serverSession_iterator serverSession_begin() throw() { return a_serverSessions.begin(); }
105 serverSession_iterator serverSession_end() throw() { return a_serverSessions.end(); }
106 static ServerSession* serverSession(serverSession_iterator ii) throw() { return ii->second; }
107 const_serverSession_iterator serverSession_begin() const throw() { return a_serverSessions.begin(); }
108 const_serverSession_iterator serverSession_end() const throw() { return a_serverSessions.end(); }
109 static const ServerSession* serverSession(const_serverSession_iterator ii) throw() { return ii->second; }
111 // INTERNAL CREATORS AND CLOSE METHODS
112 ServerSession *createServerSession(const anna::comm::ClientSocket&) throw(anna::RuntimeException);
113 void closeServerSession(ServerSession*) throw(anna::RuntimeException);
115 // INTERNAL ALLOCATORS
116 ServerSession* allocateServerSession() throw();
117 void releaseServerSession(ServerSession*) throw();
120 serverSession_iterator a_deliveryIterator;
121 ServerSession *a_lastUsedResource;
129 ~LocalServer() { close(); }
135 * Sets the local server key
136 * @param LocalServer key
138 void setKey(const socket_t &key) throw() { a_key = key; }
141 Sets the server socket optional description
143 @param description Server socket description
145 void setDescription(const std::string description) throw() { a_description = description; }
148 Set timeout to consider failed a request.
149 \param v Requests class code.
150 \param millisecond Milliseconds wait before considering the requests failed.
152 Timers are internally managed and automatically activated.
154 void setClassCodeTimeout(const ClassCode::_v v, const anna::Millisecond & millisecond) throw();
157 Sets the server socket optional category
159 @param description Server socket category
161 void setCategory(int category) throw() { a_category = category; }
164 Sets the maximum supported connections.
165 If provided value is negative or lesser than the number of current connections, an exception will be launched.
166 If all the connections was established, a new maximum will open the listen port.
167 when margin is zeroed (maximum configured is equal to current connections), listen port will be closed.
169 @param maxConnections Number of maximum connections allowed
171 void setMaxConnections(int maxConnections) throw(anna::RuntimeException);
174 Sets the maximum allowed inactivity time on server sessions born over the local server before being reset.
175 Communication engine assign a default value of 90000 msecs.
177 @param allowedInactivityTime Inactivity time allowed
179 void setAllowedInactivityTime(const anna::Millisecond & allowedInactivityTime) throw() { a_allowedInactivityTime = allowedInactivityTime; }
182 * Sets the diameter::comm::Engine
183 * @param e Diameter::comm::Engine
185 void setEngine(Engine *e) throw() { a_engine = e; }
190 * Gets the diameter::comm::Engine
191 * @return Diameter::comm::Engine
193 Engine *getEngine() const throw() { return a_engine; }
196 * Gets the local server key
197 * @return LocalServer key
199 const socket_t & getKey() const throw() { return a_key; }
202 Gets the number of maximum accepted connections that server socket is configured to handle
204 int getMaxConnections() const throw() { return a_maxConnections; }
207 Gets the number of current connections being established through server socket
209 int getCurrentConnections() const throw() { return a_currentConnections; }
212 Gets the maximum allowed inactivity time on server sessions born over the local server before being reset
214 @return Inactivity time allowed
216 const anna::Millisecond & getAllowedInactivityTime() const throw() { return a_allowedInactivityTime; }
219 Returns true when any of the server-sessions is Bound. False when all not-bound.
221 bool isAvailable() const throw() { return a_available; }
226 Disables local server socket (listener) keeping current server sessions alive.
227 Note that applications should not close the listen port directly to keep coherence (see #resetConnectionsMargin)
229 @param lock Locks disabled state (make it permanent even if new connections margin is reached).
230 Used during diameter agent isolation (lost of service, maintenance, etc.)
232 void disable(bool lock = false) throw(anna::RuntimeException);
234 /** Enables local server socket (listener)
236 @param unlock Unlocks permanent disabled states
238 void enable(bool unlock = false) throw(anna::RuntimeException);
241 Gets the number of requests messages over-the-air.
243 @return OTA messages.
245 int getOTARequests() const throw();
248 Returns idle state (no pending answers).
252 bool idle() const throw() { return (getOTARequests() == 0); }
255 Close the local server means two things: close the server socket and close all the server sessions born
256 from this local server freeing such server sessions resources.
258 void close() throw(anna::RuntimeException);
261 Performs coherent server socket close procedure zeroing margin between current established connections and maximum allowed.
263 void resetConnectionsMargin() throw(anna::RuntimeException) { setMaxConnections(a_currentConnections); }
267 * Returns server-session instance identified by client socket provided.
269 * \param clientSocket Client socket associated to the server session
270 * \param emode Action when no client-session is found with provided parameters (Throw/Ignore).
272 * \return The server-session instance identified by client socket provided.
274 * \warning If no server-session found, an exception is launched by default.
276 ServerSession* findServerSession(const anna::comm::ClientSocket &clientSocket, anna::Exception::Mode::_v emode = anna::Exception::Mode::Throw) throw(anna::RuntimeException);
279 * Returns server-session instance identified by socket id provided (hash over serialized client socket information).
281 * \param socketId Socket id which is key for the server session
282 * \param emode Action when no client-session is found with provided parameters (Throw/Ignore).
284 * \return The server-session instance identified by client socket provided.
286 * \warning If no server-session found, an exception is launched by default.
288 ServerSession* findServerSession(int socketId, anna::Exception::Mode::_v emode = anna::Exception::Mode::Throw) throw(anna::RuntimeException);
292 Sent a message to the client using a certain server-session provided or defined by #readSocketId if not.
293 When the message is a request, a timer will be set automatically to control the response time.
294 If expires, the ResultCode Timeout will be finally notified on #LocalServer::eventResponse. This
295 timeout value will be configured at #setClassCodeTimeout.
297 \param message Message sent.
298 \param socketId Server session socket id INetAddress serialization. By default, #readSocketId is invoked to get the socket id used (which uses round-robin if not re-implemented)
300 @return Boolean about success in send operation. True when any of the server sessions could send the message.
301 False, when neither of the server sessions was available or fail to send the message. Broadcast try to send all over
302 the resources in spite of any fail. If a specific socket id is provided, only this socket is used without trying any other
303 and returning false if fails.
305 bool send(const Message*, int socketId = -1 /* default uses readSocketId() */) throw(anna::RuntimeException);
306 bool send(const Message& message, int socketId = -1 /* default uses readSocketId() */) throw(anna::RuntimeException) { return send(&message, socketId); }
309 Gets the last used resource (server session) during sending.
310 Broadcast doesn't updates this information.
312 ServerSession *getLastUsedResource() const throw() { return (a_lastUsedResource); }
315 Before sending a message over each local server, socketId could be specified to select
316 which session within such server will manage the message.
318 Default implementation performs round-robin (value '-1' for socketId) but any other kind of
319 application could re-implement this method and change the behaviour.
321 \param message Message which is being sent.
323 @return Socket-id (hash over serialized client socket information). Value '-1' if round-robin is desired.
324 If socket-id is unkonwn, send procedure will throw an exception.
326 virtual int readSocketId(const Message *message) const throw() { return -1; }
329 Sent a message to all the server sessions.
330 It is used, i.e., in Disconnect-Peer-Request procedure over a certain entity.
332 \param message Message which is being sent.
334 @return Returns true (success) only when broadcast is success over all the entity servers. If any server fails,
335 then false is returned.
337 bool broadcast(const Message *message) throw(anna::RuntimeException);
338 bool broadcast(const Message &message) throw(anna::RuntimeException) { return broadcast(&message); }
342 Class string representation
343 \return String with relevant information for this instance.
345 std::string asString() const throw();
348 Class xml representation
349 \param parent Parent XML node on which hold this instance information.
350 \return XML document with relevant information for this instance.
352 anna::xml::Node* asXML(anna::xml::Node* parent) const throw();
355 void updateProcessingTimeStatisticConcept(const double &value, const anna::diameter::CommandId &cid) throw();
356 void updateReceivedMessageSizeStatisticConcept(const double &value, const anna::diameter::CommandId &cid) throw();
357 // int getProcessingTimeStatisticConcept() const throw() { return a_processing_time__StatisticConceptId; }
358 // int getReceivedMessageSizeStatisticConcept() const throw() { return a_received_message_size__StatisticConceptId; }
364 Handler about event break connection from diameter client over this server-session.
365 When notified, ANNA.diameter.comm generates an diameter::comm::ServerSession::eventResponse for every request with pending answers.
366 Default implementation traces warning event
367 \param serverSession ServerSession from which shutdown has been received
369 virtual void eventPeerShutdown(const ServerSession* serverSession) throw();
372 Handler about a request retransmission over the server-session.
373 Default implementation traces warning event
374 \param serverSession ServerSession from which retransmission happened
375 \param request Retransmitted request message
377 virtual void eventRequestRetransmission(const ServerSession* serverSession, Message *request) throw();
380 Handler for diameter client responses
382 \param response Answer container object for corresponding diameter request
384 virtual void eventResponse(const Response& response) throw(anna::RuntimeException) = 0;
387 Handler for diameter client requests
389 \param serverSession ServerSession from which request has been received
390 \param request Request data block object for corresponding diameter reception
392 virtual void eventRequest(ServerSession* serverSession, const anna::DataBlock& request) throw(anna::RuntimeException) = 0;
393 //void eventRequest(ServerSession* serverSession, const Message& request) throw(anna::RuntimeException);
396 Handler for diameter client responses out of context
398 \param serverSession ServerSession from which request has been received
399 \param response Answer data block object without context match
401 virtual void eventUnknownResponse(ServerSession* serverSession, const anna::DataBlock& response) throw(anna::RuntimeException) = 0;
404 Handler for diameter client Disconnect-Peer-Answer messages
406 \param serverSession ServerSession from which request has been received
407 \param response Answer data block object without context match
409 virtual void eventDPA(ServerSession* serverSession, const anna::DataBlock& response) throw(anna::RuntimeException) = 0;
412 friend class anna::diameter::comm::Timer;
414 friend class ServerSocket;
415 friend class ServerSession;
416 friend class ServerSessionReceiver;