Files

702 lines
24 KiB
C++

/**
* @file include/ActivMiddleware/ActivFramework/ManagedEndPoint.h
*
* @brief Header file for managed endpoint class.
*/
#if (!defined ACTIV_FRAMEWORK_MANAGED_END_POINT_H)
#define ACTIV_FRAMEWORK_MANAGED_END_POINT_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/IEndPoint.h"
#include "ActivMiddleware/ActivFramework/IHeap.h"
#include "ActivMiddleware/ActivFramework/PostMessageHelper.h"
#include "ActivMiddleware/ActivFramework/TraceBuffer.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include "ActivMiddleware/ActivBase/IniFileParser.h"
#include "ActivMiddleware/ActivBase/IntervalTimer.h"
#include "ActivMiddleware/ActivBase/ProcessorAffinity.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
#include ACTIV_BOOST_INCLUDE(optional.hpp)
#include ACTIV_BOOST_INCLUDE(utility/explicit_operator_bool.hpp)
//! Activ namespace.
namespace Activ
{
class Address;
class Application;
class Component;
class DefaultComponent;
class HeapMessage;
class IAddressableEndPoint;
class ManagedEndPointImpl;
class UiMenu;
class EventManager;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Managed endpoint class.
*
* A managed endpoint contains the underlying endpoint object and manages components that are attached to the endpoint
* and the thread that is processing messages from the endpoint.
*/
class ManagedEndPoint : private Boost::noncopyable
{
public:
typedef std::set<PortId> PortIdSet; ///< Type of the set of port ids.
//! Settings.
class Settings
{
public:
//! Default constructor.
ACTIV_FRAMEWORK_API
Settings();
/**
* @brief Read settings from an ini file section.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API
void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
//! Settings for managing the endpoint receiving messages from a particular source endpoint.
class SourceEndPointInfo
{
public:
// Default constructor.
ACTIV_FRAMEWORK_API
SourceEndPointInfo();
size_t m_maxMessagesToProcess; ///< Default: 0 (use Settings::m_maxMessagesPerEndPoint). Max messages to process from this source endpoint before moving to the next.
};
typedef std::map<String, SourceEndPointInfo> SourceEndPointInfoMap;
/**
* @brief The message processing timeout when using the internal RunHelper (Run() or StartThread()).
*
* Default: [NotInitialized] (infinite) unless ACTIV_MANAGED_END_POINT_SHOULD_POLL=1 then m_messageLoopTimeout will be 0
* and the thread will run CPU busy.
*/
UInt m_messageLoopTimeout;
Boost::optional<IAddressableEndPoint::Type> m_type; ///< Default: IAddressableEndPoint::TYPE_EVENT_MANAGED_PARENT (debug); TYPE_EVENT_MANAGED (release).
IEndPoint::NotificationType m_notificationType; ///< Default: IEndPoint::NOTIFICATION_TYPE_DEFAULT.
bool m_enableSingleThreadedAccess; ///< Default: false. When set assumes methods that modify the state of the object are single threaded, never attempts to pause/resume threads.
HANDLE m_completionPort; ///< Default: 0. For IEndPoint::NOTIFICATION_TYPE_COMPLETION_PORT only.
PortId m_initialComponentListSize; ///< Default: 64.
PortId m_minFreeComponentListSize; ///< Default: 32. This number of slots must be in the free list before a port id can be re-used.
PortIdSet m_reservedPortIdSet; ///< Default: empty. A set of PortIds that cannot by dynamically allocated by AttachComponent().
TimeoutPeriod m_threadTimerServiceTickInterval; ///< Default: 2. The tick interval to use for the ManagedEndPointTimerService in ms.
#if (defined ACTIV_PLATFORM_WINDOWS)
uint32_t m_threadPriority; ///< Default: THREAD_PRIORITY_NORMAL.
#endif
ProcessorAffinity m_threadProcessorAffinity; ///< Default: do not adjust.
bool m_shouldAllocateThreadAffinity; ///< Default: false.
bool m_shouldUseEpollEventManager; ///< Default: true. Use epoll if available when in EventManager mode?
size_t m_maxMessagesPerEndPoint; ///< Default: 1000. Max messages to process from each managed endpoint before moving to the next (when managing more than one endpoint).
SourceEndPointInfoMap m_sourceEndPointInfoMap; ///< Default: empty. Map from source endpoint name -> SourceEndPointInfo.
size_t m_maxFailedTryGetMessages; ///< Default: 8. How many failed TryGetMessages() on an endpoint before doing a blocking call.
size_t m_maxMessagesWithoutTickCountReset; ///< Default: 100. Max number of messages to process without assuming tick count will have advanced.
IHeap::Settings m_monitorServiceHeapSettings; ///< Default: empty. Use the MonitorService heap by default.
bool m_shouldUseOnload; ///< Default: false. Posix only. Should threads use onload.
String m_onloadStackName; ///< Default: empty. Posix only. If onload is available this named onload stack will be used (8 char limit).
bool m_shouldSetOnloadReceiveChannel; ///< Default: false. Posix only. Set the onload receive channel that should be used based on this threads affinity.
PostMessageHelper::Settings m_postMessageHelperSettings;
size_t m_ringBufferEventInterval; ///< Default: 1ms. Interval to lazily set RingBuffer events.
uint32_t m_ringBufferEventByteThreshold; ///< Default: 64KB. Number of bytes written before event is set (if not set due to idleness).
uint32_t m_ringBufferMaxFlushFrequency; ///< Default: 128. The number of messages which must be received in a single message loop before throttling of the ring buffer's write pointer updates will no longer increase.
uint64_t m_loopTimeTraceTrigger; ///< Default: 0. Zero causes automatic behaviour.
TraceBuffer::Settings m_traceBufferSettings;
};
/**
* @brief Helper class to run an endpoint.
*
* The behavior of the Run() method and the thread started by a call to StartThread() is to not
* return until the endpoint has received die messages (from PostDiesToThreads()).
*
* However, if you wish to integrate the endpoint message loop with another event loop
* mechanism it may be necessary to poll the endpoint, or only block for a small timeout period.
* This can be accomplished with the RunHelper class:
*
* Application application;
* ManagedEndPoint::RunHelper applicationRunHelper(application);
*
* switch (applicationRunHelper(0, 10))
* {
* case STATUS_CODE_SUCCESS:
* // Message processed.
* break;
*
* case STATUS_CODE_TIMEOUT:
* // No messages on endpoint in the timeout period.
* break;
*
* case STATUS_CODE_EXIT:
* // Endpoint has received dies.
* break;
* }
*/
class RunHelper
{
public:
/**
* @brief Constructor.
*
* Sets up the calling thread to run the endpoint.
*
* @param managedEndPoint the endpoint to run.
*
* @throw StatusCodeException if too many threads are processing the endpoint already, out of memory.
*/
ACTIV_FRAMEWORK_API
RunHelper(ManagedEndPoint &managedEndPoint);
/**
* @brief Destructor.
*
* Cleans up some thread local state.
*/
ACTIV_FRAMEWORK_API
~RunHelper();
/**
* @brief Pump the endpoint message loop.
*
* @param maxMessagesToProcess 0 for no limit, else number of messages to process before returning.
* @param timeout how long to wait for messages on the endpoint, in ms, or ACTIV_WAIT_INFINITE.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_TIMEOUT no message on the endpoint
* @retval STATUS_CODE_EXIT endpoint received a die message whilst processing messages on the endpoint.
*/
ACTIV_FRAMEWORK_API
StatusCode operator()(const size_t maxMessagesToProcess, const TimeoutPeriod timeout);
//! Get the number of messages processed in the last operator() call; not a cumulative value.
size_t GetNumberOfMessagesProcessed();
/**
* @brief Reset cached tick count for the calling thread.
*
* Next call to GetTickCount() will call IntervalTimer::GetTickCount64() rather than returning the cached
* value.
*/
ACTIV_FRAMEWORK_API
void ResetTickCount();
/**
* @brief Get the approximate current tick count.
*
* Retrieving the tick count per message can be expensive, so this tick count is cached and not updated every message;
* hence the result is approximate.
*
* @return The approximate tick count.
*/
uint64_t GetTickCount() const;
private:
ManagedEndPoint & m_managedEndPoint; ///< Hook back to the endpoint.
size_t m_numberOfMessagesProcessed;
friend class ManagedEndPointImpl;
};
//! Scoped helper to add a task to run at the end of an iteration of the ManagedEndPoint processing loop.
class ScopedPostEndPointProcessingTask
{
public:
/**
* @brief Priority enumeration.
*
* Order of processing tasks is governed by this priority ordered from PRIORITY_NORMAL first to PRIORITY_BACKGROUND last.
*/
enum Priority
{
PRIORITY_NORMAL, ///< Normal priority.
PRIORITY_FLUSH, ///< Flush tasks.
PRIORITY_BACKGROUND ///< Background work.
};
/**
* @brief Interface for a task to run after processing the endpoint. The return value indicates whether the
* ManagedEndPoint can block (false) or should run busy (true) on the next message loop.
*/
typedef CxxYZ::function<bool (void)> Task;
typedef size_t TaskId;
static const TaskId INVALID_TASK_ID = Boost::integer_traits<TaskId>::const_max;
/**
* @brief Constructor.
*
* @param managedEndPoint the ManagedEndPoint to add the task to.
* @param task initial task to configure for post endpoint processing.
* @param priority
*/
ACTIV_FRAMEWORK_API
ScopedPostEndPointProcessingTask(ManagedEndPoint &managedEndPoint, const Task &task = Task(),
const Priority priority = PRIORITY_NORMAL);
//! Destructor.
ACTIV_FRAMEWORK_API
~ScopedPostEndPointProcessingTask();
/**
* @brief Set the post endpoint processing task.
*
* @param task a CxxYZ::function wrapping the task to run. Invocation of this function is wrapped in a
* try-catch, so it may throw. The task will be run at the end of each ManagedEndPoint processing loop.
* @param priority
*
* @throw StatusCodeException
* @throw std::exception
*/
ACTIV_FRAMEWORK_API
void Set(const Task &task, const Priority priority = PRIORITY_NORMAL);
//! Remove any post endpoint processing task.
ACTIV_FRAMEWORK_API
void Reset();
//! Is a task currently set?
ACTIV_BOOST_EXPLICIT_OPERATOR_BOOL()
//! Is a task not currently set?
ACTIV_FRAMEWORK_API
bool operator!() const;
private:
ManagedEndPoint & m_managedEndPoint;
Task m_task;
TaskId m_taskId;
};
//! Class to add to ManagedEndPoint ui menu.
class ScopedUiAddition
{
public:
//! Interface for a function to add custom menu options to the ManagedEndPoint ui menu.
typedef CxxYZ::function<void (UiMenu &)> Function;
/**
* @brief Constructor.
*
* @param managedEndPoint the ManagedEndPoint to customize the ui menu for.
* @param function function to add custom ui menu options.
* @param sectionName optional ui section name. If empty added to a 'MISCELLANEOUS' section.
*
* @throw std::exception
*/
ACTIV_FRAMEWORK_API
ScopedUiAddition(ManagedEndPoint &managedEndPoint, const Function &function, const String &sectionName = String());
//! Destructor.
ACTIV_FRAMEWORK_API
~ScopedUiAddition();
private:
ManagedEndPointImpl & m_managedEndPointImpl;
const String m_sectionName;
const uint64_t m_id;
};
//! Interface for a task to run after processing of a HeapMessage.
typedef CxxYZ::function<void (void)> PostProcessingTask;
/**
* @brief Constructor.
*
* This constructor creates an endpoint with the given name. No threads are launched.
*
* @param application the application that will create the endpoint.
* @param name the name of the endpoint.
* @param settings settings for the endpoint.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API
ManagedEndPoint(Application &application, const String &name, const Settings &settings = Settings());
/**
* @brief Destructor.
*
* The destructor stops the endpoint from receiving any more messages, and clears any queued messages.
*/
ACTIV_FRAMEWORK_API
virtual ~ManagedEndPoint();
/**
* @brief Run the endpoint from the context of the calling thread.
*
* This call will not return until the endpoint has received die messages from PostDiesToThreads() or an exception
* propagates to this function.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FULL a thread is already running.
*/
ACTIV_FRAMEWORK_API
StatusCode Run();
/**
* @brief Launch a thread to process this endpoint.
*
* The virtual method Process() is called from the new thread. The default behavior of
* Process() is to run the endpoint until dies are received (essentially Run() from the new thread).
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_FULL
*/
ACTIV_FRAMEWORK_API
StatusCode StartThread();
//! Post a shutdown message to the thread processing this endpoint.
ACTIV_FRAMEWORK_API
void PostDiesToThreads() const;
/**
* @brief Filter matching function on this endpoint into a function.
*
* This method is not thread safe. It must be called from the thread processing the endpoint.
*
* When child endpoints are enabled, this method does not handle new child endpoints being created for the source endpoint
* being matched during the call.
*
* The method returns when the timeout is reached or when the @a process function returns false.
*
* Re-throws any exception thrown by the process function.
*
* @param sourceEndPointId the source endpoint of messages to filter.
* @param destinationAddress the destination address of messages to filter.
* @param filter the filter function, return true if should process.
* @param process process function, returns false to stop filtering.
* @param timeoutPeriod how long to wait for matching messages, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_TIMEOUT
*
* @throw Exception
* @throw ...
*/
ACTIV_FRAMEWORK_API
StatusCode Filter(const EndPointId sourceEndPointId, const Address &destinationAddress,
const CxxYZ::function<bool (HeapMessage &heapMessage)> &filter,
const CxxYZ::function<bool (HeapMessage &heapMessage)> &process, const TimeoutPeriod timeoutPeriod);
/**
* @brief Wait for the thread to finish processing the endpoint and exit.
*
* @param timeout how long to wait, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_TIMEOUT
* @retval STATUS_CODE_IN_USE called from within a thread processing the endpoint
*/
ACTIV_FRAMEWORK_API
StatusCode WaitForThreadsToExit(const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get the application.
*
* @return A reference to the application object.
*/
ACTIV_FRAMEWORK_API
Application &GetApplication() const;
//! Get the endpoint name.
ACTIV_FRAMEWORK_API
String GetEndPointName() const;
//! Get the endpoint id.
EndPointId GetEndPointId() const;
/**
* @brief Clear the daily endpoint high statistics.
*
* @param shouldClearAllHighStatistics if true all high statistics are cleared, if false only daily statistics are cleared.
*/
ACTIV_FRAMEWORK_API
void ClearEndPointHighStatistics(const bool shouldClearAllHighStatistics = false);
/**
* @brief Get the underlying message notification handle, if available.
*
* @param handle reference to receive the handle.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_SUPPORTED the notification type for this ManagedEndPoint does not support an exportable handle.
*/
ACTIV_FRAMEWORK_API
StatusCode GetNotificationHandle(HANDLE &handle) const;
/**
* @brief Set the state of the endpoint(s) managed by this object.
*
* Setting the endpoint state to IEndPoint::STATE_IGNORING_MESSAGES implicitly clears the endpoint of any queued messages, and
* replies to any queued requests with STATUS_CODE_FAILURE.
*
* @param endPointState the state to set the endpoint(s) to.
*/
ACTIV_FRAMEWORK_API
void SetEndPointState(const IEndPoint::State endPointState);
/**
* @brief Set the maximum allowed message loop timeout.
*
* If the provided value is greater than the current timeout then the timeout will not be updated with the new value.
*
* @param maximumAllowedMessageLoopTimeout
*/
ACTIV_FRAMEWORK_API
void SetMaximumAllowedMessageLoopTimeout(const TimeoutPeriod maximumAllowedMessageLoopTimeout);
//! Is polling. Is the thread processing the endpoint running cpu busy.
bool IsPolling() const;
/**
* @brief Find a component on the endpoint by name.
*
* @param componentName name of the component to find.
* @param componentAddress a reference to an Address to receive component's address.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
*/
ACTIV_FRAMEWORK_API
StatusCode FindComponent(const String &componentName, Address &componentAddress) const;
/**
* @brief Get endpoint's event manager.
*
* If an event manager does not exist the endpoint will attempt to create one.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API
EventManager &GetEventManager();
/**
* @brief Get the approximate current tick count.
*
* Retrieving the tick count per message can be expensive, so this tick count is cached and not updated every message;
* hence the result is approximate.
*
* This function should only be called from the context of the thread processing this ManagedEndPoint.
*
* @return The approximate tick count.
*/
uint64_t GetTickCount() const;
/**
* @brief Get the timestamp from when the current message loop started.
*
* This is the cached IntervalTimer::GetNanosecondTimestamp() value taken at the beginning of the current message loop.
*/
uint64_t GetLoopTimestamp() const;
/**
* @brief Append a task to the list of tasks to run after processing of the current HeapMessage is complete.
*
* Must be called from the context of the thread processing this ManagedEndPoint, otherwise has no effect.
*
* @param postProcessingTask a CxxYZ::function wrapping the task to run. Invocation of this function is wrapped in a
* try-catch, so it may throw.
*/
ACTIV_FRAMEWORK_API
void AddPostProcessingTask(const PostProcessingTask &postProcessingTask);
/**
* @brief Get the ManagedEndPoint PostMessageHelper, this should only be used in the context of the thread processing
* the ManagedEndPoint.
*
* This PostMessageHelper is implicitly flushed when the calling thread has finished processing the current "batch" of
* messages.
*
* @return PostMessageHelper reference.
*/
inline PostMessageHelper &GetPostMessageHelper();
/**
* @brief Get the ManagedEndPoint MessageBuilder, this should only be used in the context of the thread processing
* the ManagedEndPoint.
*
* @return MessageBuilder reference.
*/
inline MessageBuilder &GetMessageBuilder();
//! Get reference to the trace buffer.
inline TraceBuffer &GetTraceBuffer();
//! Get the settings used to construct the ManagedEndPoint.
ACTIV_FRAMEWORK_API
const Settings &GetSettings() const;
/**
* @brief Get the ManagedEndPoint implementation.
*
* For use only within ActivFramework, as the implementation of ManagedEndPoint is private.
*
* @return ManagedEndPointImpl reference.
*/
ManagedEndPointImpl &GetImpl() const;
protected:
/**
* @brief Overridable endpoint processing function.
*
* This function is called from the thread launched by a StartThread() call, it is *not* called
* after using the Run() function.
*/
ACTIV_FRAMEWORK_API
virtual void Process();
/**
* @brief Callback when a thread begins processing the ManagedEndPoint.
*
* Default implementation does nothing.
*
* Components can be safely attached in this callback.
*/
ACTIV_FRAMEWORK_API
virtual void OnThreadStart();
/**
* @brief Ok to exit this thread?
*
* Once a thread has received an exit message, CanThreadExit() will subsequently be invoked after processing
* of any message by that thread to determine if the thread can actually exit. Default behavior is
* to return true.
*
* @retval true this thread can exit
* @retval false this thread cannot exit
*/
ACTIV_FRAMEWORK_API
virtual bool CanThreadExit();
private:
/**
* @brief Validate thread access.
*
* @retval true if no thread is processing the ManagedEndPoint or this is the callback thread.
* @retval false if there is a thread processing the ManagedEndPoint and it isn't this one.
*/
ACTIV_FRAMEWORK_API
bool ValidateThreadAccess() const;
TraceBuffer m_traceBuffer;
const TimeoutPeriod m_messageLoopTimeout; ///< Internal RunHelper message loop timeout.
const CxxYZ::unique_ptr<ManagedEndPointImpl> m_pImpl; ///< Implementation details.
const CxxYZ::unique_ptr<DefaultComponent> m_pDefaultComponent;
const EndPointId m_endPointId; ///< Cached endpoint id.
mutable uint64_t m_tickCount; ///< Cached tick count for frequent access.
uint64_t m_loopTimestamp; ///< The timestamp of the current message loop.
PostMessageHelper m_postMessageHelper;
MessageBuilder m_messageBuilder;
friend class Component;
friend class ManagedEndPointImpl;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline EndPointId ManagedEndPoint::GetEndPointId() const
{
return m_endPointId;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool ManagedEndPoint::IsPolling() const
{
return (0 == m_messageLoopTimeout);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint64_t ManagedEndPoint::GetTickCount() const
{
assert(ValidateThreadAccess());
if (ACTIV_UNLIKELY(0 == m_tickCount))
m_tickCount = IntervalTimer::GetTickCount64();
return m_tickCount;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint64_t ManagedEndPoint::GetLoopTimestamp() const
{
return m_loopTimestamp;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline PostMessageHelper &ManagedEndPoint::GetPostMessageHelper()
{
assert(ValidateThreadAccess());
return m_postMessageHelper;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageBuilder &ManagedEndPoint::GetMessageBuilder()
{
assert(ValidateThreadAccess());
return m_messageBuilder;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline TraceBuffer &ManagedEndPoint::GetTraceBuffer()
{
assert(ValidateThreadAccess());
return m_traceBuffer;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t ManagedEndPoint::RunHelper::GetNumberOfMessagesProcessed()
{
return m_numberOfMessagesProcessed;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint64_t ManagedEndPoint::RunHelper::GetTickCount() const
{
return m_managedEndPoint.GetTickCount();
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_MANAGED_END_POINT_H)