Changed LICENSE. Now referenced to web site and file on project root directory
[anna.git] / include / anna / diameter.comm / LocalServer.hpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
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 //
7
8
9 #ifndef anna_diameter_comm_LocalServer_hpp
10 #define anna_diameter_comm_LocalServer_hpp
11
12
13 #include <anna/core/RuntimeException.hpp>
14 #include <anna/core/util/Millisecond.hpp>
15 #include <anna/core/util/Recycler.hpp>
16
17 // STL
18 #include <string>
19 #include <vector>
20
21 #include <anna/config/defines.hpp>
22 #include <anna/statistics/Accumulator.hpp>
23 #include <anna/diameter.comm/ServerSession.hpp>
24
25
26 namespace anna {
27 namespace xml {
28 class Node;
29 }
30 namespace comm {
31 class ClientSocket;
32 //class LocalConnection;
33 }
34 class DataBlock;
35 }
36
37 namespace anna {
38
39 namespace diameter {
40
41 namespace comm {
42
43 class Engine;
44 class Response;
45 class ServerSocket;
46 class Message;
47
48
49 /**
50    Diameter server socket
51 */
52 class LocalServer {
53
54   // main
55   socket_t a_key;
56   std::string a_description;
57   int a_maxConnections;
58   int a_currentConnections; // deberia coincidir en todo momento con el numero de local connections del server socket
59   anna::Millisecond a_allowedInactivityTime;
60   ServerSocket *a_serverSocket;
61   int a_category;
62   bool a_lock;
63
64   // Engine
65   Engine *a_engine;
66
67   // Statistics
68   int a_processing_time__StatisticConceptId; // request from local server (dpr's, etc.)
69   int a_received_message_size__StatisticConceptId;
70   anna::statistics::Accumulator a_statisticsAccumulator;
71   void initializeStatisticConcepts() throw();
72   void resetStatistics() throw();
73
74 //   void eraseServerSession(const anna::comm::ClientSocket& clientSocket) throw();
75 //   void eraseServerSession(const serverSession_iterator &it) throw();
76   void lostConnection() throw();
77   void newConnection() throw(anna::RuntimeException);
78
79   // Activity
80   anna::Millisecond a_lastIncomingActivityTime;   // last unix timestamp (in milliseconds) when message reception was managed over this entity
81   anna::Millisecond a_lastOutgoingActivityTime;   // last unix timestamp (in milliseconds) when message sending was managed over this entity
82   void updateIncomingActivityTime() throw();
83   void updateOutgoingActivityTime() throw();
84
85   // Availability
86   bool a_available; // any of the server-sessions must be bound
87   void availabilityLost() throw();
88   void availabilityRecovered() throw();
89   bool refreshAvailability() throw(); // return true if change
90
91   void attach() throw(); // attach server socket to the communicator
92   void attachPlanning() throw(); // used when attach fails (socket already in use, etc.)
93
94   typedef int serverSession_key;
95   serverSession_key getServerSessionKey(const anna::comm::ClientSocket&) const throw(); // hash for Client Socket INetAddress serialization
96   typedef std::map <serverSession_key, ServerSession*> serverSession_container;
97   typedef serverSession_container::value_type serverSession_value_type;
98   typedef serverSession_container::iterator serverSession_iterator;
99   typedef serverSession_container::const_iterator const_serverSession_iterator;
100   serverSession_container a_serverSessions;
101   anna::Recycler<ServerSession> a_serverSessionsRecycler;
102   serverSession_iterator serverSession_find(const serverSession_key&) throw();
103   serverSession_iterator serverSession_begin() throw() { return a_serverSessions.begin(); }
104   serverSession_iterator serverSession_end() throw() { return a_serverSessions.end(); }
105   static ServerSession* serverSession(serverSession_iterator ii) throw() { return ii->second; }
106   const_serverSession_iterator serverSession_begin() const throw() { return a_serverSessions.begin(); }
107   const_serverSession_iterator serverSession_end() const throw() { return a_serverSessions.end(); }
108   static const ServerSession* serverSession(const_serverSession_iterator ii) throw() { return ii->second; }
109
110   // INTERNAL CREATORS AND CLOSE METHODS
111   ServerSession *createServerSession(const anna::comm::ClientSocket&) throw(anna::RuntimeException);
112   void closeServerSession(ServerSession*) throw(anna::RuntimeException);
113
114   // INTERNAL ALLOCATORS
115   ServerSession* allocateServerSession() throw();
116   void releaseServerSession(ServerSession*) throw();
117
118   // Auxiliary
119   serverSession_iterator a_deliveryIterator;
120   ServerSession *a_lastUsedResource;
121
122 public:
123
124   /** Constructor */
125   LocalServer();
126
127   /** Destructor */
128   ~LocalServer() { close(); }
129
130
131   // setters
132
133   /**
134   * Sets the local server key
135   * @param LocalServer key
136   */
137   void setKey(const socket_t &key) throw() { a_key = key; }
138
139   /**
140      Sets the server socket optional description
141
142      @param description Server socket description
143   */
144   void setDescription(const std::string description) throw() { a_description = description; }
145
146
147   /**
148      Sets the server socket optional category
149
150      @param description Server socket category
151   */
152   void setCategory(int category) throw() { a_category = category; }
153
154   /**
155      Sets the maximum supported connections.
156      If provided value is negative or lesser than the number of current connections, an exception will be launched.
157      If all the connections was established, a new maximum will open the listen port.
158      when margin is zeroed (maximum configured is equal to current connections), listen port will be closed.
159
160      @param maxConnections Number of maximum connections allowed
161   */
162   void setMaxConnections(int maxConnections) throw(anna::RuntimeException);
163
164   /**
165      Sets the maximum allowed inactivity time on server sessions born over the local server before being reset.
166      Communication engine assign a default value of 90000 msecs.
167
168      @param allowedInactivityTime Inactivity time allowed
169   */
170   void setAllowedInactivityTime(const anna::Millisecond & allowedInactivityTime) throw() { a_allowedInactivityTime = allowedInactivityTime; }
171
172   /**
173   * Sets the diameter::comm::Engine
174   * @param e Diameter::comm::Engine
175   */
176   void setEngine(Engine *e) throw() { a_engine = e; }
177
178
179   // getters
180
181   /**
182   * Gets the local server key
183   * @return LocalServer key
184   */
185   const socket_t & getKey() const throw() { return a_key; }
186
187   /**
188      Gets the number of maximum accepted connections that server socket is configured to handle
189   */
190   int getMaxConnections() const throw() { return a_maxConnections; }
191
192   /**
193      Gets the number of current connections being established through server socket
194   */
195   int getCurrentConnections() const throw() { return a_currentConnections; }
196
197   /**
198      Gets the maximum allowed inactivity time on server sessions born over the local server before being reset
199
200      @return Inactivity time allowed
201   */
202   const anna::Millisecond & getAllowedInactivityTime() const throw() { return a_allowedInactivityTime; }
203
204   /**
205      Returns true when any of the server-sessions is Bound. False when all not-bound.
206   */
207   bool isAvailable() const throw() { return a_available; }
208
209   // helpers
210
211   /**
212      Disables local server socket (listener) keeping current server sessions alive.
213      Note that applications should not close the listen port directly to keep coherence (see #resetConnectionsMargin)
214
215      @param lock Locks disabled state (make it permanent even if new connections margin is reached).
216      Used during diameter agent isolation (lost of service, maintenance, etc.)
217   */
218   void disable(bool lock = false) throw(anna::RuntimeException);
219
220   /** Enables local server socket (listener)
221
222      @param unlock Unlocks permanent disabled states
223   */
224   void enable(bool unlock = false) throw(anna::RuntimeException);
225
226   /**
227      Gets the number of requests messages over-the-air.
228
229      @return OTA messages.
230   */
231   int getOTARequests() const throw();
232
233   /**
234      Returns idle state (no pending answers).
235
236      @return Idle state.
237   */
238   bool idle() const throw() { return (getOTARequests() == 0); }
239
240   /**
241      Close the local server means two things: close the server socket and close all the server sessions born
242      from this local server freeing such server sessions resources.
243   */
244   void close() throw(anna::RuntimeException);
245
246   /**
247      Performs coherent server socket close procedure zeroing margin between current established connections and maximum allowed.
248   */
249   void resetConnectionsMargin() throw(anna::RuntimeException) { setMaxConnections(a_currentConnections); }
250
251
252   /**
253    * Returns server-session instance identified by client socket provided.
254    *
255    * \param clientSocket Client socket associated to the server session
256    * \param emode Action when no client-session is found with provided parameters (Throw/Ignore).
257    *
258    * \return The server-session instance identified by client socket provided.
259    *
260    * \warning If no server-session found, an exception is launched by default.
261    */
262   ServerSession* findServerSession(const anna::comm::ClientSocket &clientSocket, anna::Exception::Mode::_v emode = anna::Exception::Mode::Throw) throw(anna::RuntimeException);
263
264   /**
265    * Returns server-session instance identified by socket id provided (hash over serialized client socket information).
266    *
267    * \param socketId Socket id which is key for the server session
268    * \param emode Action when no client-session is found with provided parameters (Throw/Ignore).
269    *
270    * \return The server-session instance identified by client socket provided.
271    *
272    * \warning If no server-session found, an exception is launched by default.
273    */
274   ServerSession* findServerSession(int socketId, anna::Exception::Mode::_v emode = anna::Exception::Mode::Throw) throw(anna::RuntimeException);
275
276
277   /**
278      Sent a message to the client using a certain server-session provided or defined by #readSocketId if not.
279      When the message is a request, a timer will be set automatically to control the response time.
280      If expires, the ResultCode Timeout will be finally notified on #LocalServer::eventResponse. This
281      timeout value will be configured at #setClassCodeTimeout.
282
283      \param message Message sent.
284      \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)
285
286      @return Boolean about success in send operation. True when any of the server sessions could send the message.
287      False, when neither of the server sessions was available or fail to send the message. Broadcast try to send all over
288      the resources in spite of any fail. If a specific socket id is provided, only this socket is used without trying any other
289      and returning false if fails.
290   */
291   bool send(const Message*, int socketId = -1 /* default uses readSocketId() */) throw(anna::RuntimeException);
292   bool send(const Message& message, int socketId = -1 /* default uses readSocketId() */) throw(anna::RuntimeException) { return send(&message, socketId); }
293
294   /**
295      Gets the last used resource (server session) during sending.
296      Broadcast doesn't updates this information.
297   */
298   ServerSession *getLastUsedResource() const throw() { return (a_lastUsedResource); }
299
300   /**
301      Before sending a message over each local server, socketId could be specified to select
302      which session within such server will manage the message.
303
304      Default implementation performs round-robin (value '-1' for socketId) but any other kind of
305      application could re-implement this method and change the behaviour.
306
307      \param message Message which is being sent.
308
309      @return Socket-id (hash over serialized client socket information). Value '-1' if round-robin is desired.
310      If socket-id is unkonwn, send procedure will throw an exception.
311   */
312   virtual int readSocketId(const Message *message) const throw() { return -1; }
313
314   /**
315      Sent a message to all the server sessions.
316      It is used, i.e., in Disconnect-Peer-Request procedure over a certain entity.
317
318      \param message Message which is being sent.
319
320      @return Returns true (success) only when broadcast is success over all the entity servers. If any server fails,
321      then false is returned.
322   */
323   bool broadcast(const Message *message) throw(anna::RuntimeException);
324   bool broadcast(const Message &message) throw(anna::RuntimeException) { return broadcast(&message); }
325
326
327   /**
328      Class string representation
329      \return String with relevant information for this instance.
330   */
331   std::string asString() const throw();
332
333   /**
334      Class xml representation
335      \param parent Parent XML node on which hold this instance information.
336      \return XML document with relevant information for this instance.
337   */
338   anna::xml::Node* asXML(anna::xml::Node* parent) const throw();
339
340   // Statistics
341   void updateProcessingTimeStatisticConcept(const double &value) throw();
342   void updateReceivedMessageSizeStatisticConcept(const double &value) throw();
343   int getProcessingTimeStatisticConcept() const throw() { return a_processing_time__StatisticConceptId; }
344   int getReceivedMessageSizeStatisticConcept() const throw() { return a_received_message_size__StatisticConceptId; }
345
346 protected:
347
348   // Handlers:
349   /**
350      Handler about event break connection from diameter client over this server-session.
351      When notified, ANNA.diameter.comm generates an diameter::comm::ServerSession::eventResponse for every request with pending answers.
352      Default implementation traces warning event
353      \param serverSession ServerSession from which shutdown has been received
354   */
355   virtual void eventPeerShutdown(const ServerSession* serverSession) throw();
356
357   /**
358      Handler for diameter client responses
359
360      \param response Answer container object for corresponding diameter request
361   */
362   virtual void eventResponse(const Response& response) throw(anna::RuntimeException) = 0;
363
364   /**
365      Handler for diameter client requests
366
367      \param serverSession ServerSession from which request has been received
368      \param request Request data block object for corresponding diameter reception
369   */
370   virtual void eventRequest(ServerSession* serverSession, const anna::DataBlock& request) throw(anna::RuntimeException) = 0;
371   //void eventRequest(ServerSession* serverSession, const Message& request) throw(anna::RuntimeException);
372
373   /**
374      Handler for diameter client responses out of context
375
376      \param serverSession ServerSession from which request has been received
377      \param response Answer data block object without context match
378   */
379   virtual void eventUnknownResponse(ServerSession* serverSession, const anna::DataBlock& response) throw(anna::RuntimeException) = 0;
380
381   /**
382      Handler for diameter client Disconnect-Peer-Answer messages
383
384      \param serverSession ServerSession from which request has been received
385      \param response Answer data block object without context match
386   */
387   virtual void eventDPA(ServerSession* serverSession, const anna::DataBlock& response) throw(anna::RuntimeException) = 0;
388
389
390   friend class anna::diameter::comm::Timer;
391   friend class Engine;
392   friend class ServerSocket;
393   friend class ServerSession;
394   friend class ServerSessionReceiver;
395 };
396
397 }
398 }
399 }
400
401 #endif
402