dcc31618bb2d9eb86dd7d053060247eb6902bd5f
[anna.git] / include / anna / diameter.comm / Engine.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_Engine_hpp
10 #define anna_diameter_comm_Engine_hpp
11
12
13 // STL
14 #include <map>
15 #include <vector>
16 #include <string>
17 #include <algorithm>
18
19 #include <anna/app/Component.hpp>
20 #include <anna/core/util/Recycler.hpp>
21
22 #include <anna/diameter/codec/Engine.hpp>
23 #include <anna/diameter.comm/Server.hpp>
24 #include <anna/diameter.comm/ServerSession.hpp>
25 #include <anna/config/defines.hpp>
26 #include <anna/diameter.comm/ClientSession.hpp>
27 #include <anna/diameter.comm/ServerSession.hpp>
28
29 // Standard
30 #include <time.h>
31
32
33 //------------------------------------------------------------------------------
34 //---------------------------------------------------------------------- #define
35 //------------------------------------------------------------------------------
36
37 namespace anna {
38 class DataBlock;
39 class Millisecond;
40 }
41
42
43
44 namespace anna {
45
46 namespace diameter {
47
48 namespace codec {
49 class Engine;
50 }
51
52 namespace stack {
53 class Dictionary;
54 }
55
56 namespace comm {
57
58 class Response;
59 class Entity;
60 class Server;
61 class LocalServer;
62
63 /**
64  *  General manager for connections to several diameter servers and from diameter clients.
65  *
66  *  Optimizes creation, finding and releasing of established client-sessions to a certain number of
67  *  diameter servers through entities.
68  *  Optimizes creation, finding and releasing of established server-sessions from a certain number of
69  *  diameter clients through local servers.
70  *
71  *  Implementation example:
72  *
73  *  \code
74  *
75  *     class MyEngine : public diameter::comm::Engine {
76  *     public:
77  *        MyEngine () {;}
78  *
79  *     private:
80  *        anna::Recycler<MyEntity> a_entities;
81  *
82  *        anna::diameter::comm::Entity* allocateEntity () throw () { return a_entities.create (); }
83  *
84  *        void releaseEntity (anna::diameter::comm::Entity* entity) throw () {
85  *           MyEntity* aux = static_cast <MyEntity*> (entity);
86  *           a_entities.release (aux);
87  *        }
88  *
89  *
90  *        anna::diameter::comm::LocalServer* allocateLocalServer () throw () { return a_localServers.create (); }
91  *
92  *        void releaseLocalServer (anna::diameter::comm::LocalServer* localServer) throw () {
93  *           MyLocalServer* aux = static_cast <MyLocalServer*> (localServer);
94  *           a_localServers.release (aux);
95  *        }
96  *     };
97  *
98  *  \endcode
99  */
100 class Engine : public anna::app::Component {
101 public:
102
103   /**
104      Diameter application node origin realm
105
106      @param originRealm Used to configure the Origin-Realm for outgoing messages.
107      If not configured or empty string provided, host domainname will be set.
108   */
109   void setOriginRealm(const std::string & originRealm) throw();
110
111   /**
112      Diameter application origin host
113
114      @param originHost Used to configure the Origin-Host for outgoing messages.
115      If not configured or empty string provided, hostname (system name) will be set.
116   */
117   void setOriginHost(const std::string & originHost) throw();
118
119   /**
120      Gets the configured diameter application node origin realm
121
122      @return Diameter application node origin realm
123   */
124   const std::string & getOriginRealm() const throw() { return a_originRealm; }
125
126   /**
127      Gets the configured diameter application origin host
128
129      @return Diameter application node origin host
130   */
131   const std::string & getOriginHost() const throw() { return a_originHost; }
132
133
134   /**
135    * Propagate auto recovery configuration to entities within engine. Recovery period is configured at
136    * #anna::comm::Communicator::setRecoveryTime. All the client client-sessions created throught #createEntity,
137    * will be created based on the engine auto-recovery value (enable by default). But you could access entities,
138    * servers or client-sessions independently to change this behaviour.
139    *
140    * @param autoRecovery Auto recovery indicator. True by default.
141    */
142   void raiseAutoRecovery(bool autoRecovery = true) throw(anna::RuntimeException);
143
144   /**
145    * Returns automatic bind indicator for client-sessions. By default \em true will be used.
146    * \return Value for automatic connection bind.
147    */
148   bool getAutoBind() const throw() { return a_autoBind; }
149
150   /**
151    * Sets automatic connection bind indicator for client-sessions. If not asigned, it will be \em true.
152    * \param autoBind Value for automatic connection bind.
153    *
154    * In order to change bind timer, first client-session must be created without autobind, modify time
155    * parameter and then invoking bind.
156    */
157   void setAutoBind(const bool autoBind) throw() { a_autoBind = autoBind; }
158
159   /**
160      Sets the milliseconds wait to achieve a client connection to server by mean connect primitive.
161      This is a general value for born client-sessions over engine. Particular configuration could be done
162      through #ClientSession::setMaxConnectionDelay.
163
164      \param maxConnectionDelay Milliseconds wait to get connection
165   */
166   void setMaxConnectionDelay(const anna::Millisecond & maxConnectionDelay) throw() { a_maxConnectionDelay = maxConnectionDelay; }
167
168   /**
169      Gets the milliseconds wait to achieve a client connection to server by mean connect primitive.
170      Returns the global engine value, but it could be overwritten through each client session (#ClientSession::setMaxConnectionDelay).
171      Default value is 'anna::comm::ClientSocket::DefaultMaxConnectionDelay'.
172
173      \return Milliseconds wait to get connection
174   */
175   const anna::Millisecond & getMaxConnectionDelay() throw() { return a_maxConnectionDelay; }
176
177   /**
178    * Binds engine entities.
179    *
180    * @return Returns true if all client-session were successfully bound
181    */
182   bool bind() throw(anna::RuntimeException);
183
184   /**
185    * Sets CER and DWR diameter messages to be used over created client-sessions.
186    * Its recommended to set this global configuration although it is possible to configure each client-session separately.
187    *
188    * @param cer Capabilities-Exchange-Request message (encoded) for the client-sessions bind.
189    * @param dwr Device-Watchdog-Request message (encoded) for the client-sessions keep-alive.
190    */
191   void setClientCERandDWR(const anna::DataBlock & cer, const anna::DataBlock & dwr) throw(anna::RuntimeException);
192
193   /**
194    * Sets CER and DWR diameter messages to be used over created client-sessions. If empty string is provided for CER and/or DWR, default version will be configured.
195    * Its recommended to set this global configuration although it is possible to configure each client-session separately.
196    *
197    * @param cer Capabilities-Exchange-Request xml message path file for the client-sessions bind. If empty string is provided (default), a default version for CER will be encoded.
198    * @param dwr Device-Watchdog-Request xml message path file for the client-sessions keep-alive. If empty string is provided (default), a default version for DWR will be encoded.
199    */
200   void setClientCERandDWR(const std::string & cer = "", const std::string & dwr = "") throw(anna::RuntimeException);
201
202   /**
203    * Sets the watchdog period (DWR) for client-sessions.
204    * Its recommended to set this global configuration although it is possible to configure each client-session separately.
205    *
206    * @param wp Watchdog period.
207    */
208   void setWatchdogPeriod(const anna::Millisecond & wp) throw(anna::RuntimeException);
209
210   /**
211    * Gets the number of client-sessions per server.
212    * \return numberOfClientSessionsPerServer Number of client-sessions per server.
213    */
214   int getNumberOfClientSessionsPerServer() const throw() { return a_numberOfClientSessionsPerServer; }
215
216   /**
217    * Sets the number of client-sessions per server.
218    * Its recommended to set this global configuration although it is possible to configure each client-session separately.
219    * \param numberOfClientSessionsPerServer Number of client-sessions per server.
220    */
221   void setNumberOfClientSessionsPerServer(int numberOfClientSessionsPerServer) throw() { a_numberOfClientSessionsPerServer = numberOfClientSessionsPerServer; }
222
223
224   /**
225    * Returns client-session instance identified by (address, port, socketId) provided.
226    *
227    * \param addr Diameter server address (ip or hostname).
228    * \param port Diameter server port.
229    * @param socketId Diameter server socket id.
230    * \param emode Action when no client-session is found with provided parameters (Throw/Ignore).
231    *
232    * \return The client-session instance identified by (address, port, socketId) provided.
233    *
234    * \warning If no client-session found, an exception is launched by default.
235    */
236   ClientSession* findClientSession(const std::string & addr, int port, int socketId, anna::Exception::Mode::_v emode = anna::Exception::Mode::Throw) throw(anna::RuntimeException);
237
238
239   /**
240    * Same as #findClientSession, but providing client session key (<address>:<port>|<socket id>)
241    */
242   ClientSession* findClientSession(const std::string & key, anna::Exception::Mode::_v emode = anna::Exception::Mode::Throw) throw(anna::RuntimeException);
243
244
245   /**
246    * Returns server instance identified by pair (address, port) provided.
247    *
248    * \param addr Diameter server address (ip or hostname).
249    * \param port Diameter server port.
250    * \param emode Action when no client-session is found with provided parameters (Throw/Ignore).
251    *
252    * \return The server instance identified by pair (address, port) provided.
253    *
254    * \warning If no server found, an exception is launched by default.
255    */
256   Server* findServer(const std::string & addr, int port, anna::Exception::Mode::_v emode = anna::Exception::Mode::Throw) throw(anna::RuntimeException);
257
258   /**
259    * Returns entity instance identified by internal index.
260    *
261    * \param socketList Diameter entity servers list.
262    * \param emode Action when no client-session is found with provided parameters (Throw/Ignore).
263    *
264    * \return The entity instance identified by id provided.
265    *
266    * \warning If no entity found, an exception is launched by default.
267    */
268   Entity* findEntity(const socket_v & socketList, anna::Exception::Mode::_v emode = anna::Exception::Mode::Throw) throw(anna::RuntimeException);
269
270   /**
271    * Returns entity instance identified by internal index.
272    *
273    * \param addr1 Diameter primary server address (ip or hostname).
274    * \param port1 Diameter primary server port.
275    * \param addr2 Diameter secondary server address (ip or hostname).
276    * \param port2 Diameter secondary server port.
277    * \param emode Action when no client-session is found with provided parameters (Throw/Ignore).
278    *
279    * \return The entity instance identified by id provided.
280    *
281    * \warning If no entity found, an exception is launched by default.
282    */
283   Entity* findEntity(const std::string & addr1, int port1, const std::string & addr2, int port2, anna::Exception::Mode::_v emode = anna::Exception::Mode::Throw) throw(anna::RuntimeException);
284
285   /**
286    * Creates a diameter entity with provided parameters.
287    *
288    * Depending on auto-bind configuration, capabilities exchange request will be or won't be performed over the entity client-sessions.
289    *
290    * \param socketList Diameter server priority list (priority-ordered) in order to define whole entity.
291    * @param description Optional entity description (empty by default)
292    *
293    * \return The entity created or exception when any server (address/port) already exists for another entity.
294    *
295    * \warning The entity won't be almost operative until a notification by mean 'ClientSession::eventResponse'
296    * indicates that 'ClassCode::Bind' has been correctly performed for any included client-session.
297    */
298   Entity* createEntity(const socket_v & socketList, const std::string & description = "")
299   throw(anna::RuntimeException);
300
301   /**
302    * Creates a standard (dual) diameter entity with provided parameters.
303    *
304    * Depending on auto-bind configuration, capabilities exchange request will be or won't be performed over the entity client-sessions.
305    *
306    * \param addr1 Diameter primary server address (ip or hostname).
307    * \param port1 Diameter primary server port.
308    * \param addr2 Diameter secondary server address (ip or hostname).
309    * \param port2 Diameter secondary server port.
310    * @param description Optional entity description (empty by default)
311    *
312    * \return The standard entity created or exception when any server (address/port) already exists for another entity.
313    *
314    * \warning The entity won't be almost operative until a notification by mean 'ClientSession::eventResponse'
315    * indicates that 'ClassCode::Bind' has been correctly performed for any included client-session.
316    */
317   Entity* createEntity(const std::string & addr1, int port1, const std::string & addr2, int port2, const std::string & description = "")
318   throw(anna::RuntimeException);
319
320
321   /**
322    * Returns local server instance identified by pair (address, port) provided.
323    *
324    * @param addr Diameter server socket address (ip or hostname).
325    * @param port Diameter server socket port.
326    * \param emode Action when no local server is found with provided parameters (Throw/Ignore).
327    *
328    * \return The local server instance identified by pair (address, port) provided.
329    *
330    * \warning If no local server found, an exception is launched by default.
331    */
332   LocalServer* findLocalServer(const std::string & addr, int port, anna::Exception::Mode::_v emode = anna::Exception::Mode::Throw) throw(anna::RuntimeException);
333
334   /**
335    * Returns server-session instance identified by INetAddress serialization provided.
336    *
337    * @param socketId Hash for Client Socket INetAddress serialization
338    * \param emode Action when no server-session is found with provided parameters (Throw/Ignore).
339    *
340    * \return The server-session instance identified by global unique socketId provided.
341    *
342    * \warning If no server-session found, an exception is launched by default.
343    */
344   ServerSession* findServerSession(int socketId, anna::Exception::Mode::_v emode = anna::Exception::Mode::Throw) throw(anna::RuntimeException);
345
346   /**
347    * Creates a diameter local server with provided parameters.
348    *
349    * Server socket address could be an IPv4 or hostname. Default port will be standard 3868 for diameter agents,
350    * but any other could be configured. Socket server could be created with any max accepted connections: zero
351    * value means temporarily disabled and negative values assume no limit (shared bind) for incomming connections.
352    *
353    * @param addr Diameter server socket address (ip or hostname).
354    * @param port Diameter server socket port (standard 3868 by default).
355    * @param maxConnections Diameter server max sessions allowed (no limit by default).
356    * @param allowedInactivityTime Max inactivity time for server sessions over the local server before being reset.
357    * @param category Optional socket server category (1 by default).
358    * @param description Optional socket server description (empty by default).
359    *
360    * \return The local server created or exception when is already created.
361    */
362   LocalServer *createLocalServer(const std::string & addr, int port = Session::DefaultPort, int maxConnections = -1, const anna::Millisecond & allowedInactivityTime = ServerSession::DefaultAllowedInactivityTime, int category = 1, const std::string & description = "")
363   throw(anna::RuntimeException);
364
365
366   /**
367      Close all the engine resources (entities and local servers)
368      Optionally all resources may be freed passing true
369
370      @param destroy Free all engine entity resources
371   */
372   void close(bool destroy = false) throw(anna::RuntimeException) { closeEntities(destroy); closeLocalServers(destroy); }
373
374
375   /**
376      Close all the engine entities (close servers, then close client-sessions within them). Depending on client-session configuration
377      ('OnDisconnect' behaviour), pending answers will be wait (graceful) or ignored (immediate-abrupt close).
378      Optionally all entities resources may be freed passing true; in this case, close is immediately performed:
379      @param destroy Free all engine entity resources
380   */
381   void closeEntities(bool destroy = false) throw(anna::RuntimeException);
382
383
384   /**
385    * Close entity servers (then, client-sessions included) and optionally free resources including entity itself.
386    * If entity is null, this operation has no effect.
387    *
388    * \param entity Diameter entity to be closed.
389    * \param destroy Deletes entity over the engine and all its resources.
390    */
391   void closeEntity(Entity* entity, bool destroy = false) throw(anna::RuntimeException);
392
393
394   /**
395      Close all the engine local server sockets including their children server sessions.
396      Optionally all local server resources may be freed passing true.
397
398      @param destroy Free all engine local servers resources and server sessions within them.
399   */
400   void closeLocalServers(bool destroy = false) throw(anna::RuntimeException);
401
402   /**
403    * Close local server socket and its children server sessions.
404    * This is useful when detecting service lost. When service is ready to handle traffic, a new server socket would
405    * be created by mean #LocalServer::enable() and new connections could be accepted.
406    * Optionally local server resources may be freed passing true.
407    *
408    * \param localServer Local server to be closed.
409    * \param destroy Deletes local server over engine and all its resources (server sessions within it).
410    */
411   void closeLocalServer(LocalServer * localServer, bool destroy = false) throw(anna::RuntimeException);
412
413   /**
414      Gets the number of requests messages over-the-air for entities.
415
416      @return OTA messages.
417   */
418   int getOTARequestsForEntities() const throw();
419
420   /**
421      Gets the number of requests messages over-the-air for local servers.
422
423      @return OTA messages.
424   */
425   int getOTARequestsForLocalServers() const throw();
426
427   /**
428      Gets the number of requests messages over-the-air for entities plus local servers.
429
430      @return OTA messages.
431   */
432   int getOTARequests() const throw() { return (getOTARequestsForEntities() + getOTARequestsForLocalServers()); }
433
434   /**
435      Returns idle state (no pending answers) for entities.
436
437      @return Idle state.
438   */
439   bool idleForEntities() const throw() { return (getOTARequestsForEntities() == 0); }
440
441   /**
442      Returns idle state (no pending answers).
443
444      @return Idle state.
445   */
446   bool idleForLocalServers() const throw() { return (getOTARequestsForLocalServers() == 0); }
447
448   /**
449      Returns idle state (no pending answers for entities or local servers).
450
451      @return Idle state.
452   */
453   bool idle() const throw() { return (getOTARequests() == 0); }
454
455   /**
456      Sent a message to all the engine entities.
457      It is used, i.e., in Disconnect-Peer-Request procedure over the engine.
458
459      \param message Message which is being sent.
460
461      @return Returns true (success) only when broadcast is success over all the engine entities. If any entity fails,
462      then false is returned. Broadcast try to send all over the resources in spite of any fail.
463   */
464   bool broadcastEntities(const Message*message) throw(anna::RuntimeException);
465   bool broadcastEntities(const Message& message) throw(anna::RuntimeException) { return broadcastEntities(&message); }
466
467   /**
468      Sent a message through all the engine local servers.
469      It is used, i.e., in Disconnect-Peer-Request procedure over the engine.
470
471      \param message Message which is being sent.
472
473      @return Returns true (success) only when broadcast is success over all the engine local servers. If any local server fails,
474      then false is returned. Broadcast try to send all over the resources in spite of any fail.
475   */
476   bool broadcastLocalServers(const Message*message) throw(anna::RuntimeException);
477   bool broadcastLocalServers(const Message& message) throw(anna::RuntimeException) { return broadcastLocalServers(&message); }
478
479   /**
480   * Class string representation
481   *
482   * @return String with class content
483   */
484   virtual std::string asString(void) const throw();
485
486   /**
487      Class XML representation.
488      \param parent XML node over which we will put instance information.
489      \return XML documentcon with class content.
490   */
491   virtual anna::xml::Node* asXML(anna::xml::Node* parent) const throw();
492
493
494   /**
495      When there is not bound server session over the engine, this virtual method will be invoked.
496      Applications must decide to do any other tasks at this idle/isolated situation.
497      Default implementation do nothing.
498   */
499   virtual void availabilityLostForLocalServers(Engine *) const throw() {;}
500
501   /**
502      When there is any bound server session over the engine, this virtual method will be invoked.
503      Applications must decide to do be ready for incoming traffic.
504      Default implementation do nothing.
505   */
506   virtual void availabilityRecoveredForLocalServers(Engine *) const throw() {;}
507
508   /**
509      When there is not bound entity over the engine, this virtual method will be invoked.
510      Many applications must change communicator status to Unavailable when no engines are available.
511      Default implementation do nothing.
512   */
513   virtual void availabilityLostForEntities(Engine *) const throw() {;}
514
515   /**
516      When there is any bound entity over the engine, this virtual method will be invoked.
517      Many applications must recover communicator status to Available when any engine are available.
518      Default implementation do nothing.
519   */
520   virtual void availabilityRecoveredForEntities(Engine *) const throw() {;}
521
522   /**
523      When there is not bound server-session over the local server, this virtual method will be invoked.
524      Default implementation do nothing.
525   */
526   virtual void availabilityLost(LocalServer *) const throw() {;}
527
528   /**
529      When there is any bound server-session over the local server, this virtual method will be invoked.
530      Default implementation do nothing.
531   */
532   virtual void availabilityRecovered(LocalServer *) const throw() {;}
533
534   /**
535      When there is not bound server over the entity, this virtual method will be invoked.
536      Default implementation do nothing.
537   */
538   virtual void availabilityLost(Entity *) const throw() {;}
539
540   /**
541      When there is any bound server over the entity, this virtual method will be invoked.
542      Default implementation do nothing.
543   */
544   virtual void availabilityRecovered(Entity *) const throw() {;}
545
546   /**
547      When there is not bound client-session over the server, this virtual method will be invoked.
548      Default implementation do nothing.
549   */
550   virtual void availabilityLost(Server *) const throw() {;}
551
552   /**
553      When there is any bound client-session over the server, this virtual method will be invoked.
554      Default implementation do nothing.
555   */
556   virtual void availabilityRecovered(Server *) const throw() {;}
557
558   /**
559      When a subyacent client session is going to be bound, this method is invoked before.
560      Default implementation do nothing.
561   */
562   virtual void bindingClientSession(const ClientSession *) const throw() {;}
563
564   /**
565    * Class user should implement this method in order to define Disconnect-Peer-Answer for last received DPR.
566    * Origin-Host and Origin-Realm are configured at comm::Engine with hostname and FQDN (Fully Qualified Domain Name).
567    * Default implementation imply DPA with DIAMETER_SUCCESS Result-Code, allowing remote disconnection.
568    * Any other implementation is responsible to build a valid DPA diameter message.
569    * DPR/DPA procedure is disabled with empty definition of this method: no DPA will be sent when DPR is received.
570    *
571    * @param dpa DPA datablock passed as reference
572    * @param dpr Corresponding DPR received (sequence values must be taken into account in order to build DPA)
573   */
574   virtual void readDPA(anna::DataBlock &dpa, const anna::DataBlock & dpr) throw();
575
576   /**
577    * Class user should implement this method in order to define Capabilities-Exchange-Answer for received CER over server socket.
578    * Origin-Host and Origin-Realm are configured at comm::Engine with hostname and FQDN (Fully Qualified Domain Name).
579    * Default implementation imply CEA with DIAMETER_SUCCESS Result-Code, and own domain node parameters, but application should
580    * analyze the CER message in order to accept it or not (with apropiate non-success Result-Code).
581    * Any other implementation is responsible to build a valid CEA diameter message:
582    *
583    * If one peer sends a CER message to another Peer and receiver does not have support for
584    *
585    *  1) any common application then it must return the CEA with Result-Code Avp set to DIAMETER_NO_COMMON_APPLICATION
586    *     and should disconnect the transport layer connection (automatically done by diameter::comm module).
587    *  2) no common security mechanism then it must return the CEA with Result-Code Avp set to DIAMETER_NO_COMMON_SECURITY
588    *     and should disconnect the transport layer connection (automatically done by diameter::comm module).
589    *  3) if CER is received from any unknown peer then receiver should discard the message, or send the CEA with the
590    *     Result-Code Avp set to DIAMETER_UNKNOWN_PEER.
591    *
592    *  If the local implementation policy permits to receive CER from unknown hosts, a successful CEA MAY be returned,
593    *  and the life time of the peer entry in PEER-Table is equal to the lifetime of the transport connection.
594    *  If in any case transport connection fails then all the pending transactions destined to the unknown peer can be discarded.
595    *
596    *  The CER and CEA messages MUST NOT be proxied, redirected or relayed. Since CER/CEA messages can not be proxied, but still
597    *  it is possible that proxy will receive a CER message and proxy does not have any peer to handle the application requested
598    *  in CER, in this case proxy set the E bit in CEA and set the Result-Code Avp to DIAMETER_UNABLE_TO_DELIVER, sends back to
599    *  CER generator peer.
600    *
601    * @param cea CEA datablock passed as reference. Empty cea implies to discard CER received.
602    * @param cer Corresponding CER received (sequence values must be taken into account in order to build CEA)
603   */
604   virtual void readCEA(anna::DataBlock &cea, const anna::DataBlock & cer) throw();
605
606   /**
607    * Class user should implement this method in order to define Device-Watchdog-Answer for received DWR over server socket.
608    * Origin-Host and Origin-Realm are configured at comm::Engine with hostname and FQDN (Fully Qualified Domain Name).
609    * Default implementation imply DWA with DIAMETER_SUCCESS Result-Code, and own domain node parameters.
610    * Any other implementation is responsible to build a valid DWA diameter message.
611    *
612    * @param dwa DWA datablock passed as reference
613    * @param dwr Corresponding DWR received (sequence values must be taken into account in order to build DWA)
614   */
615   virtual void readDWA(anna::DataBlock &dwa, const anna::DataBlock & dwr) throw();
616
617   /**
618    * DRA basics: CER information is gathered on every server session managed by the diameter comm engine. You could send the message to a
619    * specific realm, and optionally you could restrict a host inside it. This is common for requests (answers are normally sent through
620    * the same source server session where the request was received). Exception will be thrown if not found an available server session
621    * for the Destination-Realm and/or Destination-Host provided
622    *
623    * @param destinationRealm If empty, NULL is returned, because is nonsense to specify a host out of realm context
624    * @param destinationHost If empty, no restriction is applied within the target realm node. Random delivery is applied for the available server sessions
625    *
626    * @return transactional response reference, or NULL if answer is sent
627    */
628   const Response* sendRealmHost(const Message* message, const std::string &destinationRealm, const std::string &destinationHost = "") throw(anna::RuntimeException);
629
630   /**
631      Reset engine statistics.
632      At the moment, only diameter servers processing time is observed.
633   */
634   void resetStatistics() throw();
635
636
637   /**
638    * Engine lazy initialization. Used if the engine is created when application is already running; for example
639    * on dynamic realms registration. At the moment is not actually needed (nothing is done at initialization),
640    * but it is recommended to start the component and set its state as 'running' from the point of view of the
641    * application.
642    */
643   void lazyInitialize() throw(RuntimeException);
644
645
646 protected:
647   /**
648      Constructor.
649
650      @param className Component class name
651      @param baseProtocolDictionary This will be used internally when calling \@readCEA, \@readDPA and \@readDWA on
652      servers, and also used during base protocol messages tracing (if debug traces are enabled). You could provide
653      NULL, but you must be sure that neither of the former situations are going to happen or an exception will be
654      thrown (using setClientCERandDWR with DataBlock arguments, expects externally encoded messages and could help).
655      It is recommended to set a base protocol dictionary loading 'source/diameter/stack/setups' dictionaries (for
656      example 'avps_ietf.xml' plus 'commands_baseProtocol.xml'), or using the dictionary creation API. The dictionary
657      could also be an application stack, the only condition is containing the resources to build base protocol messages.
658   */
659   Engine(const char *className, const stack::Dictionary *baseProtocolDictionary);
660
661   // INTERNAL CREATORS AND CLOSE METHODS
662   Server *createServer(Entity*, const socket_t&) throw(anna::RuntimeException);
663   void closeServer(Server*, bool) throw(anna::RuntimeException);
664   ClientSession *createClientSession(Server*, int) throw(anna::RuntimeException);
665   void closeClientSession(ClientSession*, bool) throw(anna::RuntimeException);
666
667   // INTERNAL ALLOCATORS
668   Server* allocateServer() throw();
669   void releaseServer(Server*) throw();
670   ClientSession* allocateClientSession() throw();
671   void releaseClientSession(ClientSession*) throw();
672
673
674   /**
675      Entity allocator method.
676
677      It is recommended to use anna::Recycler for entities creation/releasing.
678
679      \see anna::Recycler
680   */
681   virtual Entity* allocateEntity() throw() { return NULL; }
682
683
684   /**
685      Invoked to free entities.
686      \see anna::Recycler
687   */
688   virtual void releaseEntity(Entity*) throw() {;}
689
690
691   /**
692      Local server allocator method.
693
694      It is recommended to use anna::Recycler for entities creation/releasing.
695
696      \see anna::Recycler
697   */
698   virtual LocalServer* allocateLocalServer() throw() { return NULL; }
699
700
701   /**
702      Invoked to free local servers.
703      \see anna::Recycler
704   */
705   virtual void releaseLocalServer(LocalServer*) throw() {;}
706
707
708 private:
709
710   // Internal use: tracing and readCEA/DPA/DWA
711   codec::Engine a_baseProtocolCodecEngine;
712
713   std::string a_originRealm;
714   std::string a_originHost;
715   bool a_autoBind;
716   int a_numberOfClientSessionsPerServer;
717
718
719   // ClientSessions messages:
720   anna::DataBlock a_cer;
721   anna::DataBlock a_dwr;
722   anna::Millisecond a_watchdogPeriod;
723
724 //   // ServerSessions messages:
725 //   anna::DataBlock a_cea;
726 //   anna::DataBlock a_dwa;
727
728   // Client connectivity
729   anna::Millisecond a_maxConnectionDelay;
730
731
732   // Availability
733   bool a_availableForEntities; // any of the entities must be bound
734   void availabilityLostForEntities() throw();
735   void availabilityRecoveredForEntities() throw();
736   bool refreshAvailabilityForEntities() throw(); // return true if change
737
738   bool a_availableForLocalServers; // any of the local servers must be bound
739   void availabilityLostForLocalServers() throw();
740   void availabilityRecoveredForLocalServers() throw();
741   bool refreshAvailabilityForLocalServers() throw(); // return true if change
742
743   void eraseDeprecatedIdleEntities() throw();
744
745   // Component:
746   void do_initialize() throw(anna::RuntimeException);
747   void do_stop() throw();
748
749   // Integrity:
750   void checkEntityCollision(const socket_v &) throw(anna::RuntimeException);
751   void assertBaseProtocolHealth() throw(anna::RuntimeException); // checks the dictionary
752
753
754   //  Gets the base protocol codec engine used internally.
755   //  This engine is initializaed on constructor with the base protocol dictionary.
756   //  The reason to not reuse any other codec engine from the application is to have this one isolated with no interference
757   //  regarding configuration changes (validation depth/mode, fix mode, etc.).
758   //
759   //  @return Pointer to the internal base protocol codec engine
760   codec::Engine *getBaseProtocolCodecEngine() const throw() { return const_cast<codec::Engine *>(&a_baseProtocolCodecEngine); }
761
762   //////////////////////////
763   // CLIENT FUNCTIONALITY //
764   //////////////////////////
765
766   //typedef int clientSession_key; // exclusiveHash('ADDR:PORT|id')
767   typedef std::string clientSession_key; // 'ADDR:PORT|id'
768   typedef std::map <clientSession_key, ClientSession*> clientSession_container;
769   typedef clientSession_container::value_type clientSession_value_type;
770   typedef clientSession_container::iterator clientSession_iterator;
771   typedef clientSession_container::const_iterator const_clientSession_iterator;
772   clientSession_container a_clientSessions;
773   anna::Recycler<ClientSession> a_clientSessionsRecycler;
774   clientSession_iterator clientSession_find(const clientSession_key&) throw();
775   clientSession_iterator clientSession_begin() throw() { return a_clientSessions.begin(); }
776   clientSession_iterator clientSession_end() throw() { return a_clientSessions.end(); }
777   static ClientSession* clientSession(clientSession_iterator ii) throw() { return ii->second; }
778   const_clientSession_iterator clientSession_begin() const throw() { return a_clientSessions.begin(); }
779   const_clientSession_iterator clientSession_end() const throw() { return a_clientSessions.end(); }
780   static const ClientSession* clientSession(const_clientSession_iterator ii) throw() { return ii->second; }
781
782   typedef socket_t server_key;
783   server_key getServerKey(const std::string & addr, int port) const throw();
784   typedef std::map <server_key, Server*> server_container;
785   typedef server_container::value_type server_value_type;
786   typedef server_container::iterator server_iterator;
787   typedef server_container::const_iterator const_server_iterator;
788   server_container a_servers;
789   anna::Recycler<Server> a_serversRecycler;
790   server_iterator server_find(const server_key&) throw();
791   server_iterator server_begin() throw() { return a_servers.begin(); }
792   server_iterator server_end() throw() { return a_servers.end(); }
793   static Server* server(server_iterator ii) throw() { return ii->second; }
794   const_server_iterator server_begin() const throw() { return a_servers.begin(); }
795   const_server_iterator server_end() const throw() { return a_servers.end(); }
796   static const Server* server(const_server_iterator ii) throw() { return ii->second; }
797
798   //typedef int entity_key; // exclusiveHash('IP1:PORT1 IP2:PORT2 IP3:PORT3 ...')
799   typedef std::string entity_key; // 'ADDR1:PORT1 ADDR2:PORT2 ADDR3:PORT3 ...'
800   entity_key getEntityKey(const socket_v &) const throw();
801   entity_key getEntityKey(const std::string & addr1, int port1, const std::string & addr2, int port2) const throw();
802   typedef std::map <entity_key, Entity*> entity_container;
803   typedef entity_container::value_type entity_value_type;
804   typedef entity_container::iterator entity_iterator;
805   typedef entity_container::const_iterator const_entity_iterator;
806   entity_container a_entities;
807   entity_iterator entity_find(const entity_key&) throw();
808   entity_iterator entity_begin() throw() { return a_entities.begin(); }
809   entity_iterator entity_end() throw() { return a_entities.end(); }
810   static Entity* entity(entity_iterator ii) throw() { return ii->second; }
811   const_entity_iterator entity_begin() const throw() { return a_entities.begin(); }
812   const_entity_iterator entity_end() const throw() { return a_entities.end(); }
813   static const Entity* entity(const_entity_iterator ii) throw() { return ii->second; }
814
815
816   //////////////////////////
817   // SERVER FUNCTIONALITY //
818   //////////////////////////
819
820   // Local servers
821   typedef std::map <socket_t, LocalServer*> localServer_container;
822   typedef localServer_container::value_type localServer_value_type;
823   typedef localServer_container::iterator localServer_iterator;
824   typedef localServer_container::const_iterator const_localServer_iterator;
825   localServer_container a_localServers;
826   localServer_iterator localServer_find(const socket_t&) throw();
827   localServer_iterator localServer_begin() throw() { return a_localServers.begin(); }
828   localServer_iterator localServer_end() throw() { return a_localServers.end(); }
829   static LocalServer* localServer(localServer_iterator ii) throw() { return ii->second; }
830   const_localServer_iterator localServer_begin() const throw() { return a_localServers.begin(); }
831   const_localServer_iterator localServer_end() const throw() { return a_localServers.end(); }
832   static const LocalServer* localServer(const_localServer_iterator ii) throw() { return ii->second; }
833
834   // Server sessions are managed within LocalServer (not at engine) due to dynamic creation nature
835   // Here we maintain the Destination-Realm / Destination-Host maps for DRA basics:
836   typedef std::vector<ServerSession*> server_sessions_vector_t;
837   typedef server_sessions_vector_t::const_iterator server_sessions_it_t;
838   typedef server_sessions_vector_t::iterator server_sessions_nc_it_t;
839   typedef std::map <std::string /* Destination-Host */, server_sessions_vector_t> dh_server_sessions_map_t;
840   typedef dh_server_sessions_map_t::const_iterator dh_server_sessions_it_t;
841   typedef dh_server_sessions_map_t::iterator dh_server_sessions_nc_it_t;
842   typedef std::map <std::string /* Destination-Realm */, dh_server_sessions_map_t> dr_dh_server_sessions_map_t;
843   typedef dr_dh_server_sessions_map_t::const_iterator dr_dh_server_sessions_it_t;
844   typedef dr_dh_server_sessions_map_t::iterator dr_dh_server_sessions_nc_it_t;
845   dr_dh_server_sessions_map_t a_dr_dh_server_sessions;
846   void manageDrDhServerSession(ServerSession *ss, bool register_or_desregister) throw();
847
848   friend class Session;
849   friend class ClientSession;
850   friend class ServerSession;
851   friend class ServerSocket;
852   friend class Server;
853   friend class Entity;
854   friend class LocalServer;
855   //friend class Message;
856 };
857
858 }
859 }
860 }
861
862 #endif
863