ReflectServer Class Reference

This class represents a MUSCLE server: It runs on a centrally located machine, and many clients may connect to it simultaneously. More...

#include <ReflectServer.h>

Inheritance diagram for ReflectServer:

Inheritance graph
[legend]
List of all members.

Public Member Functions

 ReflectServer (MemoryAllocator *optMemoryUsageTracker=NULL)
 Constructor.
virtual ~ReflectServer ()
 Destructor.
virtual status_t ServerProcessLoop ()
 The main loop for the message reflection server.
virtual status_t PutAcceptFactory (uint16 port, const ReflectSessionFactoryRef &sessionFactoryRef, const ip_address &optInterfaceIP=invalidIP, uint16 *optRetPort=NULL)
 This function may be called zero or more times before ServerProcessLoop() Each call adds one port that the server should listen on, and the factory object to use to create sessions when a connection is received on that port.
virtual status_t RemoveAcceptFactory (uint16 port, const ip_address &optInterfaceIP=invalidIP)
 Remove a listening port callback that was previously added by PutAcceptFactory().
virtual status_t ReadyToRun ()
 Called after the server is set up, but just before accepting any connections.
virtual status_t AddNewSession (const AbstractReflectSessionRef &ref, const SocketRef &socket)
 Adds a new session that uses the given socket for I/O.
status_t AddNewSession (const AbstractReflectSessionRef &ref)
 Convenience method: Calls AddNewSession() with a NULL Socket reference, so the session's default socket (obtained by calling ref()->CreateDefaultSocket()) will be used.
status_t AddNewConnectSession (const AbstractReflectSessionRef &ref, const ip_address &targetIPAddress, uint16 port, uint64 autoReconnectDelay=MUSCLE_TIME_NEVER)
 Like AddNewSession(), only creates a session that connects asynchronously to the given IP address.
status_t AddNewDormantConnectSession (const AbstractReflectSessionRef &ref, const ip_address &targetIPAddress, uint16 port, uint64 autoReconnectDelay=MUSCLE_TIME_NEVER)
 Like AddNewConnectSession(), except that the added session will not initiate a TCP connection to the specified address immediately.
virtual void Cleanup ()
 Should be called just before the ReflectServer is to be destroyed.
MessageGetCentralState ()
 Accessor to our central-state repository message.
void SetDoLogging (bool log)
 Set whether or not we should log informational messages when sessions are added and removed, etc.
bool GetDoLogging () const
 Returns whether or not we should be logging informational messages.
virtual const char * GetServerName () const
 Returns a human-readable string that describes the type of server that is running.
const Hashtable< const String *,
AbstractReflectSessionRef > & 
GetSessions () const
 Returns a read-only reference to our table of sessions currently attached to this server.
AbstractReflectSessionRef GetSession (const String &sessionName) const
 Convenience method: Given a session ID string, returns a reference to the session, or a NULL reference if no such session exists.
AbstractReflectSessionRef GetSession (uint32 sessionID) const
 Convenience method: Given a session ID number, returns a reference to the session, or a NULL reference if no such session exists.
const Hashtable< IPAddressAndPort,
ReflectSessionFactoryRef > & 
GetFactories () const
 Returns an iterator that allows one to iterate over all the session factories currently attached to this server.
ReflectSessionFactoryRef GetFactory (uint16 port, const ip_address &optInterfaceIP=invalidIP) const
 Convenience method: Given a port number, returns a reference to the factory of that port, or a NULL reference if no such factory exists.
void EndServer ()
 Call this and the server will quit ASAP.
uint64 GetServerUptime () const
 Returns the number of microseconds since our main loop started.
uint32 GetNumAvailableBytes () const
 Returns the number of bytes that are currently available to be allocated, or MUSCLE_NO_LIMIT if no memory watcher was specified in the constructor.
uint32 GetMaxNumBytes () const
 Returns the maximum number of bytes that may be allocated at any given time, or MUSCLE_NO_LIMIT if no memory watcher was specified in the constructor.
uint32 GetNumUsedBytes () const
 Returns the number of bytes that are currently allocated, or MUSCLE_NO_LIMIT if no memory watcher was specified in the constructor.
Hashtable< ip_address, String > & GetAddressRemappingTable ()
 Returns a reference to a table mapping IP addresses to custom strings.
const Hashtable< ip_address,
String > & 
GetAddressRemappingTable () const
 Read-only implementation of the above.
status_t SetSignalHandlingEnabled (bool enabled)
 If you wish to have a Control-C cause your server to gracefully exit, instead of rudely just killing your server process, you can call this method to enable a signal handler that will catch the interrupt signal and cause this ReflectServer's ServerProcessLoop() to exit cleanly.
void IncrementRefCount () const
 Increments the counter and returns true iff the new value is zero.
bool DecrementRefCount () const
 Decrements the counter and returns true iff the new value is zero.
void SetManager (AbstractObjectManager *manager)
 Sets the recycle-pointer for this object.
AbstractObjectManagerGetManager () const
 Returns this object's current recyler pointer.
uint32 GetRefCount () const
 Returns this object's current reference count.
virtual uint64 GetPulseTime (uint64 now, uint64 prevResult)
 This method can be overridden to tell the PulseNodeManager when we would like to have our Pulse() method called.
virtual void Pulse (uint64 now, uint64 scheduledTime)
 Will be called at the time specified previously by GetPulseTime().
status_t PutPulseChild (PulseNode *child)
 Adds the given child into our set of child PulseNodes.
status_t RemovePulseChild (PulseNode *child)
 Attempts to remove the given child from our set of child PulseNodes.
void ClearPulseChildren ()
 Removes all children from our set of child PulseNodes.
bool ContainsPulseChild (PulseNode *child) const
 Returns true iff the given child is in our set of child PulseNodes.
uint64 GetScheduledPulseTime () const
 Returns when this object wants its call to Pulse() scheduled next, or MUSCLE_TIME_NEVER if it has no call to Pulse() currently scheduled.
uint64 GetCycleStartTime () const
 Returns the run-time at which the PulseNodeManager started calling our callbacks.
void SetSuggestedMaximumTimeSlice (uint64 maxUsecs)
 Sets the maximum number of microseconds that this class should allow its callback methods to execute for (relative to the cycle start time, as shown above).
uint64 GetSuggestedMaximumTimeSlice () const
 Returns the current suggested maximum duration of our time slice, or MUSCLE_TIME_NEVER if there is no suggested limit.
bool IsSuggestedTimeSliceExpired () const
 Convenience method -- returns true iff the current value of the run-time clock (GetRunTime64()) indicates that our suggested time slice has expired.

Protected Member Functions

virtual status_t AttachNewSession (const AbstractReflectSessionRef &ref)
 This version of AddNewSession (which is called by the previous version) assumes that the gateway, hostname, port, etc of the new session have already been set up.
status_t SendMessageToFactory (AbstractReflectSession *session, const MessageRef &msgRef, void *userData)
 Called by a session to send a message to its factory.
status_t ReplaceSession (const AbstractReflectSessionRef &newSession, AbstractReflectSession *replaceThisOne)
 Called by a session to get itself replaced (the new session will continue using the same message io streams as the old one).
void EndSession (AbstractReflectSession *which)
 Called by a session to get itself removed & destroyed.
bool DisconnectSession (AbstractReflectSession *which)
 Called by a session to force its TCP connection to be closed @ param which The session to force-disconnect.
void InvalidatePulseTime (bool clearPrevResult=true)
 Sets a flag to indicate that GetPulseTime() should be called on this object.

Friends

class AbstractReflectSession

Detailed Description

This class represents a MUSCLE server: It runs on a centrally located machine, and many clients may connect to it simultaneously.

This server can then redirect messages uploaded by any client to other clients in a somewhat efficient manner. This class can be used as-is, or subclassed if necessary. There is typically only one ReflectServer object present in a given MUSCLE server program.

Definition at line 18 of file ReflectServer.h.


Constructor & Destructor Documentation

ReflectServer::ReflectServer ( MemoryAllocator optMemoryUsageTracker = NULL  ) 

Constructor.

Parameters:
optMemoryUsageTracker If non-NULL, this tracker will be inspected by the server in order to report back to clients how much memory is currently available on the server. Note that this tracker does NOT become owned by the ReflectServer!


Member Function Documentation

virtual status_t ReflectServer::ServerProcessLoop (  )  [virtual]

The main loop for the message reflection server.

This method will not return until the server stops running (usually due to an error).

Returns:
B_NO_ERROR if the server has decided to exit peacefully, or B_ERROR if there was a fatal error during setup or execution.

virtual status_t ReflectServer::PutAcceptFactory ( uint16  port,
const ReflectSessionFactoryRef sessionFactoryRef,
const ip_address &  optInterfaceIP = invalidIP,
uint16 *  optRetPort = NULL 
) [virtual]

This function may be called zero or more times before ServerProcessLoop() Each call adds one port that the server should listen on, and the factory object to use to create sessions when a connection is received on that port.

Parameters:
port The TCP port the server will listen on. (muscled's traditional port is 2960) If this port is zero, then the server will choose an available port number to use. If this port is the same as one specified in a previous call to PutAcceptFactory(), the old factory associated with that port will be replaced with this one.
sessionFactoryRef Reference to a factory object that can generate new sessions when needed.
optInterfaceIP Optional local interface address to listen on. If not specified, or if specified as (invalidIP), then connections will be accepted from all local network interfaces.
optRetPort If specified non-NULL, then on success the port that the factory was bound to will be placed into this parameter.
Returns:
B_NO_ERROR on success, B_ERROR on failure (couldn't bind to socket?)

virtual status_t ReflectServer::RemoveAcceptFactory ( uint16  port,
const ip_address &  optInterfaceIP = invalidIP 
) [virtual]

Remove a listening port callback that was previously added by PutAcceptFactory().

Parameters:
port whose callback should be removed. If (port) is set to zero, all callbacks will be removed.
optInterfaceIP Interface(s) that the specified callbacks were assigned to in their PutAcceptFactory() call. This parameter is ignored when (port) is zero.
Returns:
B_NO_ERROR on success, or B_ERROR if a factory for the specified port was not found.

virtual status_t ReflectServer::ReadyToRun (  )  [virtual]

Called after the server is set up, but just before accepting any connections.

Should return B_NO_ERROR if it's okay to continue, or B_ERROR to abort and shut down the server.

Returns:
Default implementation returns B_NO_ERROR.

virtual status_t ReflectServer::AddNewSession ( const AbstractReflectSessionRef ref,
const SocketRef socket 
) [virtual]

Adds a new session that uses the given socket for I/O.

Parameters:
ref New session to add to the server.
socket The TCP socket that the new session should use, or a NULL reference, if the new session is to have no client connection (or use the default socket, if CreateDefaultSocket() has been overridden by the session's subclass). Note that if the session already has a gateway and DataIO installed, then the DataIO's existing socket will be used instead, and this socket will be ignored.
Returns:
B_NO_ERROR if the new session was added successfully, or B_ERROR if there was an error setting it up.

Referenced by AddNewSession().

status_t ReflectServer::AddNewConnectSession ( const AbstractReflectSessionRef ref,
const ip_address &  targetIPAddress,
uint16  port,
uint64  autoReconnectDelay = MUSCLE_TIME_NEVER 
)

Like AddNewSession(), only creates a session that connects asynchronously to the given IP address.

AttachedToServer() will be called immediately on the session, and then when the connection is complete, AsyncConnectCompleted() will be called. Other than that, however, (session) will behave like any other session, except any I/O messages for the client won't be transferred until the connection completes.

Parameters:
ref New session to add to the server.
targetIPAddress IP address to connect to
port Port to connect to at that IP address.
autoReconnectDelay If specified, this is the number of microseconds after the connection is broken that an automatic reconnect should be attempted. If not specified, an automatic reconnect will not be attempted, and the session will be removed when the connection breaks. Specifying this is equivalent to calling SetAutoReconnectDelay() on (ref).
Returns:
B_NO_ERROR if the session was successfully added, or B_ERROR on error (out-of-memory, or the connect attempt failed immediately)

status_t ReflectServer::AddNewDormantConnectSession ( const AbstractReflectSessionRef ref,
const ip_address &  targetIPAddress,
uint16  port,
uint64  autoReconnectDelay = MUSCLE_TIME_NEVER 
)

Like AddNewConnectSession(), except that the added session will not initiate a TCP connection to the specified address immediately.

Instead, it will just hang out and do nothing until you call Reconnect() on it. Only then will it create the TCP connection to the address specified here.

Parameters:
ref New session to add to the server.
targetIPAddress IP address to connect to
port Port to connect to at that IP address.
autoReconnectDelay If specified, this is the number of microseconds after the connection is broken that an automatic reconnect should be attempted. If not specified, an automatic reconnect will not be attempted, and the session will be removed when the connection breaks. Specifying this is equivalent to calling SetAutoReconnectDelay() on (ref).
Returns:
B_NO_ERROR if the session was successfully added, or B_ERROR on error (out-of-memory, or the connect attempt failed immediately)

virtual void ReflectServer::Cleanup (  )  [virtual]

Should be called just before the ReflectServer is to be destroyed.

this in a good place to put any cleanup code. Be sure to call Cleanup() of your parent class as well! (We can't just do this in the destructor, as some cleanup relies on the subclass still being functional, which it isn't when our destructor gets called!)

void ReflectServer::SetDoLogging ( bool  log  )  [inline]

Set whether or not we should log informational messages when sessions are added and removed, etc.

Default state is true.

Definition at line 139 of file ReflectServer.h.

virtual const char* ReflectServer::GetServerName (  )  const [virtual]

Returns a human-readable string that describes the type of server that is running.

Returns:
Default implementation returns "MUSCLE".

ReflectSessionFactoryRef ReflectServer::GetFactory ( uint16  port,
const ip_address &  optInterfaceIP = invalidIP 
) const

Convenience method: Given a port number, returns a reference to the factory of that port, or a NULL reference if no such factory exists.

Parameters:
port number to check
optInterfaceIP If the factory was created to listen on a specific local interface address (when it was passed in to PutAcceptFactory()), then specify that address again here. Defaults to (invalidIP), indicating a factory that listens on all local network interfaces.

Hashtable<ip_address, String>& ReflectServer::GetAddressRemappingTable (  )  [inline]

Returns a reference to a table mapping IP addresses to custom strings.

.. This table may be examined or altered. When a new connection is accepted, the ReflectServer will consult this table for the address-level MUSCLE node's name. If an entry is found, it will be used verbatim; otherwise, a name will be created based on the peer's IP address. Useful for e.g. NAT remapping...

Definition at line 198 of file ReflectServer.h.

status_t ReflectServer::SetSignalHandlingEnabled ( bool  enabled  ) 

If you wish to have a Control-C cause your server to gracefully exit, instead of rudely just killing your server process, you can call this method to enable a signal handler that will catch the interrupt signal and cause this ReflectServer's ServerProcessLoop() to exit cleanly.

Note that this function is currently implemented only under Linux and OS/X; under other operating systems it will just always return B_ERROR.

Parameters:
enabled If true, managed signal handling will be enabled; if false, it will be disabled.

virtual status_t ReflectServer::AttachNewSession ( const AbstractReflectSessionRef ref  )  [protected, virtual]

This version of AddNewSession (which is called by the previous version) assumes that the gateway, hostname, port, etc of the new session have already been set up.

Parameters:
ref The new session to add.
Returns:
B_NO_ERROR if the new session was added successfully, or B_ERROR if there was an error setting it up.

status_t ReflectServer::SendMessageToFactory ( AbstractReflectSession session,
const MessageRef msgRef,
void *  userData 
) [protected]

Called by a session to send a message to its factory.

See also:
AbstractReflectSession::SendMessageToFactory() for details.

status_t ReflectServer::ReplaceSession ( const AbstractReflectSessionRef newSession,
AbstractReflectSession replaceThisOne 
) [protected]

Called by a session to get itself replaced (the new session will continue using the same message io streams as the old one).

Returns:
B_NO_ERROR on success, B_ERROR if the new session returns an error in its AttachedToServer() method. If B_ERROR is returned, then this call is guaranteed not to have had any effect on the old session.

bool ReflectServer::DisconnectSession ( AbstractReflectSession which  )  [protected]

Called by a session to force its TCP connection to be closed @ param which The session to force-disconnect.

@ returns true iff the session has decided to terminate itself, or false if it decided to continue hanging around the server even though its client connection has been severed.

See also:
AbstractReflectSession::ClientConnectionClosed().

void RefCountable::IncrementRefCount (  )  const [inline, inherited]

Increments the counter and returns true iff the new value is zero.

Thread safe.

Definition at line 32 of file RefCount.h.

References AtomicCounter::AtomicIncrement().

bool RefCountable::DecrementRefCount (  )  const [inline, inherited]

Decrements the counter and returns true iff the new value is zero.

Thread safe.

Definition at line 35 of file RefCount.h.

References AtomicCounter::AtomicDecrement().

void RefCountable::SetManager ( AbstractObjectManager manager  )  [inline, inherited]

Sets the recycle-pointer for this object.

If set to non-NULL, this pointer is used by the ObjectPool class to recycle this object when it is no longer in use, so as to avoid the overhead of having to delete it and re-create it later on. The RefCountable class itself does nothing with this pointer. Default value is NULL.

Parameters:
manager Pointer to the new manager object to use, or NULL to use no manager.

Definition at line 44 of file RefCount.h.

uint32 RefCountable::GetRefCount (  )  const [inline, inherited]

Returns this object's current reference count.

Note that the value returned by this method is volatile in multithreaded environments, so it may already be wrong by the time it is returned. Be careful!

Definition at line 54 of file RefCount.h.

References AtomicCounter::GetCount().

virtual uint64 PulseNode::GetPulseTime ( uint64  now,
uint64  prevResult 
) [virtual, inherited]

This method can be overridden to tell the PulseNodeManager when we would like to have our Pulse() method called.

This method is guaranteed to be called only during the following times:

  1. When the PulseNode is first probed by the PulseNodeManager
  2. Immediately after our Pulse() method has returned
  3. Soon after InvalidatePulseTime() has been called one or more times (InvalidatePulseTime() calls are merged together for efficiency)
Parameters:
now The current wall-clock time in microseconds, for convenience.
prevResult The value that this method returned the last time it was called. The very first time this method is called, this value will be passed in as MUSCLE_TIME_NEVER.
Returns:
Return MUSCLE_TIME_NEVER if you don't wish to schedule a future call to Pulse(); or return the time at which you want Pulse() to be called. Returning values less than or equal to (now) will cause Pulse() to be called as soon as possible. The default implementation always returns MUSCLE_TIME_NEVER.

Reimplemented in AbstractReflectSession, and RateLimitSessionIOPolicy.

virtual void PulseNode::Pulse ( uint64  now,
uint64  scheduledTime 
) [virtual, inherited]

Will be called at the time specified previously by GetPulseTime().

GetPulseTime() will be called again immediately after this call, to check if you want to schedule another Pulse() call for later. Default implementation is a no-op.

Parameters:
now The current wall-clock time-value in microseconds, for convenience.
scheduledTime The time this Pulse() call was scheduled to occur at, in microseconds, as previously returned by GetPulseTime(). Note that unless your computer is infinitely fast, this time will always be at least a bit less than (now), since there is a delay between when the program gets woken up to service the next Pulse() call, and when the call actually happens. (you may be able to use this value to compensate for the slippage, if it bothers you)

Reimplemented in AbstractReflectSession, and RateLimitSessionIOPolicy.

status_t PulseNode::PutPulseChild ( PulseNode child  )  [inherited]

Adds the given child into our set of child PulseNodes.

Any PulseNode in our set of children will have its pulsing needs taken care of by us, but it is not considered "owned" by this PulseNode--it will not be deleted when we are.

Parameters:
child The child to place into our set of child PulseNodes.
Returns:
B_NO_ERROR on success, or B_ERROR on failure (out of memory).

status_t PulseNode::RemovePulseChild ( PulseNode child  )  [inherited]

Attempts to remove the given child from our set of child PulseNodes.

Parameters:
child The child to remove
Returns:
B_NO_ERROR on success, or B_ERROR on failure (child wasn't in our set)

bool PulseNode::ContainsPulseChild ( PulseNode child  )  const [inline, inherited]

Returns true iff the given child is in our set of child PulseNodes.

Parameters:
child the child to look for.

Definition at line 84 of file PulseNode.h.

References PulseNode::_parent.

uint64 PulseNode::GetCycleStartTime (  )  const [inline, inherited]

Returns the run-time at which the PulseNodeManager started calling our callbacks.

Useful for any object that wants to limit the maximum duration of its timeslice in the PulseNodeManager's event loop.

Definition at line 95 of file PulseNode.h.

void PulseNode::SetSuggestedMaximumTimeSlice ( uint64  maxUsecs  )  [inline, inherited]

Sets the maximum number of microseconds that this class should allow its callback methods to execute for (relative to the cycle start time, as shown above).

Note that this value is merely a suggestion; it remains up to the subclass's callback methods to ensure that the suggestion is actually followed.

Parameters:
maxUsecs Maximum number of microseconds that the time slice should last for. If set to MUSCLE_TIME_NEVER, that indicates that there is no suggested limit.

Definition at line 104 of file PulseNode.h.

uint64 PulseNode::GetSuggestedMaximumTimeSlice (  )  const [inline, inherited]

Returns the current suggested maximum duration of our time slice, or MUSCLE_TIME_NEVER if there is no suggested limit.

Default value is MUSCLE_TIME_NEVER.

Definition at line 109 of file PulseNode.h.

bool PulseNode::IsSuggestedTimeSliceExpired (  )  const [inline, inherited]

Convenience method -- returns true iff the current value of the run-time clock (GetRunTime64()) indicates that our suggested time slice has expired.

This method is cheap to call often.

Definition at line 115 of file PulseNode.h.

void PulseNode::InvalidatePulseTime ( bool  clearPrevResult = true  )  [protected, inherited]

Sets a flag to indicate that GetPulseTime() should be called on this object.

Call this whenever you've decided to reschedule your pulse time outside of a Pulse() event.

Parameters:
clearPrevResult if true, this call will also clear the stored prevResult value, so that the next time GetPulseTime() is called, prevResult is passed in as MUSCLE_TIME_NEVER. If false, the prevResult value will be left alone.

Referenced by AbstractReflectSession::SetAutoReconnectDelay().


The documentation for this class was generated from the following file:
Generated on Thu Jun 5 17:48:29 2008 for MUSCLE by  doxygen 1.5.1