Remove Activ libs and includes

This commit is contained in:
John Colvin committed 2023-12-15 13:15:08 -05:00
1 parent 28ed30c944
commit 4b718994be
10967 files changed
-2306716

No files matched your search

@@ -1,27 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ActivFramework.h
*
* @brief Main header file for framework.
*/
#if (!defined ACTIV_FRAMEWORK_H)
#define ACTIV_FRAMEWORK_H
#if (!defined ACTIV_LITE_FRAMEWORK)
#include "ActivMiddleware/ActivFramework/Address.h"
#include "ActivMiddleware/ActivFramework/HeapMessageDeserializer.h"
#include "ActivMiddleware/ActivFramework/PostMessageHelper.h"
#include "ActivMiddleware/ActivFramework/Application.h"
#include "ActivMiddleware/ActivFramework/ThinApplication.h"
#include "ActivMiddleware/ActivFramework/Component.h"
#include "ActivMiddleware/ActivFramework/Service.h"
#include "ActivMiddleware/ActivFramework/ChildService.h"
#include "ActivMiddleware/ActivFramework/UiComponent.h"
#include "ActivMiddleware/ActivFramework/UiMenu.h"
#include "ActivMiddleware/ActivFramework/UiIo.h"
#endif // (!defined ACTIV_LITE_FRAMEWORK)
#endif // (!defined ACTIV_FRAMEWORK_H)
@@ -1,341 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/Address.h
*
* @brief Address header file.
*/
#if (!defined ACTIV_FRAMEWORK_ADDRESS_H)
#define ACTIV_FRAMEWORK_ADDRESS_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include "ActivMiddleware/ActivBase/MessageValidator.h"
#include "ActivMiddleware/ActivBase/ActivBase.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#include ACTIV_BOOST_INCLUDE(functional/hash.hpp)
//! Activ namespace.
namespace Activ
{
/**
* @brief Address.
*/
class Address
{
public:
/**
* @brief Default constructor.
*
* The endpoint id is set to INVALID_ENDPOINT_ID and the port id to INVALID_PORT_ID.
*/
Address();
/**
* @brief Constructor.
*
* @param endPointId
* @param portId
*/
Address(const EndPointId endPointId, const PortId portId);
/**
* @brief Serialize the address.
*
* @param messageBuilder
*
* @return STATUS_CODE_SUCCESS or an error status code.
*/
StatusCode Serialize(MessageBuilder &messageBuilder) const;
/**
* @brief Deserialize the address.
*
* @param messageValidator
*
* @return STATUS_CODE_SUCCESS or an error status code.
*/
StatusCode Deserialize(MessageValidator &messageValidator);
/**
* @brief Get the serialized length of an Address object.
*
* @return The serialized length in bytes.
*/
static size_t GetSerializedLength();
/**
* @brief Clear the address.
*
* The endpoint id is set to INVALID_ENDPOINT_ID and the port id to INVALID_PORT_ID.
*/
void Clear();
/**
* @brief Convert the address to a string.
*
* @return String representation of the address, in the form "endPointId:portId".
*/
ACTIV_FRAMEWORK_API const String ToString() const;
/**
* @brief Initialize the address from a string.
*
* @param str a string in the format returned by ToString().
*
* @return True if the conversion was successful.
*/
ACTIV_FRAMEWORK_API bool FromString(const String &str);
/**
* @brief Is this a valid address?
*
* A valid address is one where endPointId is not INVALID_ENDPOINT_ID and portId is not INVALID_PORT_ID.
*
* @return Boolean.
*/
bool IsValid() const;
/**
* @brief Get the endpoint id.
*
* @return the endpoint id.
*/
EndPointId GetEndPointId() const;
/**
* @brief Set the endpoint id.
*
* @param endPointId the endpoint id.
*/
void SetEndPointId(const EndPointId endPointId);
/**
* @brief Get the port id.
*
* @return the port id.
*/
PortId GetPortId() const;
/**
* @brief Set the port id.
*
* @param portId the port id.
*/
void SetPortId(const PortId portId);
/**
* @brief Set the endpoint and port id.
*
* @param endPointId the endpoint id.
* @param portId the port id.
*/
void Set(const EndPointId endPointId, const PortId portId);
/**
* @brief '==' operator.
*
* @param rhs Address to compare.
*
* @return Boolean.
*/
bool operator==(const Address &rhs) const;
/**
* @brief '!=' operator.
*
* @param rhs Address to compare.
*
* @return Boolean.
*/
bool operator!=(const Address &rhs) const;
/**
* @brief '<' operator.
*
* @param rhs Address to compare.
*
* @return Boolean.
*/
bool operator<(const Address &rhs) const;
private:
EndPointId m_endPointId;
PortId m_portId;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline Address::Address()
{
Clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Address::Address(const EndPointId endPointId, const PortId portId)
{
SetEndPointId(endPointId);
SetPortId(portId);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Address::Serialize(MessageBuilder &messageBuilder) const
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageBuilder.Append<MessageBuilder::ENDIAN_LITTLE>(m_endPointId));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageBuilder.Append<MessageBuilder::ENDIAN_LITTLE>(m_portId));
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Address::Deserialize(MessageValidator &messageValidator)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, (messageValidator.ValidateBinaryIntegral<sizeof(m_endPointId),
MessageValidator::ENDIAN_LITTLE>(m_endPointId)));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, (messageValidator.ValidateBinaryIntegral<sizeof(m_portId),
MessageValidator::ENDIAN_LITTLE>(m_portId)));
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Address::GetSerializedLength()
{
return ACTIV_FIELD_SIZE(Address, m_endPointId) + ACTIV_FIELD_SIZE(Address, m_portId);
}
// ---------------------------------------------------------------------------------------------------------------------------------
ACTIV_FORCE_INLINE void Address::Clear()
{
// HACK. Small performance win over two member sets. Various asserts to be safe(r).
ACTIV_BOOST_STATIC_ASSERT(sizeof(Address) == (sizeof(EndPointId) + sizeof(PortId)));
ACTIV_BOOST_STATIC_ASSERT(INVALID_PORT_ID == INVALID_ENDPOINT_ID);
ACTIV_BOOST_STATIC_ASSERT(INVALID_PORT_ID == uint16_t(0xffff));
::memset(this, 0xff, sizeof(Address));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline EndPointId Address::GetEndPointId() const
{
return m_endPointId;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Address::SetEndPointId(EndPointId endPointId)
{
m_endPointId = endPointId;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline PortId Address::GetPortId() const
{
return m_portId;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Address::SetPortId(PortId portId)
{
m_portId = portId;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Address::Set(const EndPointId endPointId, const PortId portId)
{
m_endPointId = endPointId;
m_portId = portId;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Address::IsValid() const
{
return (INVALID_ENDPOINT_ID != m_endPointId) && (INVALID_PORT_ID != m_portId);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Address::operator==(const Address &rhs) const
{
return (m_endPointId == rhs.m_endPointId) && (m_portId == rhs.m_portId);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Address::operator!=(const Address &rhs) const
{
return !(*this == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Address::operator<(const Address &rhs) const
{
if (m_endPointId < rhs.m_endPointId)
return true;
if (m_endPointId > rhs.m_endPointId)
return false;
return m_portId < rhs.m_portId;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline std::size_t hash_value(const Address &address)
{
size_t seed = 0;
Boost::hash_combine(seed, address.GetEndPointId());
Boost::hash_combine(seed, address.GetPortId());
return seed;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Global operator<< to dump an Address to an ostream.
*
* @param os
* @param address
*
* @return The ostream @a os.
*/
inline std::ostream &operator<<(std::ostream &os, const Activ::Address &address)
{
os << address.ToString();
return os;
}
} // namespace Activ
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
namespace ACTIV_CXXYZ_HASH_NAMESPACE
{
template<>
struct hash<Activ::Address>
{
size_t operator()(const Activ::Address &address) const
{
return hash_value(address);
}
};
} // namespace ACTIV_CXXYZ_HASH_NAMESPACE
#endif // (!defined ACTIV_FRAMEWORK_ADDRESS_H)
@@ -1,297 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/Application.h
*
* @brief Header file for base application class.
*/
#if (!defined ACTIV_FRAMEWORK_APPLICATION_H)
#define ACTIV_FRAMEWORK_APPLICATION_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/Component.h"
#include "ActivMiddleware/ActivFramework/DirectoryWatchApi.h"
#include "ActivMiddleware/ActivFramework/TimerServiceApi.h"
#include "ActivMiddleware/ActivFramework/LoggerServiceApi.h"
#include "ActivMiddleware/ActivFramework/ManagedEndPoint.h"
#include "ActivMiddleware/ActivFramework/RouterServiceApi.h"
#include "ActivMiddleware/ActivFramework/PubSubServiceApi.h"
#include "ActivMiddleware/ActivFramework/ServiceApi.h"
#include "ActivMiddleware/ActivFramework/ISystem.h"
#include "ActivMiddleware/ActivBase/CtrlHandler.h"
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
#if (defined ACTIV_ENABLE_DPDK)
#include "ActivMiddleware/ActivFramework/KernelBypass/DpdkSettings.h"
#endif
//! Activ namespace.
namespace Activ
{
class CurrentDateTime;
class SystemImpl;
class PostMessageHelper;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Proxy class for ISystem interface.
*/
class SystemProxy : public ISystem
{
public:
/**
* @brief Destructor.
*/
ACTIV_FRAMEWORK_API ~SystemProxy();
// ISystem.
ACTIV_FRAMEWORK_API virtual IEndPoint *CreatePrivateEndPoint(const IEndPoint::Settings &settings) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual IAddressableEndPoint *CreateEndPoint(const IAddressableEndPoint::Settings &settings) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual IAddressableEndPoint *OpenEndPoint(const String &name,
Timeout &timeout = Timeout::GetInfinite()) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual IAddressableEndPoint *OpenEndPoint(EndPointId endPointId,
Timeout &timeout = Timeout::GetInfinite()) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual IAddressableEndPoint *OpenSystemEndPoint() ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual IHeap *CreateHeap(const String &name, const IHeap::Settings &settings) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual IHeap *OpenHeap(const String &name, Timeout &timeout = Timeout::GetInfinite()) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual IHeap *OpenHeap(const HeapId heapId, Timeout &timeout = Timeout::GetInfinite()) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual IProcess *OpenProcess(const String &name, Timeout &timeout = Timeout::GetInfinite()) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual IProcess *OpenProcess(const ProcessId processId, Timeout &timeout = Timeout::GetInfinite()) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual const String &GetSystemName() const ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual IHeap *GetSystemHeap() const ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual IProcess *GetProcess() const ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual SystemInfo GetSystemInfo() const ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual void EnumerateObjects(IProcessEnumerator &enumerator) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual void EnumerateObjects(IEndPointEnumerator &enumerator) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual void EnumerateObjects(IHeapEnumerator &enumerator) ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual uint16_t GetNextAffinityProcessorId() const ACTIV_OVERRIDE;
private:
/**
* @brief Create a system.
*
* @param settings settings.
* @param processName the name of this process, if an empty string is provided uses the system name.
* @param heapSettings describing the properties of the system heap to create.
* @param systemVersion arbitrary version string for the system.
*
* @throw Exception.
*/
SystemProxy(const ISystem::Settings &settings, const String &processName, const IHeap::Settings &heapSettings, const String &systemVersion);
/**
* @brief Open a system.
*
* @param settings settings.
* @param processName the name of this process, empty string gives a process name based on the os process id.
* @param timeout how long to wait for the system to exist, in ms.
*
* @throw Exception.
*/
SystemProxy(const ISystem::Settings &settings, const String &processName, Timeout &timeout = Timeout::GetInfinite());
const Boost::scoped_ptr<SystemImpl> m_pSystem; ///< The underlying system
friend class Application;
friend class ManagedEndPointImpl;
friend class PostMessageHelper;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Base application class.
*
* The base application class provides the ISystem interface to create and open heaps, endpoints.
* It also provides always on router and timer functionality and creates a default endpoint which is given the
* name of the process.
*
* Do not use the Application class directly. AgentApplication is provided for processes which are to
* create a shared memory system or standalone private memory application,
* and ThinApplication for those which link into an existing shared memory system.
*/
class Application : public SystemProxy, public ManagedEndPoint, public Component
{
public:
using Component::GetApplication;
/**
* @brief Settings.
*/
class Settings : public ISystem::Settings
{
public:
/**
* @brief List of exception handler types.
*
* Exception handler on available on Windows platform.
*/
enum ExceptionHandlerType
{
EXCEPTION_HANDLER_TYPE_NONE, ///< no exception handler
EXCEPTION_HANDLER_TYPE_NORMAL, ///< don't dump entire address space
EXCEPTION_HANDLER_TYPE_FULL_MEMORY ///< do dump address space
};
/**
* @brief 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);
String m_processName; ///< If empty a name will be assigned automatically.
bool m_enableCtrlHandler; ///< Default: true.
bool m_shouldMemoryLock; ///< Default: false. Posix only. Should the application be locked in memory.
ExceptionHandlerType m_exceptionHandlerType; ///< Default: EXCEPTION_HANDLER_TYPE_NONE.
ManagedEndPoint::Settings m_managedEndPointSettings; ///< Settings for default application endpoint.
IHeap::Settings m_loggerServiceHeapSettings;///< Settings for thread-specific logger service heap.
#if (defined ACTIV_ENABLE_DPDK)
KernelBypass::DpdkSettings m_dpdkSettings;
#endif
};
/**
* @brief Shutdown reasons.
*/
enum ShutdownReason
{
SHUTDOWN_REASON_API, ///< Shutdown() called on Application object.
SHUTDOWN_REASON_UI, ///< System shutdown initiated from UI service.
SHUTDOWN_REASON_UI_RESTART, ///< System restart initiated from UI service.
SHUTDOWN_REASON_LOGOFF, ///< System shutdown initiated due to OS shutting down / user logging off.
SHUTDOWN_REASON_TERMINATE_PROCESS, ///< SIGTERM, CTRL_CLOSE_EVENT received.
SHUTDOWN_REASON_NOT_LICENSED ///< System is not licensed.
};
/**
* @brief Destructor.
*/
ACTIV_FRAMEWORK_API virtual ~Application() ACTIV_OVERRIDE;
/**
* @brief Set the state of the process.
*
* @param state new state.
*/
ACTIV_FRAMEWORK_API void SetState(const IProcess::State state);
/**
* @brief Initiate a shutdown.
*/
ACTIV_FRAMEWORK_API void Shutdown();
/**
* @brief Get the monitor service heap.
*
* The monitor service heap should be used for publishing monitoring messages.
*
* @return Heap used by the monitor service.
*/
ACTIV_FRAMEWORK_API IHeap *GetMonitorServiceHeap() const;
/**
* @brief Get the monitor service heap.
*
* The monitor service heap should be used for publishing monitoring messages.
*
* @param component
*
* @return Heap used by the monitor service for this component.
*/
ACTIV_FRAMEWORK_API IHeap *GetMonitorServiceHeap(const Component &component) const;
/**
* @brief Get the name of the default ui service.
*
* This name should be used when adding components to the ui service. See UiComponent.h.
*
* @return The name of the default ui service.
*/
ACTIV_FRAMEWORK_API static const String &GetUiServiceName();
class Private;
/**
* @brief Get private implementation.
*
* @return Const reference to private implementation object.
*/
const Private &GetPrivate() const;
protected:
ACTIV_FRAMEWORK_API virtual StatusCode OnMessage(HeapMessage &message) ACTIV_OVERRIDE;
/**
* @brief Application has received a ctrl event.
*
* @param eventType the type of ctrl event.
*/
ACTIV_FRAMEWORK_API virtual void OnCtrlEvent(const CtrlHandler::EventType eventType);
/**
* @brief Shutdown has been invoked.
*
* This callback is invoked for all processes when a system is shutdown (i.e. the Agent has called AgentApplication::Shutdown()),
* or for a single application if it itself calls ThinApplication::Shutdown().
*
* When overriding, call the base class method at the end of the override.
*
* @param shutdownReason the reason for the shutdown.
*/
ACTIV_FRAMEWORK_API virtual void OnShutdown(const ShutdownReason shutdownReason);
private:
/**
* @brief Create a system.
*
* @param settings settings for the application.
* @param heapSettings info describing the properties of the system heap to create.
* @param systemVersion arbitrary version string for the system.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API Application(const Settings &settings, const IHeap::Settings &heapSettings,
const String &systemVersion);
/**
* @brief Open a system.
*
* @param settings settings for the application.
* @param heapSettings info describing the properties of the application's heap. If empty, use the system heap.
* @param timeout how long to wait for the system to exist, in ms.
*
* @throw Exception.
*/
Application(const Settings &settings, const IHeap::Settings &heapSettings, Timeout &timeout = Timeout::GetInfinite());
class SharedCurrentDateTime;
Private * m_pPrivate; ///< Hidden implementation details.
CxxYZ::unique_ptr<SharedCurrentDateTime> m_pSharedCurrentDateTime; ///< Current time in shared memory.
friend class AgentApplication;
friend class ThinApplication;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline const Application::Private &Application::GetPrivate() const
{
return *m_pPrivate;
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_APPLICATION_H)
@@ -1,40 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/BasicTypes.h
*
* @brief Basic types for ActivFramework.
*/
#if (!defined ACTIV_FRAMEWORK_BASIC_TYPES_H)
#define ACTIV_FRAMEWORK_BASIC_TYPES_H
#include "ActivMiddleware/ActivMiddleware.h"
#include <set>
//! Activ namespace.
namespace Activ
{
typedef uint16_t MessageType; ///< Message type.
typedef uint64_t MessageId; ///< MessageId has to be at least the size of a pointer as in private heaps it is one.
typedef byte_t BucketId; ///< Type of bucket ids.
typedef uint16_t HeapId; ///< Type of heap ids.
typedef uint16_t PortId; ///< Type of port ids.
typedef uint16_t EndPointId; ///< Type of endpoint ids.
typedef uint16_t ProcessId; ///< Type of process ids.
typedef std::set<EndPointId> EndPointIdSet;
const MessageType INVALID_MESSAGE_TYPE = ~0; ///< Invalid message type.
const BucketId INVALID_BUCKET_ID = ~0; ///< Invalid bucket id.
const HeapId INVALID_HEAP_ID = ~0; ///< Invalid heap id.
const PortId INVALID_PORT_ID = ~0; ///< Invalid port id.
const PortId DEFAULT_PORT_ID = 1; ///< ManagedEndPoint default component. Use 1 to avoid clashing with "Manager" or Application components, which use 0.
const PortId APPLICATION_PORT_ID = 0; ///< Application's port id.
const EndPointId INVALID_ENDPOINT_ID = ~0; ///< Invalid endpoint id.
const ProcessId INVALID_PROCESS_ID = ~0; ///< Invalid process id.
const TimeoutPeriod COMPONENT_DEFAULT_TIMEOUT = 30000; ///< Default component timeout.
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_BASIC_TYPES_H)
@@ -1,57 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ChildService.h
*
* @brief Header file for child service class.
*/
#if (!defined ACTIV_FRAMEWORK_CHILD_SERVICE_H)
#define ACTIV_FRAMEWORK_CHILD_SERVICE_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/Service.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Child service class
*
* A child service is attached to another service. The child service is given the same service id as the parent.
*/
template <typename T>
class ChildService : public Service
{
public:
/**
* @brief Constructor.
*
* Attaches the child service to a managed endpoint at the next available slot with the service of the parent service.
*
* @param parentService reference to the parent service.
* @param managedEndPoint reference to a ManagedEndPoint object to which this component is to be attached.
* @param pHeap heap to use for messaging, or 0 for the parent service heap.
* @param name name of the Component, local to the endpoint.
*
* @throw Exception.
*/
ChildService(T &parentService, ManagedEndPoint &managedEndPoint, IHeap * const pHeap = 0,
const String &name = Component::anonymousName);
T &m_parentService; ///< Reference back to the parent service.
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T>
ChildService<T>::ChildService(T &parentService, ManagedEndPoint &managedEndPoint, IHeap * const pHeap,
const String &name) :
Service(parentService, managedEndPoint, pHeap, name),
m_parentService(parentService)
{
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_CHILD_SERVICE_H)
File diff suppressed because it is too large. Load diff
@@ -1,104 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ComponentWrapper.h
*
* @brief Header file for component wrapping class.
*/
#if (!defined ACTIV_FRAMEWORK_COMPONENT_WRAPPER_H)
#define ACTIV_FRAMEWORK_COMPONENT_WRAPPER_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/Component.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#if (defined ACTIV_BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#include ACTIV_BOOST_INCLUDE(preprocessor/arithmetic/inc.hpp)
#include ACTIV_BOOST_INCLUDE(preprocessor/punctuation/comma_if.hpp)
#include ACTIV_BOOST_INCLUDE(preprocessor/repetition/repeat_from_to.hpp)
#endif
//! Activ namespace.
namespace Activ
{
/**
* @brief Component wrapper class.
*
* This class can be used to "automatically" Enable()/Disable() a Component. Instead of:
*
* MyUdpTransmitter myUdpTransmitter(p1, p2, p3);
* Component::Enabler myUdpTransmitterEnabler(myUdpTransmitter);
*
* You can:
*
* ComponentWrapper<MyUdpTransmitter> myUdpTransmitter(CxxYZ::ref(p1), CxxYZ::cref(p2), CxxYZ::ref(p3));
*
* In C++11 or later only code, perfect forwarding is available:
*
* ComponentWrapper<MyUdpTransmitter> myUdpTransmitter(p1, p2, p3);
*
* Otherwise, all non-scalar parameters must be passed as reference wrappers (e.g. with CxxYZ::ref/cref). This is not
* perfect, as it could be valid to pass by value but isn't for the vast majority of use cases (and equally the intention
* might be to pass an integral reference that would not be flagged by these static asserts).
*/
template<typename COMPONENT>
class ComponentWrapper : public COMPONENT
{
public:
#if (defined ACTIV_BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#define ACTIV_COMPONENT_WRAPPER_TEMPLATE_PARAM(z, n, data) ACTIV_BOOST_PP_COMMA_IF(n) typename T##n
#if (defined ACTIV_BOOST_NO_CXX11_RVALUE_REFERENCES)
#define ACTIV_COMPONENT_WRAPPER_CTOR_PARAM(z, n, data) ACTIV_BOOST_PP_COMMA_IF(n) T##n arg##n
#define ACTIV_COMPONENT_WRAPPER_CTOR_PARAM_PASS(z, n, data) ACTIV_BOOST_PP_COMMA_IF(n) arg##n
// NB the block scoping here is due to ACTIV_BOOST_STATIC_ASSERT using the current line number for uniqueness, which
// breaks inside a PP loop.
#define ACTIV_COMPONENT_WRAPPER_CTOR_IS_REF(z, n, data) { ACTIV_BOOST_STATIC_ASSERT(Boost::is_scalar<T##n>::value || \
CxxYZ::is_reference_wrapper<T##n>::value); }
#else
#define ACTIV_COMPONENT_WRAPPER_CTOR_PARAM(z, n, data) ACTIV_BOOST_PP_COMMA_IF(n) T##n &&arg##n
#define ACTIV_COMPONENT_WRAPPER_CTOR_PARAM_PASS(z, n, data) ACTIV_BOOST_PP_COMMA_IF(n) std::forward<T##n>(arg##n)
#define ACTIV_COMPONENT_WRAPPER_CTOR_IS_REF(z, n, data)
#endif
#define ACTIV_COMPONENT_WRAPPER_DECLARE_CTOR(z, n, data) \
template<ACTIV_BOOST_PP_REPEAT_FROM_TO(0, ACTIV_BOOST_PP_INC(n), ACTIV_COMPONENT_WRAPPER_TEMPLATE_PARAM, )> \
ComponentWrapper(ACTIV_BOOST_PP_REPEAT_FROM_TO(0, ACTIV_BOOST_PP_INC(n), ACTIV_COMPONENT_WRAPPER_CTOR_PARAM, )) : \
COMPONENT(ACTIV_BOOST_PP_REPEAT_FROM_TO(0, ACTIV_BOOST_PP_INC(n), ACTIV_COMPONENT_WRAPPER_CTOR_PARAM_PASS, )) \
{ \
ACTIV_BOOST_PP_REPEAT_FROM_TO(0, ACTIV_BOOST_PP_INC(n), ACTIV_COMPONENT_WRAPPER_CTOR_IS_REF, ) \
this->Enable(); \
}
ACTIV_BOOST_PP_REPEAT_FROM_TO(0, 10, ACTIV_COMPONENT_WRAPPER_DECLARE_CTOR, )
#else
#if (defined ACTIV_BOOST_NO_CXX11_RVALUE_REFERENCES)
#error Variadic template support but no rvalue ref support is not supported
#endif
template<typename... Ts>
ComponentWrapper(Ts &&...args) :
COMPONENT(std::forward<Ts>(args)...)
{
this->Enable();
}
#endif
~ComponentWrapper()
{
this->Disable();
}
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_COMPONENT_WRAPPER_H)
@@ -1,12 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/DatabaseUiOptions.h
*
* @brief Forwarding header for DatabaseUiOptions.h.
*/
#if (!defined ACTIV_FRAMEWORK_DATABASE_UI_OPTIONS_H)
#define ACTIV_FRAMEWORK_DATABASE_UI_OPTIONS_H
#include "ActivMiddleware/ActivDatabase/DatabaseUiOptions.h"
#endif // (!defined ACTIV_FRAMEWORK_DATABASE_UI_OPTIONS_H)
@@ -1,104 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/DirectoryWatchApi.h
*
* @brief Header file for the directory watch api.
*/
#if (!defined ACTIV_FRAMEWORK_DIRECTORY_WATCH_API_H)
#define ACTIV_FRAMEWORK_DIRECTORY_WATCH_API_H
#include "ActivMiddleware/ActivFramework/External.h"
#include <vector>
//! Activ namespace.
namespace Activ
{
class Component;
class HeapMessage;
class ScopedAddress;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Api to the agent's directory watching service.
*/
class DirectoryWatchApi
{
public:
/**
* @brief Message type received in OnMessage() by the component adding a directory watch when a change happens.
*/
static const MessageType MESSAGE_TYPE = ROUTER_MESSAGE_USER_NOTIFY_DIRECTORY_WATCH_EVENTS;
typedef uint32_t WatchType;
static const WatchType WATCH_TYPE_RECURSIVE = 0x00000001; ///< watch sub-directories?
static const WatchType WATCH_TYPE_ADDS_DELETES = 0x00000002;///< watch for file & directory additions / deletions
static const WatchType WATCH_TYPE_ATTRIBUTES = 0x00000004; ///< watch for changes in attributes (size, access times etc.) of files & directories
/**
* @brief List of event types that can be received.
*/
enum EventType
{
EVENT_TYPE_ADDED, ///< file or directory has been added
EVENT_TYPE_DELETED, ///< file or directory has been deleted
EVENT_TYPE_MODIFIED ///< some attribute of the file or directory has changed
};
/**
* @brief File/directory change event.
*/
class Event
{
public:
String m_path; ///< path of file or directory that has changed
EventType m_eventType; ///< type of event that has happened
};
typedef std::vector<Event> EventList; ///< list of events
/**
* @brief Add a directory watch.
*
* Change notifications will be received in the OnMessage() callback of @a component, with message type
* DirectoryWatchApi::MESSAGE_TYPE. Call DirectoryWatchApi::Deserialize() to get a list of Event objects.
*
* @param component the component wanting to create the watch.
* @param directoryPath path of a directory to watch.
* @param watchType type of watch to start.
* @param watchAddress reference to a ScopedAddress object to receive the address of the new watch.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_TIMEOUT
* @retval STATUS_CODE_NOT_A_DIRECTORY path provided isn't a directory or doesn't exist
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode AddWatch(const Component &component, const String &directoryPath,
const WatchType watchType, ScopedAddress &watchAddress);
/**
* @brief Deserialize a directory watch message.
*
* @param heapMessage message containing the serialized events.
* @param eventList to receive the deserialized events.
*
* @return STATUS_CODE_SUCCESS or an error status code.
*/
ACTIV_FRAMEWORK_API static StatusCode Deserialize(const HeapMessage &heapMessage, EventList &eventList);
/**
* @brief Convert an event type to a string.
*
* @param eventType the EventType to convert.
*
* @return String representation of @a eventType.
*/
ACTIV_FRAMEWORK_API static String EventTypeToString(const EventType eventType);
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_DIRECTORY_WATCH_API_H)
@@ -1,89 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/External.h
*
* @brief Import rules for ActivFramework exports.
*/
#if (!defined ACTIV_FRAMEWORK_EXTERNAL_H)
#define ACTIV_FRAMEWORK_EXTERNAL_H
#if (!defined ACTIV_FRAMEWORK_API)
# if (!defined ACTIV_STATIC)
# define ACTIV_FRAMEWORK_API ACTIV_IMPORT_DLL
# else
# define ACTIV_FRAMEWORK_API ACTIV_IMPORT_LIB
# endif // (!defined ACTIV_STATIC)
#endif // (!defined ACTIV_FRAMEWORK_API)
#include "ActivMiddleware/ActivMiddleware.h"
#include "ActivMiddleware/ActivFramework/BasicTypes.h"
#include "ActivMiddleware/ActivFramework/MessageTypes.h"
// Enable ef_vi for x86-64, Linux, c++11
#if (defined ACTIV_PROCESSOR_X86_64) && (defined ACTIV_PLATFORM_LINUX) && (ACTIV_CPLUSPLUS >= ACTIV_CPLUSPLUS_11)
# define ACTIV_ENABLE_EFVI
#endif
// Enable DPDK for x86-64, Linux/Windows, c++11
#if (defined ACTIV_PROCESSOR_X86_64) && (ACTIV_CPLUSPLUS >= ACTIV_CPLUSPLUS_11)
# if ((defined ACTIV_PLATFORM_LINUX) || (defined ACTIV_PLATFORM_WINDOWS))
# define ACTIV_ENABLE_DPDK
#endif
#endif
// Enable onload for x86-64, Linux
#if (defined ACTIV_PROCESSOR_X86_64) && (defined ACTIV_PLATFORM_LINUX)
# define ACTIV_ENABLE_ONLOAD
#endif
// Enable exanic for Windows
#if (defined ACTIV_PLATFORM_WINDOWS)
# define ACTIV_ENABLE_EXANIC
#endif
//! Activ namespace.
namespace Activ
{
//! List of agent scopes.
#define ACTIV_AGENT_SCOPE_LIST(d) \
d(AGENT_SCOPE_LOCAL, "Local") \
d(AGENT_SCOPE_GLOBAL, "Global") \
d(AGENT_SCOPE_REMOTE, "Remote")
/**
* @brief Agent scope type.
*
* AGENT_SCOPE_LOCAL within the agent space
* AGENT_SCOPE_GLOBAL local & remote
* AGENT_SCOPE_REMOTE outside the agent space
*/
typedef byte_t AgentScope;
enum
{
ACTIV_AGENT_SCOPE_LIST(ACTIV_DECLARE_HIDDEN_ELEMENT_1)
NUM_AGENT_SCOPES
};
#define ACTIV_DECLARE_AGENT_SCOPE(a, b) ACTIV_DECLARE_CONSTANT_ELEMENT_1(AgentScope, a, b)
ACTIV_AGENT_SCOPE_LIST(ACTIV_DECLARE_AGENT_SCOPE)
#undef ACTIV_DECLARE_AGENT_SCOPE
//! Convert an AgentScope to a string.
ACTIV_FRAMEWORK_API const String AgentScopeToString(const AgentScope agentScope);
/**
* @brief Convert a string to an AgentScope.
*
* @param str
*
* @return The AgentScope.
*
* @throw std::exception if the conversion wasn't possible.
*/
ACTIV_FRAMEWORK_API AgentScope StringToAgentScope(const String &str);
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_EXTERNAL_H)
@@ -1,86 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/FrameworkException.h
*
* @brief Header file for ActivFramework exception class.
*/
#if (!defined ACTIV_FRAMEWORK_FRAMEWORK_EXCEPTION_H)
#define ACTIV_FRAMEWORK_FRAMEWORK_EXCEPTION_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/Exception.h"
/**
* @brief The list of possible errors and their strings.
*
* Note this list is converted to an enum using the ACTIV_DECLARE_ELEMENT_1 macro in ActivMiddleware.h,
* and the strings are unpicked using ACTIV_DECLARE_ELEMENT_2.
*/
#define ACTIV_FRAMEWORK_EXCEPTION_LIST(d) \
d(ERROR_FAILED_TO_ALLOC_MESSAGE_ARRAY, "failed to allocate message array") \
d(ERROR_FAILED_TO_ALLOC_SYSTEM, "failed to allocate system") \
d(ERROR_FAILED_TO_ALLOC_PROCESS, "failed to allocate process") \
d(ERROR_FAILED_TO_ALLOC_PROCESS_TABLE, "failed to allocate process table") \
d(ERROR_PROCESS_DOES_NOT_EXIST, "process does not exist") \
d(ERROR_FAILED_TO_ALLOC_ENDPOINT, "failed to allocate endpoint") \
d(ERROR_FAILED_TO_ALLOC_ENDPOINT_TABLE, "failed to allocate endpoint table") \
d(ERROR_ENDPOINT_DOES_NOT_EXIST, "endpoint does not exist") \
d(ERROR_FAILED_TO_ALLOC_HEAP, "failed to allocate heap") \
d(ERROR_FAILED_TO_ALLOC_HEAP_TABLE, "failed to allocate heap table") \
d(ERROR_HEAP_DOES_NOT_EXIST, "heap does not exist") \
d(ERROR_INVALID_NUMBER_OF_BUCKETS, "invalid number of buckets") \
d(ERROR_INVALID_MESSAGE_SIZE, "invalid message size (probably 0)") \
d(ERROR_INVALID_HEAP_ID, "invalid heap id") \
d(ERROR_INVALID_ENDPOINT_ID, "invalid endpoint id") \
d(ERROR_INVALID_PROCESS_ID, "invalid process id") \
d(ERROR_PORT_ID_IN_USE, "port id in use") \
d(ERROR_INVALID_PROCESS_STATE, "invalid process state") \
d(ERROR_UNKNOWN_SYSTEM_LOG_MODE, "unknown system log mode") \
d(ERROR_INVALID_MEMORY_MODEL, "invalid memory model") \
d(ERROR_COMPONENT_LIST_FULL, "component list full") \
d(ERROR_ENDPOINT_NAME_ALREADY_EXISTS, "endpoint name already exists") \
d(ERROR_ENDPOINT_NAME_TOO_LONG, "endpoint name too long") \
d(ERROR_HEAP_NAME_ALREADY_EXISTS, "heap name already exists") \
d(ERROR_HEAP_NAME_TOO_LONG, "heap name too long")
//! Activ namespace.
namespace Activ
{
/**
* @brief ActivFramework exception class.
*
* An exception of class FrameworkException is thrown only by classes inside ActivFramework.
*/
class FrameworkException : public Exception
{
public:
/**
* @brief Enumeration of all FrameworkException errors.
*/
enum
{
ACTIV_FRAMEWORK_EXCEPTION_LIST(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
NUM_ERRORS
};
/**
* @brief Constructor.
*
* @param file the file which raised the exception
* @param function the function which raised the exception
* @param line the line number which raised the exception
* @param errorCode the exception specific error code
* @param message the exception message.
*/
ACTIV_FRAMEWORK_API
FrameworkException(const char *file, const char *function, const uint_fast32_t line, const uint_fast32_t errorCode,
const String &message = "");
ACTIV_FRAMEWORK_API
virtual String ToString() const ACTIV_OVERRIDE;
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_FRAMEWORK_EXCEPTION_H)
File diff suppressed because it is too large. Load diff
@@ -1,172 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/HeapMessageBuilder.h
*
* @brief Header file for heap message / message builder class.
*/
#if (!defined ACTIV_FRAMEWORK_HEAP_MESSAGE_BUILDER_H)
#define ACTIV_FRAMEWORK_HEAP_MESSAGE_BUILDER_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include "ActivMiddleware/ActivFramework/HeapMessage.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Helper class to build directly into a HeapMessage, if possible.
*/
class HeapMessageBuilder
{
public:
/**
* @brief Constructor.
*
* @param pHeap the heap to get the HeapMessage from.
* @param approximateSize the approximate size of the message that will be built. A HeapMessage of size
* @a approximateSize will be allocated from @a pHeap.
* @param messageVersion optional version passed through to the underlying MessageBuilder.
*/
HeapMessageBuilder(IHeap * const pHeap, const size_t approximateSize,
const MessageBuilder::MessageVersion messageVersion = MessageBuilder::MESSAGE_VERSION_UNDEFINED);
/**
* @brief Constructor.
*
* @param heapMessage an existing allocated HeapMessage. If it is contiguous, the MessageBuilder will be
* set up initially build in to it directly.
* @param approximateSize the approximate size of the message that will be built. If @a heapMessage is not contiguous,
* this is the size of the MessageBuilder's initial buffer.
* @param messageVersion optional version passed through to the underlying MessageBuilder.
*/
HeapMessageBuilder(HeapMessage &heapMessage, const size_t approximateSize,
const MessageBuilder::MessageVersion messageVersion = MessageBuilder::MESSAGE_VERSION_UNDEFINED);
/**
* @brief Get the underlying MessageBuilder.
*
* @return Reference to MessageBuilder.
*/
MessageBuilder &GetMessageBuilder();
/**
* @brief Get the built HeapMessage.
*
* @return HeapMessage reference. On error, no message will be attached to @a heapMessage
* (!heapMessage will return true).
*/
void GetHeapMessage(HeapMessage &heapMessage);
private:
//! Initialize.
void Initialize();
IHeap * const m_pHeap;
HeapMessage m_heapMessage;
void * m_pBuffer;
size_t m_size;
MessageBuilder m_messageBuilder;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline HeapMessageBuilder::HeapMessageBuilder(IHeap * const pHeap, const size_t approximateSize,
const MessageBuilder::MessageVersion messageVersion) :
m_pHeap(pHeap),
m_heapMessage(*pHeap, approximateSize),
m_pBuffer(0)
{
if (m_heapMessage)
Initialize();
StatusCode statusCode;
if (0 != m_pBuffer)
statusCode = m_messageBuilder.Initialize(m_pBuffer, m_size, true, messageVersion);
else
statusCode = m_messageBuilder.Initialize(approximateSize, true, messageVersion);
if (STATUS_CODE_SUCCESS != statusCode)
ACTIV_THROW(StatusCodeException, statusCode);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline HeapMessageBuilder::HeapMessageBuilder(HeapMessage &heapMessage, const size_t approximateSize,
const MessageBuilder::MessageVersion messageVersion) :
m_pHeap(0),
m_heapMessage(CxxYZ::move(heapMessage)),
m_pBuffer(0)
{
if (m_heapMessage)
Initialize();
else
ACTIV_THROW(StatusCodeException, STATUS_CODE_INVALID_PARAMETER);
StatusCode statusCode;
if (0 != m_pBuffer)
statusCode = m_messageBuilder.Initialize(m_pBuffer, m_size, true, messageVersion);
else
statusCode = m_messageBuilder.Initialize(approximateSize, true, messageVersion);
if (STATUS_CODE_SUCCESS != statusCode)
ACTIV_THROW(StatusCodeException, statusCode);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageBuilder &HeapMessageBuilder::GetMessageBuilder()
{
return m_messageBuilder;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HeapMessageBuilder::GetHeapMessage(HeapMessage &heapMessage)
{
// If we have a HeapMessage, and the message was built into it in one block, set the length of the HeapMessage.
// NB if m_pBuffer is non-null, it must point to a HeapMessage. Hence no check on m_heapMessage being valid.
if ((m_messageBuilder.GetMessage() == m_pBuffer) &&
(STATUS_CODE_SUCCESS == m_heapMessage.SetLength(m_messageBuilder.GetLength())))
{
heapMessage = CxxYZ::move(m_heapMessage);
}
else if (0 != m_pHeap)
{
m_pHeap->GetMessage(m_messageBuilder, heapMessage);
}
else
{
if (STATUS_CODE_SUCCESS == m_heapMessage.Append(m_messageBuilder))
heapMessage = CxxYZ::move(m_heapMessage);
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void HeapMessageBuilder::Initialize()
{
assert(m_heapMessage);
if (ACTIV_LIKELY(m_heapMessage.IsContiguous()))
{
// HeapMessage is contiguous, store pointer and length of one and only block.
const HeapMessage::Iterator iter = m_heapMessage.Begin();
m_pBuffer = const_cast<void *>(iter.GetData());
m_size = iter.GetSize();
}
else
{
m_pBuffer = 0;
m_size = 0;
}
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_HEAP_MESSAGE_BUILDER_H)
@@ -1,152 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/HeapMessageDeserializer.h
*
* @brief Header file for the heap message deserializer template class.
*/
#if (!defined ACTIV_FRAMEWORK_HEAP_MESSAGE_DESERIALIZER_H)
#define ACTIV_FRAMEWORK_HEAP_MESSAGE_DESERIALIZER_H
#include "ActivMiddleware/ActivBase/MessageValidator.h"
#if (defined ACTIV_LITE_FRAMEWORK)
#include "ActivMiddleware/ActivLiteFramework/Message.h"
#else
#include "ActivMiddleware/ActivFramework/HeapMessage.h"
#endif
//! Activ namespace.
namespace Activ
{
#if (!defined ACTIV_LITE_FRAMEWORK)
/**
* @brief Template class to wrap up deserializing a HeapMessage.
*
* @param MESSAGE_TYPE type of message to deserialize. Must have a StatusCode Deserialize(MessageValidator &) method.
* @param BUFFER_SIZE (UNUSED).
*/
template<typename MESSAGE_TYPE, size_t BUFFER_SIZE = 0>
class HeapMessageDeserializer : private Boost::noncopyable
{
public:
/**
* @brief Initialize by getting a pointer to a contiguous block containing the contents of a HeapMessage.
*
* @param heapMessage the HeapMessage to initialize from.
* @param messageVersion optional message version.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
*/
StatusCode Initialize(const HeapMessage &heapMessage,
const MessageHandler::MessageVersion messageVersion = MessageHandler::MESSAGE_VERSION_UNDEFINED);
/**
* @brief Deserialize from the current position.
*
* @param message object to deserialize into.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode Deserialize(MESSAGE_TYPE &message);
/**
* @brief Deserialize the contents of a HeapMessage into an object.
*
* Use this method if the HeapMessage contains only one instance of a message.
*
* @param heapMessage the HeapMessage to initialize from.
* @param message object to deserialize into.
* @param messageVersion optional message version.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_FORMAT
* @retval STATUS_CODE_HEAP_EMPTY
* @retval ...
*/
StatusCode operator()(const HeapMessage &heapMessage, MESSAGE_TYPE &message,
const MessageHandler::MessageVersion messageVersion = MessageHandler::MESSAGE_VERSION_UNDEFINED);
//! Has all data been deserialized from the HeapMessage?
bool IsEndOfMessage() const;
private:
MessageValidator m_messageValidator;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename MESSAGE_TYPE, size_t BUFFER_SIZE>
inline StatusCode HeapMessageDeserializer<MESSAGE_TYPE, BUFFER_SIZE>::Initialize(const HeapMessage &heapMessage,
const MessageHandler::MessageVersion messageVersion)
{
return heapMessage.Get(m_messageValidator, messageVersion);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename MESSAGE_TYPE, size_t BUFFER_SIZE>
inline StatusCode HeapMessageDeserializer<MESSAGE_TYPE, BUFFER_SIZE>::Deserialize(MESSAGE_TYPE &message)
{
return message.Deserialize(m_messageValidator);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename MESSAGE_TYPE, size_t BUFFER_SIZE>
inline StatusCode HeapMessageDeserializer<MESSAGE_TYPE, BUFFER_SIZE>::operator()(const HeapMessage &heapMessage,
MESSAGE_TYPE &message, const MessageHandler::MessageVersion messageVersion)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, Initialize(heapMessage, messageVersion));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, Deserialize(message));
return IsEndOfMessage() ? STATUS_CODE_SUCCESS : STATUS_CODE_INVALID_LENGTH;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename MESSAGE_TYPE, size_t BUFFER_SIZE>
inline bool HeapMessageDeserializer<MESSAGE_TYPE, BUFFER_SIZE>::IsEndOfMessage() const
{
return m_messageValidator.IsEndOfMessage();
}
#endif // (!defined ACTIV_LITE_FRAMEWORK)
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Deserialize the contents of a HeapMessage into an object.
*
* @param heapMessage the HeapMessage to initialize from.
* @param message object to deserialize into.
* @param messageVersion optional message version.
*
* @throw StatusCodeException
*/
template<typename MESSAGE_TYPE>
#if (defined ACTIV_LITE_FRAMEWORK)
inline void DeserializeHeapMessage(const Lite::Message &heapMessage, MESSAGE_TYPE &message,
const MessageHandler::MessageVersion messageVersion = MessageHandler::MESSAGE_VERSION_UNDEFINED)
{
MessageValidator messageValidator(heapMessage.GetData(), heapMessage.GetLength(), messageVersion);
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, message.Deserialize(messageValidator));
}
#else
inline void DeserializeHeapMessage(const HeapMessage &heapMessage, MESSAGE_TYPE &message,
const MessageHandler::MessageVersion messageVersion = MessageHandler::MESSAGE_VERSION_UNDEFINED)
{
MessageValidator messageValidator;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, heapMessage.Get(messageValidator, messageVersion));
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, message.Deserialize(messageValidator));
}
#endif
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_HEAP_MESSAGE_DESERIALIZER_H)
@@ -1,100 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/HeapPool.h
*
* @brief Header file for heap pool class.
*/
#if (!defined ACTIV_FRAMEWORK_HEAP_POOL_H)
#define ACTIV_FRAMEWORK_HEAP_POOL_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/IHeap.h"
#include <vector>
//! Activ namespace.
namespace Activ
{
/**
* @brief Heap pool.
*/
class HeapPool : private Boost::noncopyable
{
public:
/**
* @brief Constructor.
*
* @param pSystem system to create heaps in.
* @param heapSettings properties of heaps to create.
* @param initialSize number of heaps to create initially.
* @param namePrefix prefix to give to heap names.
*/
ACTIV_FRAMEWORK_API
HeapPool(ISystem * const pSystem, const IHeap::Settings &heapSettings, const size_t initialSize,
const String &namePrefix);
/**
* @brief Get a message from the pool of free heaps.
*
* @param pData
* @param dataLength
* @param heapMessage to receive the allocated message.
*/
ACTIV_FRAMEWORK_API
void GetMessage(const void * const pData, const size_t dataLength, HeapMessage &heapMessage);
/**
* @brief Get a heap from the pool.
*
* If no heaps are in the pool, a new heap is created.
*
* @return Pointer to a heap, or 0 if failed to create a heap.
*/
ACTIV_FRAMEWORK_API
IHeap *Get();
/**
* @brief Return a heap to the pool.
*
* @param pHeap the heap to return.
*
* @return true if the heap was returned to the pool, or false if the heap wasn't created by this pool (and therefore
* has not been returned to it).
*/
ACTIV_FRAMEWORK_API
bool Return(IHeap * const pHeap);
/**
* @brief Extend the number of heaps in the pool.
*
* @param numberOfHeaps number of heaps to create.
*
* @return Number of heaps actually created.
*/
ACTIV_FRAMEWORK_API
size_t Extend(const size_t numberOfHeaps);
private:
/**
* @brief Create an individual heap.
*
* @return pHeap the heap, or 0 on error.
*/
IHeap *CreateHeap();
typedef std::set<IHeap *> HeapSet;
typedef std::vector<IHeap *> HeapList;
ISystem * const m_pSystem; ///< System to create heaps in.
const IHeap::Settings m_heapSettings; ///< Properties of heaps to create.
const String m_namePrefix; ///< Prefix to give to heap names.
size_t m_nextHeapNumber; ///< Increasing count to make unique heap names.
HeapSet m_heapSet; ///< Set of all heaps created by this object.
HeapList m_freeHeapList; ///< Free heaps in the pool.
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_HEAP_POOL_H)
@@ -1,457 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/IEndPoint.h
*
* @brief Header file for abstract endpoint class.
*/
#if (!defined ACTIV_FRAMEWORK_IEND_POINT_H)
#define ACTIV_FRAMEWORK_IEND_POINT_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/ThreadUtils.h"
#include "ActivMiddleware/CxxYZ/atomic.h"
//! Activ namespace.
namespace Activ
{
class ISystem;
class HeapMessage;
// ---------------------------------------------------------------------------------------------------------------------------------
//! Endpoint data notification types.
#define ACTIV_IENDPOINT_NOTIFICATION_TYPE_LIST(d) \
d(NOTIFICATION_TYPE_NONE, "none") \
d(NOTIFICATION_TYPE_EVENT, "event") \
d(NOTIFICATION_TYPE_SOCKET, "socket") \
d(NOTIFICATION_TYPE_ACCURATE_WAIT_EVENT, "accurate wait event") \
d(NOTIFICATION_TYPE_COMPLETION_PORT, "completion port")
// ---------------------------------------------------------------------------------------------------------------------------------
//! Endpoint states.
#define ACTIV_IENDPOINT_STATE_LIST(d) \
d(STATE_ALLOWING_MESSAGES, "accepting") \
d(STATE_PROCESSING_MESSAGES, "processing") \
d(STATE_IGNORING_MESSAGES, "ignoring")
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Abstract endpoint interface class.
*/
class IEndPoint : private Boost::noncopyable
{
public:
//! Endpoint data notification types.
enum NotificationType
{
ACTIV_IENDPOINT_NOTIFICATION_TYPE_LIST(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
NOTIFICATION_TYPE_DEFAULT = -1,
#if (defined ACTIV_PLATFORM_WINDOWS)
NOTIFICATION_TYPE_MULTIPLEX = NOTIFICATION_TYPE_EVENT
#elif (defined ACTIV_PLATFORM_POSIX)
NOTIFICATION_TYPE_MULTIPLEX = NOTIFICATION_TYPE_SOCKET
#else
#error Configure
#endif
};
//! Settings for endpoint creation.
class Settings
{
public:
//! Default constructor.
ACTIV_FRAMEWORK_API Settings();
bool m_hasMutex; ///< Default: false.
NotificationType m_notificationType; ///< Default: NOTIFICATION_TYPE_NONE.
//! For NOTIFICATION_TYPE_COMPLETION_PORT only. Default: 0 (a completion port is created).
HANDLE m_completionPort;
};
//! Endpoint states.
enum State
{
ACTIV_IENDPOINT_STATE_LIST(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
NUM_STATES
};
//! Stats for an endpoint.
class Stats
{
public:
NotificationType m_notificationType; ///< Message notification type.
bool m_hasMutex; ///< Does the endpoint have a mutex?
size_t m_mutexContentionCount; ///< Approx. contentions on the endpoint's mutex.
State m_state;
size_t m_messageCount; ///< Current number of messages on endpoint.
size_t m_messageCountHigh; ///< All-time high number of messages on endpoint.
size_t m_messageCountDailyHigh; ///< Daily high number of messages on endpoint.
size_t m_messageCountLastHigh; ///< High number of messages on endpoint in last stats interval.
size_t m_byteCount; ///< Current number of bytes on endpoint.
size_t m_byteCountHigh; ///< All-time high number of bytes on endpoint.
size_t m_byteCountDailyHigh; ///< Daily high number of bytes on endpoint.
size_t m_byteCountLastHigh; ///< High number of bytes on endpoint in last stats interval.
};
// Loop count type.
typedef uint32_t LoopCount;
// Peak loop time. -1 means not set.
typedef int64_t PeakLoopTime;
//! Destructor.
virtual ~IEndPoint() = 0;
/**
* @brief Add a message to the tail of the endpoint.
*
* @param heapMessage the message to add.
*
* @retval STATUS_CODE_SUCCESS @a heapMessage added to this endpoint.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages. @a heapMessage returned to its heap.
* @retval STATUS_CODE_FULL the endpoint maximum byte count has been reached. @a heapMessage returned to its heap.
* @retval STATUS_CODE_ACCESS_DENIED this does not support private messages and @a heapMessage is a private message.
*/
virtual StatusCode PostMessage(HeapMessage &heapMessage) = 0;
/**
* @brief Add a chain of messages to the tail of this endpoint.
*
* @param pEndPoint the chain of messages to add.
*
* @retval STATUS_CODE_SUCCESS messages on @a pEndPoint added to this endpoint.
* @retval STATUS_CODE_DISABLED this is not accepting messages. All messages returned to their heap(s).
* @retval STATUS_CODE_FULL this endpoint's maximum byte count has been reached. All messages returned to their heap(s).
* @retval STATUS_CODE_ACCESS_DENIED this does not support private messages and @a pEndPoint endpoint does.
*/
virtual StatusCode PostMessages(IEndPoint * const pEndPoint) = 0;
/**
* @brief Try to add a chain of messages to the tail of this endpoint.
*
* @param pEndPoint the chain of messages to add. This must be a non-mutexed, non-notification endpoint.
*
* @retval STATUS_CODE_SUCCESS @a heapMessage added to the endpoint.
* @retval STATUS_CODE_FAILURE unable to acquire the mutex on this or @a pEndPoint. If this, messages dequeued from
* @a pEndPoint have been returned to their heap(s).
* @retval STATUS_CODE_DISABLED this is not accepting messages. All messages returned to their heap(s).
* @retval STATUS_CODE_FULL this endpoint's maximum byte count has been reached. All messages returned to their heap(s).
* @retval STATUS_CODE_ACCESS_DENIED this does not support private messages and @a pEndPoint endpoint does.
*/
virtual StatusCode TryPostMessages(IEndPoint * const pEndPoint) = 0;
/**
* @brief Get a message from the head of the endpoint.
*
* @param heapMessage reference to a HeapMessage object to receive the head message.
* @param timeout how long to wait for a message on the endpoint, in ms.
* Will be ignored if the object was not created with a data notification mechanism.
*
* @retval STATUS_CODE_SUCCESS.
* @retval STATUS_CODE_TIMEOUT no messages on this endpoint in the timeout period, @a heapMessage unaffected. Note this
* return value is possible even with @a timeout set to ACTIV_WAIT_INFINITE. @a heapMessage will only contain
* a retrieved message if the return value is STATUS_CODE_SUCCESS.
*/
virtual StatusCode GetMessage(HeapMessage &heapMessage, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) = 0;
/**
* @brief Get multiple messages from this endpoint and add to the tail of a second endpoint.
*
* @param pEndPoint the endpoint to add messages to.
* @param timeout how long to wait for a message on this endpoint, in ms.
* Will be ignored if the object was not created with a data notification mechanism.
*
* @retval STATUS_CODE_SUCCESS.
* @retval STATUS_CODE_TIMEOUT no messages on this endpoint in the timeout period, @a pEndPoint unaffected.
* @retval STATUS_CODE_DISABLED @a pEndPoint is not accepting messages, all returned to their heap(s).
* @retval STATUS_CODE_FULL @a pEndPoint's maximum byte count has been reached. All messages returned to their heap(s).
* @retval STATUS_CODE_ACCESS_DENIED @a pEndPoint does not support private messages and this endpoint does.
*/
virtual StatusCode GetMessages(IEndPoint * const pEndPoint, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) = 0;
/**
* @brief Try to get multiple messages from this endpoint and add to the tail of a second endpoint.
*
* @param pEndPoint the endpoint to add messages to.
*
* @retval STATUS_CODE_SUCCESS.
* @retval STATUS_CODE_FAILURE unable to acquire the mutex on this or @a pEndPoint. If pEndPoint, messages dequeued from
* this have been returned to their heap(s).
* @retval STATUS_CODE_DISABLED @a pEndPoint is not accepting messages, all returned to their heap(s).
* @retval STATUS_CODE_FULL @a pEndPoint's maximum byte count has been reached. All messages returned to their heap(s).
* @retval STATUS_CODE_ACCESS_DENIED @a pEndPoint does not support private messages and this endpoint does.
*/
virtual StatusCode TryGetMessages(IEndPoint * const pEndPoint) = 0;
/**
* @brief Get the loop count.
*
* Incremented on each message loop.
*
* @return reference to atomic loop count.
*/
virtual CxxYZ::atomic<LoopCount> &GetLoopCount() = 0;
/**
* @brief Get the peak message loop time.
*
* Holds the peak duration of a single message loop since the value was last cleared by MonitorService.
*
* @return reference to atomic peak loop time.
*/
virtual CxxYZ::atomic<PeakLoopTime> &GetPeakLoopTime() = 0;
/**
* @brief Remove all messages from the endpoint and return them to their heaps. Any queued requests are replied to with a
* status of STATUS_CODE_FAILURE.
*/
virtual void Clear() = 0;
/**
* @brief Set the state of the endpoint.
*
* Setting the endpoint state to STATE_IGNORING_MESSAGES implicitly clears the endpoint of any queued messages, and
* replies to any queued requests with STATUS_CODE_FAILURE.
*
* @param state the state to set the endpoint to.
*/
virtual void SetState(const State state) = 0;
//! Get the current state of the endpoint.
virtual State GetState() const = 0;
/**
* @brief Set the id of the thread processing the endpoint.
*
* @param threadId os id of the thread processing the endpoint.
*/
virtual void SetProcessingThreadId(const ThreadUtils::OsId threadId) = 0;
/**
* @brief Get the id of the thread processing the endpoint.
*
* @param threadId reference to receive the os thread id.
*
* @return whether the processing thread id has been set.
*/
virtual bool GetProcessingThreadId(ThreadUtils::OsId &threadId) = 0;
/**
* @brief Set whether the thread processing the endpoint is polling.
*
* @param isPolling whether the thread processing the endpoint is polling.
*/
virtual void SetIsPolling(const bool isPolling) = 0;
//! Is the thread processing the endpoint polling?
virtual bool IsPolling() const = 0;
//! Increment the busy cpu reset count.
virtual void IncrementBusyCpuResetCount() = 0;
//! Get the current busy reset count.
virtual size_t GetBusyCpuResetCount() const = 0;
//! Get the system that created the endpoint.
virtual ISystem *GetSystem() const = 0;
/**
* @brief Get endpoint stats.
*
* @param stats reference to a Stats object.
*/
virtual void GetStats(Stats &stats) const = 0;
//! Clear all high message and byte counts.
virtual void ClearAllHighCounts() = 0;
//! Clear daily high message and byte counts.
virtual void ClearDailyHighCounts() = 0;
//! Clear last high message and byte counts.
virtual void ClearLastHighCounts() = 0;
/**
* @brief Set the maximum bytes allowed on the endpoint.
*
* By default there is no limit, but if set to a non 0 value, posting a message to an endpoint which takes
* the number of bytes on the endpoint to over maxByteCount, the call will return STATUS_CODE_FULL.
*
* @param maxByteCount max bytes to allow on the endpoint, or 0 for no limit.
*/
virtual void SetMaxByteCount(const size_t maxByteCount) = 0;
//! Get maximum bytes allowed on the endpoint (0 is unlimited).
virtual size_t GetMaxByteCount() const = 0;
//! Get the underlying message notification type.
virtual NotificationType GetNotificationType() const = 0;
/**
* @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 endpoint does not support an exportable handle.
*/
virtual StatusCode GetNotificationHandle(HANDLE &handle) const = 0;
/**
* @brief Return an endpoint notification type in string form.
*
* @param notificationType to convert.
*
* @return Notification type as a string.
*/
ACTIV_FRAMEWORK_API
static String NotificationTypeToString(const NotificationType notificationType);
/**
* @brief Return all endpoint notification types in pretty-printed string form.
*
* @return Notification types as a string.
*/
ACTIV_FRAMEWORK_API
static String NotificationTypesToString();
/**
* @brief Convert string to notification type.
*
* @param str the string to convert.
* @param notificationType to receive the notification type value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
*/
ACTIV_FRAMEWORK_API
static StatusCode StringToNotificationType(const String &str, NotificationType &notificationType);
/**
* @brief Return an endpoint state in string form.
*
* @param state to convert.
*
* @return Endpoint state as a string.
*/
ACTIV_FRAMEWORK_API
static String StateToString(const State state);
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Endpoint types.
#define ACTIV_IADDRESSABLE_ENDPOINT_TYPE_LIST(d) \
d(TYPE_UNMANAGED, "unmanaged") \
d(TYPE_SYNCHRONOUS, "synchronous") \
d(TYPE_MANAGED, "managed") \
d(TYPE_EVENT_MANAGED, "event managed") \
d(TYPE_EVENT_MANAGED_PARENT, "event managed parent") \
d(TYPE_EVENT_MANAGED_CHILD, "event managed child")
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Endpoint interface for an endpoint that is addressable.
*/
class IAddressableEndPoint : public IEndPoint
{
public:
//! Endpoint types.
enum Type
{
ACTIV_IADDRESSABLE_ENDPOINT_TYPE_LIST(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
NUMBER_OF_TYPES
};
class Settings : public IEndPoint::Settings
{
public:
/**
* @brief Default constructor.
*
* m_hasMutex is set to true.
* m_notificationType is set to NOTIFICATION_TYPE_DEFAULT.
*/
ACTIV_FRAMEWORK_API
Settings();
String m_name; ///< The name of the endpoint. If empty, the endpoint is given a name based on a unique id.
Type m_type; ///< Default: TYPE_UNMANAGED.
};
//! Stats for an addressable endpoint.
class Stats : public IEndPoint::Stats
{
public:
String m_name; ///< Name of the endpoint.
EndPointId m_id; ///< System-wide id of the endpoint.
EndPointId m_parentId; ///< If a child endpoint, the id of the parent.
ProcessId m_creatorProcessId; ///< Pid of the process that created the endpoint.
Type m_type; ///< Endpoint type.
};
//! Get the unique system wide name of the endpoint.
virtual String GetName() const = 0;
//! Get the unique system-wide id of the endpoint.
virtual EndPointId GetId() const = 0;
//! If this is a child endpoint, get the id of the parent otherwise INVALID_ENDPOINT_ID.
virtual EndPointId GetParentId() const = 0;
//! Get the process id of the creator of the endpoint.
virtual ProcessId GetCreatorProcessId() const = 0;
//! Get the endpoint's type.
virtual Type GetType() const = 0;
/**
* @brief Get endpoint stats.
*
* @param stats reference to a Stats object.
*/
virtual void GetStats(Stats &stats) const = 0;
// Keep the base GetStats() visible and rely on ADL to pick up the appropriate function.
using IEndPoint::GetStats;
//! Return an endpoint type in string form.
ACTIV_FRAMEWORK_API
static String TypeToString(const Type type);
//! Return all endpoint types in pretty-printed string form.
ACTIV_FRAMEWORK_API
static String TypesToString();
/**
* @brief Convert string to endpoint type.
*
* @param str the string to convert.
* @param type to receive the type value.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
*/
ACTIV_FRAMEWORK_API
static StatusCode StringToType(const String &str, Type &type);
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline IEndPoint::~IEndPoint()
{
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_IEND_POINT_H)
@@ -1,520 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/IHeap.h
*
* @brief Header file for abstract heap class.
*/
#if (!defined ACTIV_FRAMEWORK_IHEAP_H)
#define ACTIV_FRAMEWORK_IHEAP_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/IniFileParser.h"
#include "ActivMiddleware/ActivBase/FieldTypes/DateTime.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include <vector>
//! Activ namespace.
namespace Activ
{
class ISystem;
class HeapMessage;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Abstract heap interface class.
*/
class IHeap : private Boost::noncopyable
{
public:
/**
* @brief Heap bucket size information.
*/
class BucketInfo
{
public:
size_t m_messageSize; ///< Size of message body in each message in this bucket.
size_t m_numberOfMessages; ///< Number of messages in this bucket.
};
typedef std::vector<BucketInfo> BucketInfoVector; ///< Bucket info vector type.
/**
* @brief Heap settings.
*/
class Settings
{
public:
/**
* @brief Inter-message padding size.
*/
enum InterMessagePadding
{
INTER_MESSAGE_PADDING_WORD_SIZE, ///< Pad messages in heap by processor word size.
INTER_MESSAGE_PADDING_CACHE_SIZE ///< Pad messages in heap by processor cache line size.
};
//! Default constructor.
ACTIV_FRAMEWORK_API
Settings();
/**
* @brief Constructor.
*
* @param bucketInfoVector
*/
ACTIV_FRAMEWORK_API
Settings(const BucketInfoVector &bucketInfoVector);
/**
* @brief Read setting from an ini-file.
*
* @param sectionIterator
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API
void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
/**
* @brief Padding between messages in a heap. Default: INTER_MESSAGE_PADDING_WORD_SIZE.
*/
InterMessagePadding m_interMessagePadding;
/**
* @brief Should memory lock the heap. Default: false. Posix and Shared memory only.
*/
bool m_shouldMemoryLock;
/**
* @brief Description of buckets to use.
*/
BucketInfoVector m_bucketInfoVector;
/**
* @brief Private memory only: how much of the heap to pre-allocate, as a percentage of the bucket definitions.
* Default: 0%.
*/
size_t m_preallocationPercent;
/**
* @brief Scale the number of messages in m_bucketInfoVector for thread local buckets, if m_isFastPathGetEnabled is true
* or for the shared buckets if m_isFastPathGetEnabled is false.
* Default: 100%.
*/
size_t m_bucketsScalePercent;
/**
* @brief Enable single-threaded optimization of the GetMessage() methods? In this case, the heap will create
* two sets of buckets. One set of buckets will be of the size defined in m_bucketInfoVector, and will be
* assigned to whichever thread is chosen as the fast-path get thread using the thresholds below. The second
* set of buckets will have the number of messages in them scaled by m_fastPathSharedBucketsScalePercent
* and will be available to satisfy any other thread making a GetMessage() call. Default: false.
*/
bool m_isFastPathGetEnabled;
/**
* @brief Enable single-threaded optimization of the return path? Default: true.
*/
bool m_isFastPathReturnEnabled;
/**
* @brief Scale the number of messages in m_bucketInfoVector for shared buckets, if m_isFastPathGetEnabled is true.
* Default: 15%.
*/
size_t m_fastPathSharedBucketsScalePercent;
/**
* @brief Don't create a scaled bucket smaller than this number of messages (when m_isFastPathGetEnabled is true).
* Default: 10.
*/
size_t m_fastPathMinimumScaledBucketSize;
/**
* @brief Number of get/return operations that must be done before the Heap will attempt to chose the single-threaded
* optimized fast-path thread. If no thread has done m_fastPathThresholdPercent % of the gets/returns after
* 2*m_fastPathThreshold gets/returns, no thread is chosen and all threads will continue to use the slow-path.
* Default: 50000.
*/
size_t m_fastPathThreshold;
/**
* @brief A thread must do this % of the total gets or returns before it will be chosen as the single-threaded
* optimized fast-path thread. Default 90%.
*/
size_t m_fastPathThresholdPercent;
/**
* @brief How empty a thread-local get free-list must be before it replenishes itself from the shared free-lists.
* Default: 60%.
*/
size_t m_fastPathGetMoveFreeListPercent;
/**
* @brief How full a thread-local return free-list must be before it is pushed back to the shared free-lists.
* Default: 10%.
*/
size_t m_fastPathReturnMoveFreeListPercent;
/**
* @brief Whether to enable distribution logging. Default: false (release build), true (debug build). Note will have
* noticeable performance impact.
*/
bool m_isRequestDistributionLoggingEnabled;
/**
* @brief Whether to alert on heap failures. Default: true.
*/
bool m_isAlertingEnabled;
};
/**
* @brief Heap stats.
*/
class Stats
{
public:
/**
* @brief Request distribution stats.
*/
class RequestDistributionStats
{
public:
size_t m_minSize; ///< Minimum size of request.
size_t m_maxSize; ///< Maximum size of request.
size_t m_count; ///< Number of requests >= m_minSize and <= m_maxSize.
};
typedef std::vector<RequestDistributionStats> DistributionVector;
/**
* @brief Individual Bucket stats.
*/
class BucketStats
{
public:
/**
* @brief Default constructor.
*/
ACTIV_FRAMEWORK_API
BucketStats();
BucketInfo m_bucketInfo;
size_t m_numberOfFreeMessages; ///< Number of free messages.
size_t m_lowFreeMessagesInInterval; ///< Lowest number of free messages in log interval.
size_t m_lowFreeMessages; ///< Lowest number of free messages since daily reset.
size_t m_firstRunFails; ///< Number of fails when most ideal sized bucket.
size_t m_secondRunFails; ///< Number of fails when > ideal sized bucket.
};
typedef std::vector<BucketStats> BucketStatsVector;
/**
* @brief List of bucket stats.
*/
class BucketListStats
{
public:
/**
* @brief Default constructor.
*/
ACTIV_FRAMEWORK_API
BucketListStats();
/**
* @brief Get the current free % across all buckets in this list.
*
* @return Current free percentage, or 100 if no messages in this bucket list.
*/
size_t GetCurrentFreePercent() const;
/**
* @brief Get the low free % across all buckets in this list.
*
* @return Low free percentage, or 100 if no messages in this bucket list.
*/
size_t GetLowFreePercent() const;
/**
* @brief Get the low free % across all buckets in this list during the last logging interval.
*
* @return Interval low free percentage, or 100 if no messages in this bucket list.
*/
size_t GetIntervalLowFreePercent() const;
size_t m_numberOfFails; ///< Number of GetMessage() calls failed using this set of buckets.
size_t m_totalNumberOfMessages; ///< Number of messages in total in this set of buckets.
size_t m_totalCurrentFreeMessages; ///< Current free messages across all buckets in this set.
size_t m_totalLowFreeMessagesInInterval; ///< Low of free messages across all buckets in this set in log interval.
size_t m_totalLowFreeMessages; ///< Low of free messages across all buckets in this set since daily reset.
BucketStatsVector m_bucketStatsVector; ///< Individual bucket stats.
};
ACTIV_FRAMEWORK_API
Stats();
/**
* @brief Get the current free % across all buckets.
*
* If the heap has fast-path gets active, the lowest of the shared and fast-path buckets is returned.
*
* @return Current free percentage.
*/
size_t GetCurrentFreePercent() const;
/**
* @brief Get the low free % across all buckets.
*
* If the heap has fast-path gets active, the lowest of the shared and fast-path buckets is returned.
*
* @return Low free percentage.
*/
size_t GetLowFreePercent() const;
/**
* @brief Get the low free % across all buckets during the last logging interval.
*
* If the heap has fast-path gets active, the lowest of the shared and fast-path buckets is returned.
*
* @return Interval low free percentage.
*/
size_t GetIntervalLowFreePercent() const;
// Heap-wide constants.
HeapId m_id;
ProcessId m_creatorProcessId;
String m_name;
size_t m_memoryUsage; ///< Approximate memory usage of this heap.
// Heap-wide stats.
size_t m_numberOfIdealBucketFails; ///< Number of requests for a message larger than largest bucket size.
size_t m_numberOfTotalFails; ///< Number of GetMessage() requests that have failed in total.
DateTime m_firstFailLocalDateTime; ///< Local date/time of first fail.
DateTime m_lastFailLocalDateTime; ///< Local date/time of last fail.
size_t m_mutexContentionCount; ///< Approx. contentions on the heap's mutex.
// Shared bucket stats.
BucketListStats m_sharedBucketListStats; ///< Shared bucket list stats.
// Fast-path stats.
bool m_isFastPathGetEnabled; ///< Was heap created with m_isFastPathGetEnabled set in Settings?
bool m_isFastPathGetActive; ///< Has a thread been allocated to fast-path gets?
bool m_isFastPathReturnEnabled; ///< Was heap created with m_isFastPathReturnEnabled set in Settings?
bool m_isFastPathReturnActive; ///< Has a thread been allocated to fast-path returns?
String m_fastPathGetThreadName; ///< If active, the thread with fast path gets enabled.
String m_fastPathReturnThreadName; ///< If active, the thread with fast path returns enabled.
BucketListStats m_fastPathBucketListStats; ///< Only relevant if m_isFastPathGetEnabled.
// IHeap::SetRequestDistributionLogging(true) needs to be called for the following to be populated:
size_t m_maxRequestSize; ///< Size of max request.
DistributionVector m_distributionVector; ///< Request stats distribution.
};
/**
* @brief Destructor.
*/
virtual ~IHeap() = 0;
/**
* @brief Get a message or chain of messages from the heap.
*
* @param size the number of bytes the message needs to hold.
* @param heapMessage to receive the allocated message. If message allocation fails, @a heapMessage will not have an
* attached message (i.e. !heapMessage will be true).
*/
void GetMessage(const size_t size, HeapMessage &heapMessage);
/**
* @brief Get a message or chain of messages from the heap and copy data in.
*
* @param pData pointer to data to copy into the message. Can be null.
* @param dataLength the number of bytes the messages needs to hold and the number of bytes from @a pData copied in.
* @param heapMessage to receive the allocated message. If message allocation or data copy fails, @a heapMessage will not
* have an attached message (i.e. !heapMessage will be true).
*/
void GetMessage(const void *pData, const size_t dataLength, HeapMessage &heapMessage);
/**
* @brief Get a message or chain of messages from the heap and block if the heap is empty.
*
* @param pData pointer to data to copy into the message.
* @param dataLength the number of bytes the messages needs to hold and the number of bytes from @a pData copied in.
* @param timeoutPeriod maximum time to wait for a message allocation to succeed if the heap is empty.
* @param heapMessage to receive the allocated message. If message allocation or data copy fails, @a heapMessage will not
* have an attached message (i.e. !heapMessage will be true).
*/
ACTIV_FRAMEWORK_API
void GetMessage(const void *pData, const size_t dataLength, const TimeoutPeriod timeoutPeriod, HeapMessage &heapMessage);
/**
* @brief Get a message or chain of messages from the heap and copy data in.
*
* @param messageBuilder containing the data to copy in to the message.
* @param heapMessage to receive the allocated message. If message allocation or data copy fails, @a heapMessage will not
* have an attached message (i.e. !heapMessage will be true).
*/
void GetMessage(const MessageBuilder &messageBuilder, HeapMessage &heapMessage);
/**
* @brief Get the name of the heap.
*
* @return A string object containing the name of the heap.
*/
virtual String GetName() const = 0;
/**
* @brief Get the unique system wide heap id.
*
* @return The heap id.
*/
virtual HeapId GetId() const = 0;
/**
* @brief Get the system that created the heap.
*
* @return An ISystem interface.
*/
virtual ISystem *GetSystem() const = 0;
/**
* @brief Get heap stats.
*
* @param returnStats reference to a stats object.
*/
virtual void GetStats(Stats &returnStats) const = 0;
/**
* @brief Get previous heap stats.
*
* @param returnStats reference to a stats object.
*/
virtual void GetPreviousStats(Stats &returnStats) const = 0;
/**
* @brief Reset heap stats.
*/
virtual void ResetStats() = 0;
/**
* @brief Reset daily heap stats.
*/
virtual void ResetDailyStats() = 0;
/**
* @brief Get request distribution logging state.
*
* @return true if request distribution loggin is enabled.
*/
virtual bool GetRequestDistributionLogging() const = 0;
/**
* @brief Enable or disable request distribution logging.
*
* @param shouldEnable true to enable.
*/
virtual void SetRequestDistributionLogging(const bool shouldEnable) = 0;
/**
* @brief Is alerting on failures enabled?
*
* @return Boolean.
*/
virtual bool IsAlertingEnabled() const = 0;
/**
* @brief Get a message or chain of messages from a list of heaps.
*
* @param heapMessage to receive the message.
* @param size the maximum number of bytes the message will hold.
* @param ... a 0 terminated list of IHeap pointers.
*
* GetMessage() will be called on each heap until a successful allocation.
*/
ACTIV_FRAMEWORK_API
static void GetMessageFromList(HeapMessage &heapMessage, const size_t size, ...);
protected:
virtual void InternalGetMessage(const size_t size, const bool shouldUpdateFailStats, HeapMessage &heapMessage) = 0;
virtual size_t GetMaxMessageSize() const = 0;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline IHeap::~IHeap()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IHeap::GetMessage(const size_t size, HeapMessage &heapMessage)
{
return InternalGetMessage(size, true, heapMessage);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IHeap::GetMessage(const MessageBuilder &messageBuilder, HeapMessage &heapMessage)
{
return GetMessage(messageBuilder.GetMessage(), messageBuilder.GetLength(), heapMessage);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t IHeap::Stats::GetCurrentFreePercent() const
{
if (!m_isFastPathGetEnabled)
return m_sharedBucketListStats.GetCurrentFreePercent();
return GetMinimum<size_t>(m_sharedBucketListStats.GetCurrentFreePercent(), m_fastPathBucketListStats.GetCurrentFreePercent());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t IHeap::Stats::GetLowFreePercent() const
{
if (!m_isFastPathGetEnabled)
return m_sharedBucketListStats.GetLowFreePercent();
return GetMinimum<size_t>(m_sharedBucketListStats.GetLowFreePercent(), m_fastPathBucketListStats.GetLowFreePercent());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t IHeap::Stats::GetIntervalLowFreePercent() const
{
if (!m_isFastPathGetEnabled)
return m_sharedBucketListStats.GetIntervalLowFreePercent();
return GetMinimum<size_t>(m_sharedBucketListStats.GetIntervalLowFreePercent(),
m_fastPathBucketListStats.GetIntervalLowFreePercent());
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t IHeap::Stats::BucketListStats::GetCurrentFreePercent() const
{
return (m_totalNumberOfMessages != 0) ? ((m_totalCurrentFreeMessages * 100) / m_totalNumberOfMessages) : 100;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t IHeap::Stats::BucketListStats::GetLowFreePercent() const
{
return (m_totalNumberOfMessages != 0) ? ((m_totalLowFreeMessages * 100) / m_totalNumberOfMessages) : 100;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t IHeap::Stats::BucketListStats::GetIntervalLowFreePercent() const
{
return (m_totalNumberOfMessages != 0) ? ((m_totalLowFreeMessagesInInterval * 100) / m_totalNumberOfMessages) : 100;
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_IHEAP_H)
@@ -1,134 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/IProcess.h
*
* @brief Header file for process interface class.
*/
#if (!defined ACTIV_FRAMEWORK_IPROCESS_H)
#define ACTIV_FRAMEWORK_IPROCESS_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/MessageValidator.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include "ActivMiddleware/ActivBase/Process.h"
#include "ActivMiddleware/ActivBase/Timeout.h"
/**
* @brief List of process states.
*/
#define ACTIV_IPROCESS_STATE_LIST(d) \
d(STATE_INITIALIZING, "initializing") \
d(STATE_RUNNING, "running") \
d(STATE_SHUTTING_DOWN, "shutting down") \
d(STATE_EXITED, "exited") \
d(STATE_DEAD, "dead")
//! Activ namespace.
namespace Activ
{
class ISystem;
class Uuid;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Process interface class.
*/
class IProcess : private Boost::noncopyable
{
public:
typedef Process::Id OsProcessId;
//! @brief Process states.
enum State
{
ACTIV_IPROCESS_STATE_LIST(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
NUM_STATES
};
//! Process stats.
class Stats
{
public:
ProcessId m_id; ///< System wide id of the process.
OsProcessId m_osId; ///< OS wide id if the process.
String m_name; ///< Name of the process in the system.
String m_version; ///< Process version string.
String m_type; ///< Process type string.
String m_userContext; ///< Arbitrary user context string.
State m_state; ///< State of the process.
};
//! Destructor.
virtual ~IProcess() = 0;
//! Get the system unique process id for this process.
virtual ProcessId GetId() const = 0;
//! Get the os process id for this process.
virtual OsProcessId GetOsId() const = 0;
//! @brief Get the name of this process.
virtual const String &GetName() const = 0;
//! Get the type of this process.
virtual const String &GetType() const = 0;
//! Get the user context for this process.
virtual const String &GetUserContext() const = 0;
//! Get UUID of this process.
virtual const Uuid &GetUuid() const = 0;
//! Get the system that created the process.
virtual ISystem *GetSystem() const = 0;
/**
* @brief Get process stats.
*
* @param stats reference to a Stats object.
*/
virtual void GetStats(Stats &stats) const = 0;
//! Get the current state of the process.
virtual State GetState() const = 0;
/**
* @brief Set the state of the process.
*
* @param state new state.
*/
virtual void SetState(const State state) = 0;
/**
* @brief Wait for the state of the process to be a given value.
*
* @param state to wait for.
* @param timeout how long to wait.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_TIMEOUT
*/
virtual StatusCode WaitForState(const State state, Timeout &timeout = Timeout::GetInfinite()) = 0;
/**
* @brief Convert process state to string.
*
* @param state state to convert.
*
* @return string form of system state.
*/
ACTIV_FRAMEWORK_API
static String StateToString(const State state);
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline IProcess::~IProcess()
{
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_IPROCESS_H)
@@ -1,105 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ISocketEventManagee.h
*
* @brief Header file for ISocketEventManagee and derived classes.
*/
#if (!defined ACTIV_FRAMEWORK_I_SOCKET_EVENT_MANAGEE_H)
#define ACTIV_FRAMEWORK_I_SOCKET_EVENT_MANAGEE_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include "ActivMiddleware/ActivBase/Ip/UdpDatagramInfo.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#include "ActivMiddleware/Misc/CrtHelper.h"
#include ACTIV_BOOST_INCLUDE(smart_ptr/intrusive_ptr.hpp)
#include ACTIV_BOOST_INCLUDE(smart_ptr/intrusive_ref_counter.hpp)
//! Activ namespace.
namespace Activ
{
// Forward declarations.
class IpAddress;
class ManagedEndPoint;
// Declare smart pointer.
class ISocketEventManagee;
typedef Boost::intrusive_ptr<ISocketEventManagee> ISocketEventManageePointer;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Interface class to hook a local datagram socket in to an endpoint's EventManager.
*
* If there is intention to destroy a ISocketEventManagee inside the context of the OnEvents() callback, then it should be
* referenced counted with ISocketEventManageePointer.
*/
class ISocketEventManagee : public Boost::intrusive_ref_counter<ISocketEventManagee, Boost::thread_unsafe_counter>
{
public:
//! OnDatagram callback function definition.
typedef UdpDatagramCallbackFunction CallbackFunction;
/**
* @brief Create a ISocketEventManagee.
*
* @param managedEndPoint
* @param callbackFunction
* @param socket the socket handle to process events on. This will be cloned.
* @param maximumReadBytes the maximum number of bytes to read from the socket in one event. 0 for no limit.
*
* @return A pointer to the ISocketEventManagee, always valid.
*
* @throw StatusCodeException
*/
ACTIV_FRAMEWORK_API static ISocketEventManageePointer Create(ManagedEndPoint &managedEndPoint,
const CallbackFunction &callbackFunction, const SOCKET socket, const size_t maximumReadBytes);
//! Destructor.
ACTIV_FRAMEWORK_API virtual ~ISocketEventManagee();
/**
* @brief Initiate a read on the socket.
*
* The socket receive buffer is emptied first (without invoking OnDatagram()). This is to avoid issues with receive buffer
* overflows between socket creation and calling this function (which might cause retransmissions, for example).
*
* @return STATUS_CODE_SUCCESS or an error value.
*/
ACTIV_FRAMEWORK_API virtual StatusCode InitiateRead() = 0;
/**
* @brief Do a blocking send of some data to a specified ip address.
*
* @param ipAddress destination ip address.
* @param pData pointer to data to send.
* @param dataLength length of data to send.
*
* @return STATUS_CODE_SUCCESS or an error value.
*/
ACTIV_FRAMEWORK_API virtual StatusCode PostData(const IpAddress &ipAddress, const void * const pData,
const size_t dataLength) = 0;
//! Get the source IpAddress.
const IpAddress &GetSourceIpAddress() const;
//! Is timestamping enabled?
ACTIV_FRAMEWORK_API virtual bool IsTimeStampingEnabled() const = 0;
protected:
UdpDatagramInfo m_udpDatagramInfo;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline const IpAddress &ISocketEventManagee::GetSourceIpAddress() const
{
return m_udpDatagramInfo.m_sourceIpAddress;
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_I_SOCKET_EVENT_MANAGEE_H)
@@ -1,455 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ISystem.h
*
* @brief Header file for abstract system class.
*/
#if (!defined ACTIV_FRAMEWORK_ISYSTEM_H)
#define ACTIV_FRAMEWORK_ISYSTEM_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/DateTime.h"
#include "ActivMiddleware/ActivBase/IniFileParser.h"
#include "ActivMiddleware/ActivBase/Process.h"
#include "ActivMiddleware/ActivBase/SystemInfo.h"
#include "ActivMiddleware/ActivBase/Timeout.h"
#include "ActivMiddleware/ActivFramework/IEndPoint.h"
#include "ActivMiddleware/ActivFramework/IHeap.h"
#include "ActivMiddleware/ActivFramework/IProcess.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Abstract system interface class.
*
* Provides functionality to create new or open existing endpoints and heaps.
*/
class ISystem : private Boost::noncopyable
{
public:
/**
* @brief Settings.
*/
class Settings
{
public:
enum MemoryModel
{
MEMORY_MODEL_SHARED, ///< System exists in shared memory.
MEMORY_MODEL_PRIVATE ///< System exists in private memory.
};
enum SystemLogMode
{
SYSTEM_LOG_MODE_OFF, ///< System log off for this process.
SYSTEM_LOG_MODE_TO_CONSOLE, ///< System log goes to local console for this process.
SYSTEM_LOG_MODE_TO_AGENT ///< System log messages published to agent for this process.
};
/**
* @brief 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);
String m_systemName; ///< Name of the system to create / open (default is contents of ACTIV_SYSTEM_NAME env-var if set, otherwise "System").
MemoryModel m_memoryModel; ///< Shared or private memory system (default private).
String m_processVersion; ///< Process version string.
String m_processType; ///< Process type string.
String m_processUserContext; ///< Arbitrary user context string for the process.
bool m_setConsoleTitle; ///< Set console title (default false).
SystemLogMode m_systemLogMode; ///< System log mode for this process (default SYSTEM_LOG_MODE_TO_AGENT).
ProcessorAffinity m_processorAffinity; ///< Default: do not adjust.
uint16_t m_initialThreadAffinityProcessorId; ///< First processor to use when allocating thread affinities.
bool m_shouldSwitchToAgentUser; ///< Linux only. Default: true. If true the child process should be switch to the Agent user if run as root.
String m_memoryAllocationTraceFile; ///< Linux only: file to trace malloc/frees to. Default: empty.
bool m_shouldEnableThreadSpecificEndPoints; ///< Default: false. Enable thread-specific endpoints.
protected:
ACTIV_FRAMEWORK_API
static const String sectionName; ///< All settings are in this section.
};
/**
* @brief System information.
*/
class SystemInfo : public Activ::SystemInfo
{
public:
/**
* @brief Default constructor.
*/
ACTIV_FRAMEWORK_API
SystemInfo();
/**
* @brief Serialize this SystemInfo in non-versioned generic self-describing format.
*
* @param messageBuilder to serialize into.
*
* @return STATUS_CODE_SUCCESS or error code.
*/
ACTIV_FRAMEWORK_API
StatusCode Serialize2(MessageBuilder &messageBuilder) const;
/**
* @brief Serialize this SystemInfo in legacy versioned format.
*
* @param messageBuilder to serialize into.
*
* @return STATUS_CODE_SUCCESS or error code.
*/
ACTIV_FRAMEWORK_API
StatusCode SerializeVersioned(MessageBuilder &messageBuilder) const;
/**
* @brief Serialize this SystemInfo in legacy versioned format, to the version of the SystemInfo parameter.
*
* @param messageBuilder to serialize into.
* @param systemInfo containing the version to serialize to.
*
* @return STATUS_CODE_SUCCESS or error code.
*/
ACTIV_FRAMEWORK_API
StatusCode SerializeVersioned(MessageBuilder &messageBuilder, const SystemInfo &systemInfo) const;
/**
* @brief Deserialize SystemInfo in generic self-describing format.
*
* @param messageValidator to deserialize from.
*
* @return STATUS_CODE_SUCCESS or error code.
*/
ACTIV_FRAMEWORK_API
StatusCode Deserialize2(MessageValidator &messageValidator);
/**
* @brief Deserialize SystemInfo in legacy versioned format.
*
* @param messageValidator to deserialize from.
*
* @return STATUS_CODE_SUCCESS or error code.
*/
ACTIV_FRAMEWORK_API
StatusCode DeserializeVersioned(MessageValidator &messageValidator);
String m_systemName; ///< System name.
String m_systemVersion; ///< System version.
Settings::MemoryModel m_memoryModel; ///< Shared or private memory system (default shared).
DateTime m_utcStartupDateTime; ///< System startup time, utc.
size_t m_upTimeSeconds; ///< System uptime in seconds.
private:
/**
* @brief Serialize this SystemInfo to a specific legacy version.
*
* @param messageBuilder to serialize into.
* @param version containing the version to serialize to.
*
* @return STATUS_CODE_SUCCESS or error code.
*/
StatusCode SerializeVersioned(MessageBuilder &messageBuilder, const byte_t version) const;
static const byte_t currentVersion = 1; ///< Current version of serialized format.
byte_t m_version;
class Message;
};
/**
* @brief Process enumerator callback interface.
*/
class IProcessEnumerator
{
public:
/**
* @brief Destructor.
*/
virtual ~IProcessEnumerator() = 0;
/**
* @brief Callback on a process instance.
*
* @param pProcess pointer to an object providing an IProcess interface.
*
* @retval true to continue enumerating.
* @retval false to stop enumerating.
*/
virtual bool OnObject(IProcess * const pProcess) = 0;
};
/**
* @brief Endpoint enumerator callback interface.
*/
class IEndPointEnumerator
{
public:
/**
* @brief Destructor.
*/
virtual ~IEndPointEnumerator() = 0;
/**
* @brief Callback on an endpoint instance.
*
* @param pEndPoint pointer to an object providing an IAddressableEndPoint interface.
*
* @retval true to continue enumerating.
* @retval false to stop enumerating.
*/
virtual bool OnObject(IAddressableEndPoint * const pEndPoint) = 0;
};
/**
* @brief Heap enumerator callback interface.
*/
class IHeapEnumerator
{
public:
/**
* @brief Destructor.
*/
virtual ~IHeapEnumerator() = 0;
/**
* @brief Callback on a heap instance.
*
* @param pHeap pointer to an object providing an IHeap interface.
*
* @retval true to continue enumerating.
* @retval false to stop enumerating.
*/
virtual bool OnObject(IHeap * const pHeap) = 0;
};
/**
* @brief Destructor.
*/
virtual ~ISystem() = 0;
/**
* @brief Create a private, local memory endpoint.
*
* @param settings describing the endpoint to create.
*
* @return Pointer to an object providing an IEndPoint interface.
*
* @throw Exception
*/
virtual IEndPoint *CreatePrivateEndPoint(const IEndPoint::Settings &settings) = 0;
/**
* @brief Create a system endpoint.
*
* @param settings describing the endpoint to create.
*
* @return Pointer to an object providing an IAddressableEndPoint interface.
*
* @throw Exception
*/
virtual IAddressableEndPoint *CreateEndPoint(const IAddressableEndPoint::Settings &settings) = 0;
/**
* @brief Open a system endpoint by name.
*
* @param name the name of the endpoint which exists within the parent system namespace.
* @param timeout a Timeout object specifying how long to wait for the endpoint to exist.
*
* @return Pointer to an object providing an IAddressableEndPoint interface.
*
* @throw Exception
*/
virtual IAddressableEndPoint *OpenEndPoint(const String &name, Timeout &timeout = Timeout::GetInfinite()) = 0;
/**
* @brief Open a system endpoint by id.
*
* @param endPointId the system unique id of the endpoint to open.
* @param timeout a Timeout object specifying how long to wait for the endpoint to exist.
*
* @return Pointer to an object providing an IAddressableEndPoint interface.
*
* @throw Exception
*/
virtual IAddressableEndPoint *OpenEndPoint(EndPointId endPointId, Timeout &timeout = Timeout::GetInfinite()) = 0;
/**
* @brief Open the system endpoint.
*
* @return Pointer to an object providing an IAddressableEndPoint interface.
*
* @throw Exception
*/
virtual IAddressableEndPoint *OpenSystemEndPoint() = 0;
/**
* @brief Create a named memory heap.
*
* @param name the name of the heap which will exist within the parent system namespace.
* @param settings describing the layout of the heap.
*
* @return Pointer to an object providing an IHeap interface.
*
* @throw Exception
*/
virtual IHeap *CreateHeap(const String &name, const IHeap::Settings &settings) = 0;
/**
* @brief Open an existing named memory heap.
*
* @param name the name of the heap which exists within the parent system namespace.
* @param timeout a Timeout object specifying how long to wait for the heap to exist.
*
* @return Pointer to an object providing an IHeap interface.
*
* @throw Exception
*/
virtual IHeap *OpenHeap(const String &name, Timeout &timeout = Timeout::GetInfinite()) = 0;
/**
* @brief Open an existing named memory heap.
*
* @param heapId the system unique id of the heap to open.
* @param timeout a Timeout object specifying how long to wait for the heap to exist.
*
* @return Pointer to an object providing an IHeap interface.
*
* @throw Exception
*/
virtual IHeap *OpenHeap(const HeapId heapId, Timeout &timeout = Timeout::GetInfinite()) = 0;
/**
* @brief Open an existing process within the shared memory system.
*
* @param name the name of the process.
* @param timeout a Timeout object specifying how long to wait for the process to exist, in ms.
*
* @return An object providing an IProcess interface.
*
* @throw Exception.
*/
virtual IProcess *OpenProcess(const String &name, Timeout &timeout = Timeout::GetInfinite()) = 0;
/**
* @brief Open an existing process within the shared memory system.
*
* @param processId the id of the process within the system.
* @param timeout a Timeout object specifying how long to wait for the process to exist, in ms.
*
* @return An object providing an IProcess interface.
*
* @throw Exception.
*/
virtual IProcess *OpenProcess(const ProcessId processId, Timeout &timeout = Timeout::GetInfinite()) = 0;
/**
* @brief Get the name of the system.
*
* @return Reference to a string object containing the name of the system.
*/
virtual const String &GetSystemName() const = 0;
/**
* @brief Get the system heap.
*
* @return An object providing an IHeap interface.
*/
virtual IHeap *GetSystemHeap() const = 0;
/**
* @brief Get this process.
*
* @return An IProcess interface to this process.
*/
virtual IProcess *GetProcess() const = 0;
/**
* @brief Get system info.
*
* @return SystemInfo.
*
* @throw Exception.
*/
virtual SystemInfo GetSystemInfo() const = 0;
/**
* @brief Enumerate all opened processes.
*
* @param enumerator reference to an object providing an IProcessEnumerator interface to
* be called back on a process instance.
*/
virtual void EnumerateObjects(IProcessEnumerator &enumerator) = 0;
/**
* @brief Enumerate all opened endpoints.
*
* @param enumerator reference to an object providing an IEndPointEnumerator interface to
* be called back on an endpoint instance.
*/
virtual void EnumerateObjects(IEndPointEnumerator &enumerator) = 0;
/**
* @brief Enumerate all opened heaps.
*
* @param enumerator reference to an object providing an IHeapEnumerator interface to
* be called back on a process instance.
*/
virtual void EnumerateObjects(IHeapEnumerator &enumerator) = 0;
/**
* @brief Get the next processor id for setting a thread's affinity.
*
* The system maintains an atomic system-wide cyclic processor id that can be used for setting a thread's affinity.
* This function is mainly intended to be used by the ManagedEndPoint::Settings::m_shouldAllocateThreadAffinity setting
* and should be used with care beyond this.
*
* @return Processor id.
*/
virtual uint16_t GetNextAffinityProcessorId() const = 0;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline ISystem::~ISystem()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline ISystem::IProcessEnumerator::~IProcessEnumerator()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline ISystem::IEndPointEnumerator::~IEndPointEnumerator()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline ISystem::IHeapEnumerator::~IHeapEnumerator()
{
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_ISYSTEM_H)
@@ -1,97 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/KernelBypass/DpdkSettings.h
*
* @brief Header file for DpdkSettings class.
*/
#if (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_DPDK_SETTINGS_H)
#define ACTIV_FRAMEWORK_KERNEL_BYPASS_DPDK_SETTINGS_H
#include "ActivMiddleware/ActivFramework/External.h"
#if (!defined ACTIV_ENABLE_DPDK)
#error DPDK is not supported on this processor/platform/compiler.
#endif
#include "ActivMiddleware/ActivBase/IniFileParser.h"
#include "ActivMiddleware/ActivBase/ProcessorAffinity.h"
//! Activ namespace.
namespace Activ
{
//! KernelBypass namespace.
namespace KernelBypass
{
/**
* @brief Process wide settings for DPDK.
*
* To use DPDK in multiple threads these settings must be fully populated.
*
* To use DPDK in a single thread these settings do not need to be specified. Devices will be initialized as needed.
*/
class DpdkSettings
{
public:
//! Settings for a device.
class Device
{
public:
//! Default constructor.
ACTIV_FRAMEWORK_API Device();
/**
* @brief Read settings from an ini file section.
*
* @param sectionIterator iterator to an ini file section.
* @param isDefault whether the default section is being read.
*
* @throw Exception
*/
void Read(const IniFileParser::ConstSectionIterator &sectionIterator, const bool isDefault = false);
String m_deviceName; ///< Name of the device, e.g. eth1.
uint16_t m_rxDescriptorCount; ///< Number of rx descriptors.
uint32_t m_rxBufferCount; ///< Number of rx buffers for queuing.
uint32_t m_rxBufferCacheSize; ///< Size of the per core rx buffer cache.
uint32_t m_rxBufferSize; ///< Size of the rx buffers, zero for DPDK default.
uint16_t m_txDescriptorCount; ///< Number of tx descriptors.
uint32_t m_txBufferCount; ///< Number of tx buffers for queuing.
uint32_t m_txBufferCacheSize; ///< Size of the per core tx buffer cache.
uint32_t m_txBufferSize; ///< Size of the tx buffers, zero for DPDK default.
std::set<String> m_managedEndPointSet; ///< Set of ManagedEndPoint names that will use the device.
};
//! Type to map from device name to device settings.
using DeviceMap = std::map<String, Device>;
//! Default constructor.
ACTIV_FRAMEWORK_API DpdkSettings();
/**
* @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);
bool m_isEnabled; ///< Whether DPDK is configured to enable at initialization time.
String m_driverPath; ///< The path to the PMD drivers.
ProcessorAffinity m_controlThreadAffinity; ///< Affinity to apply to any DPDK control threads.
std::vector<String> m_optionList; ///< Additional options to pass to DPDK.
bool m_enableRxInterrupts; ///< Whether to enable RX interrupts.
bool m_enableStatsLog; ///< Whether to enable the per-process stats log.
uint32_t m_statsLogInterval; ///< Interval in ms between stats log entries.
uint32_t m_statsLogNumberOfBackups; ///< Number of stats log backups to keep.
Device m_defaultDeviceSettings; ///< Default settings for devices.
DeviceMap m_deviceMap; ///< Map of devices to configure at initialization time.
};
} // namespace KernelBypass
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_DPDK_SETTINGS_H)
@@ -1,227 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/KernelBypass/DpdkTransmitter.h
*
* @brief Header file for DpdkTransmitter class.
*/
#if (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_DPDK_TRANSMITTER_H)
#define ACTIV_FRAMEWORK_KERNEL_BYPASS_DPDK_TRANSMITTER_H
#include "ActivMiddleware/ActivFramework/External.h"
#if (!defined ACTIV_ENABLE_DPDK)
#error DPDK is not supported on this processor/platform/compiler.
#endif
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include <memory>
// Forward declare DPDK packet buffer.
struct rte_mbuf;
//! Activ namespace.
namespace Activ
{
class ManagedEndPoint;
//! KernelBypass namespace.
namespace KernelBypass
{
//! Class to transmit data over a DPDK interface.
class DpdkTransmitter
{
public:
class Impl;
//! Handle to a transmit packet.
class Packet
{
public:
//! Default constructor.
Packet();
// Deleted copy constructor.
Packet(const Packet &) = delete;
//! Move constructor.
Packet(Packet &&rhs);
//! Destructor.
~Packet();
//! Move assignment operator.
Packet &operator=(Packet &&rhs);
//! Release the object when the ownership of the underlying buffer has changed.
void Release();
//! Reset the object; the underlying buffer is returned.
void Reset();
//! Is the a packet attached?
operator bool() const;
//! Get the packet data, the a packet must be attached to use this method.
void *GetData() const;
private:
/**
* @brief Return an mbuf back to the pool.
*
* @param pImpl the transmitter impl that owns the pool.
* @param pMbuf the mbuf to return.
*/
ACTIV_FRAMEWORK_API static void FreeMbuf(Impl *pImpl, rte_mbuf *pMbuf);
//! The transmitter impl the packet belongs to, null means a packet is not attached.
Impl * m_pImpl;
rte_mbuf * m_pMbuf; ///< The mbuf pointer.
void * m_pBuffer; ///< Pointer to the payload of the packet.
friend class Impl;
};
//! Back pressure mode enumeration.
enum BackPressureMode
{
BACK_PRESSURE_MODE_SPIN, ///< Spin until space becomes available.
BACK_PRESSURE_MODE_RETURN ///< Return if sufficient space is not available.
};
/**
* @brief Constructor.
*
* @param managedEndPoint
* @param interfaceIndex
*
* @throw Exception
* @throw std::exception
*/
ACTIV_FRAMEWORK_API explicit DpdkTransmitter(ManagedEndPoint &managedEndPoint, const size_t interfaceIndex);
//! Destructor.
ACTIV_FRAMEWORK_API virtual ~DpdkTransmitter();
/**
* @brief Allocate a packet for transmission.
*
* An exception is thrown for a fatal condition where packets have been exhausted. This should never happen.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API Packet AllocatePacket();
/**
* @brief Transmit a raw Ethernet packet.
*
* @param packet
* @param length
* @param backPressureMode action to take if there is not enough space to write the packet.
*
* @throw Exception
* @throw std::exception
*
* @return whether the packet was written, always true if BACK_PRESSURE_MODE_SPIN is specified.
*/
ACTIV_FRAMEWORK_API bool TransmitPacket(Packet &packet, const uint16_t length,
const BackPressureMode backPressureMode = BACK_PRESSURE_MODE_SPIN);
//! Get the capacity of packets. User must ensure not to write more data into a packet than this.
uint16_t GetPacketCapacity() const;
private:
static const uint16_t MAX_PACKET_SIZE = 1522; ///< The maximum packet size.
std::unique_ptr<Impl> m_pImpl; ///< Private implementation.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint16_t DpdkTransmitter::GetPacketCapacity() const
{
return MAX_PACKET_SIZE;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline DpdkTransmitter::Packet::Packet() :
m_pImpl(nullptr)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline DpdkTransmitter::Packet::Packet(Packet &&rhs) :
m_pImpl(rhs.m_pImpl),
m_pMbuf(rhs.m_pMbuf),
m_pBuffer(rhs.m_pBuffer)
{
rhs.m_pImpl = nullptr;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline DpdkTransmitter::Packet::~Packet()
{
if (m_pImpl)
{
assert(m_pMbuf);
FreeMbuf(m_pImpl, m_pMbuf);
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline DpdkTransmitter::Packet &DpdkTransmitter::Packet::operator=(Packet &&rhs)
{
std::swap(m_pImpl, rhs.m_pImpl);
std::swap(m_pMbuf, rhs.m_pMbuf);
std::swap(m_pBuffer, rhs.m_pBuffer);
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void DpdkTransmitter::Packet::Release()
{
m_pImpl = nullptr;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void DpdkTransmitter::Packet::Reset()
{
if (m_pImpl)
{
assert(m_pMbuf);
FreeMbuf(m_pImpl, m_pMbuf);
m_pImpl = nullptr;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline DpdkTransmitter::Packet::operator bool() const
{
return bool(m_pImpl);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void *DpdkTransmitter::Packet::GetData() const
{
assert(m_pImpl && m_pMbuf && m_pBuffer);
return m_pBuffer;
}
} // namespace KernelBypass
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_DPDK_TRANSMITTER_H)
@@ -1,116 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/KernelBypass/EfviTransmitter.h
*
* @brief Header file for EfviTransmitter class.
*/
#if (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_EFVI_TRANSMITTER_H)
#define ACTIV_FRAMEWORK_KERNEL_BYPASS_EFVI_TRANSMITTER_H
#include "ActivMiddleware/ActivFramework/External.h"
#if (!defined ACTIV_ENABLE_EFVI)
#error ef_vi is not supported on this processor/platform/compiler.
#endif
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include "ActivMiddleware/CxxYZ/memory.h"
//! Activ namespace.
namespace Activ
{
class ManagedEndPoint;
//! KernelBypass namespace.
namespace KernelBypass
{
//! Class to transmit data over an ef_vi interface.
class EfviTransmitter
{
public:
class Impl;
//! Back pressure mode enumeration.
enum BackPressureMode
{
BACK_PRESSURE_MODE_SPIN, ///< Spin until space becomes available.
BACK_PRESSURE_MODE_RETURN ///< Return if sufficient space is not available.
};
/**
* @brief Constructor.
*
* @param managedEndPoint
* @param interfaceAddress
* @param isHardwareTimestampEnabled
*
* @throw Exception
* @throw std::exception
*/
ACTIV_FRAMEWORK_API explicit EfviTransmitter(ManagedEndPoint &managedEndPoint, const String &interfaceAddress,
const bool isHardwareTimestampEnabled = false);
//! Destructor.
ACTIV_FRAMEWORK_API virtual ~EfviTransmitter();
/**
* @brief Write a raw Ethernet packet.
*
* @param pData
* @param length
* @param backPressureMode action to take if there is not enough space to write the packet.
*
* @throw Exception
* @throw std::exception
*
* @return whether the packet was written, always true if BACK_PRESSURE_MODE_SPIN is specified.
*/
ACTIV_FRAMEWORK_API bool Write(const void * const pData, const size_t length,
const BackPressureMode backPressureMode = BACK_PRESSURE_MODE_SPIN);
//! Whether the transmitter is sending to a vlan.
bool IsTransmittingToVlan() const;
//! Get the id of the vlan being transmitted to.
uint16_t GetVlanId() const;
/**
* @brief Get hardware timestamp for the last Write() call.
*
* Note this method polls until the hardware timestamp is received (or the method timesout. This should only be called if
* hardware timestamping was enabled in the constructor.
*
* @param timestamp the hardware timestamp.
* @param timeoutPeriod how long to wait for the timestamp.
*
* @throw Exception
*/
void GetLastHardwareTimestamp(timespec &timestamp, const TimeoutPeriod timeoutPeriod = ACTIV_WAIT_INFINITE);
private:
CxxYZ::unique_ptr<Impl> m_pImpl;
bool m_isTransmittingToVlan;
uint16_t m_vlanId;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool EfviTransmitter::IsTransmittingToVlan() const
{
return m_isTransmittingToVlan;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint16_t EfviTransmitter::GetVlanId() const
{
return m_vlanId;
}
} // KernelBypass
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_EFVI_TRANSMITTER_H)
@@ -1,77 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/KernelBypass/EthernetReceiver.h
*
* @brief Header file for EthernetReceiver class.
*/
#if (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_ETHERNET_RECEIVER_H)
#define ACTIV_FRAMEWORK_KERNEL_BYPASS_ETHERNET_RECEIVER_H
#include "ActivMiddleware/ActivFramework/External.h"
#if (!defined ACTIV_ENABLE_EFVI)
#error ef_vi is not supported on this processor/platform/compiler.
#endif
#include "ActivMiddleware/ActivFramework/KernelBypass/Mode.h"
#include "ActivMiddleware/ActivFramework/KernelBypass/Statistics.h"
#include <functional>
#include <vector>
//! Activ namespace.
namespace Activ
{
class MacAddress;
class ManagedEndPoint;
//! KernelBypass namespace.
namespace KernelBypass
{
class EfviDistributor;
///! EthernetReceiver class.
class EthernetReceiver
{
public:
//! PacketInfo struct.
struct PacketInfo
{
bool m_hasTimestamp; ///< Indicates, if packet has m_timestamp filled.
size_t m_length; ///< The length.
timespec m_timestamp; ///< The UTC timestamp associated with a received packet.
};
//! Callback function type specification.
typedef std::function<void (const void * const, const PacketInfo &)> CallbackFunction;
/**
* @brief Constructor.
*
* @param managedEndPoint the managed end point to attach to.
* @param mode
* @param callbackFunction
* @param interfaceId id of the interface to open a virtual interface on.
* @param macAddressList
*
* @throw std::exception
*/
ACTIV_FRAMEWORK_API EthernetReceiver(ManagedEndPoint &managedEndPoint, const Mode mode,
const CallbackFunction &callbackFunction, const size_t interfaceId, const std::vector<MacAddress> &macAddressList);
ACTIV_FRAMEWORK_API ~EthernetReceiver();
//! Is time stamping enabled?
ACTIV_FRAMEWORK_API bool IsTimestampingEnabled() const;
private:
EfviDistributor * m_pDistributor;
};
} // namespace KernelBypass
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_ETHERNET_RECEIVER_H)
@@ -1,128 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/KernelBypass/Mode.h
*
* @brief Header file for kernel bypass mode constants and functions.
*/
#if (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_MODE_H)
#define ACTIV_FRAMEWORK_KERNEL_BYPASS_MODE_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/IniFileParser.h"
//! Activ namespace.
namespace Activ
{
class ManagedEndPoint;
//! KernelBypass namespace.
namespace KernelBypass
{
//! Mode.
enum Mode
{
MODE_NONE, ///< Use default TCP/IP stack.
MODE_AUTO, ///< Use ExaNIC/EFVI/DBL_API if available, else fallback to NONE.
MODE_AUTO_REQUIRED, ///< Use ExaNIC/EFVI/DBL_API if available, else fail. Note that if the application is onloaded it will be favored over ef_vi.
MODE_EFVI, ///< Explicitly use Solarflare EFVI.
MODE_DBL, ///< Explicitly use Myricom DBL.
MODE_EXANIC, ///< Explicitly use Exablaze ExaNIC.
MODE_DPDK, ///< Explicitly use DPDK.
// Not configurable but may be set during detection.
MODE_ONLOAD,
};
/**
* @brief Detect supported kernel bypass mode. AUTO and AUTO_REQUIRED will be resolved.
*
* @param interfaceAddress
* @param mode the requested mode.
*
* @retval The resolved kernel bypass mode to use.
*
* @throw Exception
* @throw std::exception
*/
ACTIV_FRAMEWORK_API
Mode DetectReceiveMode(const String &interfaceAddress, const Mode mode);
/**
* @brief Detect supported kernel bypass mode optimized using cached info from ManagedEndPoint.
*
* AUTO and AUTO_REQUIRED will be resolved.
*
* @param managedEndPoint
* @param interfaceAddress
* @param mode the requested mode.
*
* @retval The resolved kernel bypass mode to use.
*
* @throw Exception
* @throw std::exception
*/
ACTIV_FRAMEWORK_API
Mode DetectReceiveMode(ManagedEndPoint &managedEndPoint, const String &interfaceAddress, const Mode mode);
/**
* @brief Detect supported kernel bypass mode. AUTO and AUTO_REQUIRED will be resolved.
*
* @param managedEndPoint
* @param interfaceAddress
* @param mode the requested mode.
*
* @retval The resolved kernel bypass mode to use.
*
* @throw Exception
* @throw std::exception
*/
ACTIV_FRAMEWORK_API
Mode DetectTransmitMode(ManagedEndPoint &managedEndPoint, const String &interfaceAddress, const Mode mode);
/**
* @brief Read the kernel bypass mode from an ini file section iterator.
*
* @param sectionIterator
* @param mode the default Mode.
*
* @retval The kernel bypass mode.
*/
ACTIV_FRAMEWORK_API
Mode ReadSetting(const IniFileParser::ConstSectionIterator &sectionIterator, const Mode mode);
/**
* @brief Get string representation of kernel bypass mode.
*
* @param kernelBypassMode
*
* @return kernel bypass mode in string form.
*/
ACTIV_FRAMEWORK_API
String ModeToString(const Mode mode);
/**
* @brief Get kernel bypass mode from a string.
*
* @param string the string representation of kernel bypass mode.
*
* @return kernel bypass mode.
*/
ACTIV_FRAMEWORK_API
Mode StringToMode(const String &string);
/**
* @brief Whether to create a UdpReceiver for the mode.
*
* @param mode
*/
ACTIV_FRAMEWORK_API
bool ShouldCreateUdpReceiver(const Mode mode);
} // namespace KernelBypass
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_MODE_H)
@@ -1,87 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/KernelBypass/Statistics.h
*
* @brief Header file for Kernel Bypass statistics.
*/
#if (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_STATISTICS_H)
#define ACTIV_FRAMEWORK_KERNEL_BYPASS_STATISTICS_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/DateTime.h"
#include "ActivMiddleware/ActivFramework/KernelBypass/Mode.h"
#include "ActivMiddleware/CxxYZ/functional.h"
//! Activ namespace.
namespace Activ
{
//! KernelBypass namespace.
namespace KernelBypass
{
//! Statistics class.
class Statistics
{
public:
//! Constructor.
Statistics();
//! Clear all statistics.
void Reset();
size_t m_totalPackets; ///< Total number of packets received on this virtual interface.
size_t m_totalBytes; ///< Total number of bytes received on this virtual interface.
size_t m_udpPackets; ///< Number of IPV4 UDP packets received on this virtual interface.
size_t m_udpBytes; ///< Number of IPV4 UDP bytes received on this virtual interface.
size_t m_filteredPackets; ///< Number of packets received matching a filter on this virtual interface.
size_t m_filteredBytes; ///< Number of bytes received matching a filter on this virtual interface.
size_t m_processingErrors; ///< Number of network stack processing errors on this virtual interface.
size_t m_peakQueuedPackets; ///< Peak number of queued packets since reset.
DateTime m_peakQueuedPacketsDateTime; ///< The date and time that the peak queued packets occurred.
uint32_t m_processEventLoops; ///< Process event loop counter.
//! Number of fragmented packets received on this virtual interface. NOTE: fragmented packets are not currently supported.
size_t m_fragmentedPackets;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline Statistics::Statistics()
{
Reset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Statistics::Reset()
{
m_totalPackets = 0;
m_totalBytes = 0;
m_udpPackets = 0;
m_udpBytes = 0;
m_filteredPackets = 0;
m_filteredBytes = 0;
m_processingErrors = 0;
m_peakQueuedPackets = 0;
m_peakQueuedPacketsDateTime.Reset();
m_fragmentedPackets = 0;
m_processEventLoops = 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Statistics callback function definition.
typedef CxxYZ::function<void(const Mode, const String &, const Statistics &, const uint64_t)> StatisticsLogCallback;
} // namespace KernelBypass
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_STATISTICS_H)
@@ -1,116 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/KernelBypass/UdpReceiver.h
*
* @brief Header file for the base kernel bypass UdpReceiver class.
*/
#if (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_UDP_RECEIVER_H)
#define ACTIV_FRAMEWORK_KERNEL_BYPASS_UDP_RECEIVER_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/Ip/UdpDatagramInfo.h"
#include "ActivMiddleware/ActivFramework/KernelBypass/Mode.h"
#include "ActivMiddleware/ActivFramework/KernelBypass/Statistics.h"
#include "ActivMiddleware/CxxYZ/memory.h"
//! Activ namespace.
namespace Activ
{
// Forwards declarations.
class ManagedEndPoint;
//! KernelBypass namespace.
namespace KernelBypass
{
class Distributor;
class HardwareFilter;
class UdpFilter;
//! Class to receive data destined for a single UDP address/port.
class UdpReceiver
{
public:
//! OnDatagram callback function definition.
typedef UdpDatagramCallbackFunction CallbackFunction;
/**
* @brief Construct a kernel bypass UDP receiver. The receiver will be initially disabled.
*
* @param managedEndPoint
* @param mode
* @param callbackFunction
* @param interfaceAddress
* @param destinationAddress
* @param destinationPort
*
* @retval Pointer to a UdpReceiver if required for the mode.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API UdpReceiver(ManagedEndPoint &managedEndPoint, const Mode mode,
const CallbackFunction &callbackFunction, const String &interfaceAddress, const String &destinationAddress,
const uint16_t destinationPort);
//! Destructor.
ACTIV_FRAMEWORK_API ~UdpReceiver();
//! Enable the receiver.
ACTIV_FRAMEWORK_API void Enable();
//! Disable the receiver.
ACTIV_FRAMEWORK_API void Disable();
//! Is timestamping enabled?
ACTIV_FRAMEWORK_API bool IsTimestampingEnabled() const;
const UdpDatagramCallbackFunction &GetCallbackFunction() const;
/**
* @brief Enable logging per interface.
*
* This setting only takes effect when applied before any Receivers have been instantiated.
*
* @param managedEndPoint
* @param isEnabled whether to enable interface logging.
*/
ACTIV_FRAMEWORK_API static void SetInterfaceLoggingEnabled(ManagedEndPoint &managedEndPoint, const bool isEnabled);
/**
* @brief Set a callback function to be invoked when the statistics have been logged.
*
* A callback will be received for each interface.
*
* @param managedEndPoint
* @param callbackFunction a CxxYZ::function wrapping the callback. The parameters it receives are the interface name,
* the statistics and a uint64_t containing the buffer peak packet size since the last callback for that interface.
*/
ACTIV_FRAMEWORK_API
static void SetOnStatisticsLogCallback(ManagedEndPoint &managedEndPoint, const StatisticsLogCallback &callbackFunction);
private:
template <typename T>
void Initialize(ManagedEndPoint &managedEndPoint, const UdpFilter &udpFilter);
Distributor * m_pDistributor;
UdpDatagramCallbackFunction m_callbackFunction;
int m_interfaceId;
String m_interfaceName;
bool m_isEnabled; ///< Whether this receiver is enabled.
CxxYZ::unique_ptr<HardwareFilter> m_pHardwareFilter;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline const UdpDatagramCallbackFunction &UdpReceiver::GetCallbackFunction() const
{
return m_callbackFunction;
}
} // namespace KernelBypass
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_KERNEL_BYPASS_UDP_RECEIVER_H)
@@ -1,953 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/LatencyProfiler.h
*
* @brief Header file for the latency profiler class.
*/
#if (!defined ACTIV_FRAMEWORK_LATENCY_PROFILER_H)
#define ACTIV_FRAMEWORK_LATENCY_PROFILER_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/IniFileParser.h"
#include "ActivMiddleware/ActivFramework/Timer.h"
#include "ActivMiddleware/ActivFramework/ManagedEndPoint.h"
#include "ActivMiddleware/CxxYZ/array.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#include "ActivMiddleware/CxxYZ/map.h"
#include "ActivMiddleware/CxxYZ/unordered_map.h"
#include "ActivMiddleware/CxxYZ/vector.h"
//! Activ namespace.
namespace Activ
{
class Component;
class UiIo;
//! Latency profiler.
class LatencyProfiler
{
public:
//! Percentile update state.
enum PercentileUpdateState
{
PERCENTILE_UPDATE_STATE_DISABLED,
PERCENTILE_UPDATE_STATE_ENABLED,
PERCENTILE_UPDATE_STATE_LOGGING
};
//! Settings class.
class Settings
{
public:
/**
* @brief Bucket info.
*
* Describes the specification of the buckets for some range of values:
* - the interval size of the increments stored as an exponent of power-2 (m_granularityExponent).
* - the index offset in the buckets frequency list (m_baseOffset).
*/
class BucketInfo
{
public:
//! Default constructor.
ACTIV_FRAMEWORK_API BucketInfo();
uint32_t m_granularityExponent; ///< The granularity exponent.
uint32_t m_baseOffset; ///< The base offset.
};
ACTIV_BOOST_STATIC_CONSTEXPR size_t BUCKET_INFO_MAX_EXPONENT_INDEX = 32;
typedef CxxYZ::array<BucketInfo, BUCKET_INFO_MAX_EXPONENT_INDEX + 1> BucketInfoList; ///< The bucket info list.
typedef CxxYZ::vector<double> PercentileList; ///< The percentile list.
/**
* @brief Create bucket info list helper.
*
* The bucket info list details the specification of evaluating the correct index of the histogram
* frequency buckets from a latency value (in nanoseconds).
*
* Each BucketInfo deals with a range of values explicitly defined in powers of two:
*
* BucketInfoList[0]: covers only latency=0
* BucketInfoList[1]: 2^(0) <= latency < 2^(1)
* BucketInfoList[2]: 2^(1) <= latency < 2^(2)
* ...
* BucketInfoList[x]: 2^(x-1) <= latency < 2^(x)
* ...
* BucketInfoList[32]: 2^(31) <= latency < 2^(32)
*
* A single BucketInfo tells us the offset start position (m_baseOffset) and the power-2 exponent
* of the granularity (m_granularityExponent) which determines the granularity of the bucket info range.
*
* From the above, we see the latency values covered in the bucket info list is 0 to UINT32_MAX (~4.29 seconds).
*
* Default bucket info list (when calling GetDefault())
*
* Note: x is power-2 exponent.
*
* Range (x=exponent) Increment (x=Exponent) Buckets Index offset
* 0<=x<1 (1.00 ns to 2.00 ns) x=8 (256.00 ns) 1 0
* 1<=x<2 (2.00 ns to 4.00 ns) x=8 (256.00 ns) 1 0
* 2<=x<3 (4.00 ns to 8.00 ns) x=8 (256.00 ns) 1 0
* 3<=x<4 (8.00 ns to 16.00 ns ... 1 0
* 4<=x<5 (16.00 ns to 32.00 ns) 1 0
* 5<=x<6 (32.00 ns to 64.00 ns) 1 0
* 6<=x<7 (64.00 ns to 128.00 ns) 1 0
* 7<=x<8 (128.00 ns to 256.00 ns) 1 0
* 8<=x<9 (256.00 ns to 512.00 ns) 1 1
* 9<=x<10 (512.00 ns to 1024.00 ns) 2 2
* 10<=x<11 (1024.00 ns to 2.05 us) 4 4
* 11<=x<12 (2.05 us to 4.10 us) 8 8
* 12<=x<13 (4.10 us to 8.19 us) 16 16
* 13<=x<14 (8.19 us to 16.38 us) 32 32
* 14<=x<15 (16.38 us to 32.77 us) 64 64
* 15<=x<16 (32.77 us to 65.54 us) x=10 (1024.00 ns) 32 128
* 16<=x<17 (65.54 us to 131.07 us) ... (1024.00 ns) 64 160
* 17<=x<18 (131.07 us to 262.14 us) (1024.00 ns) 128 224
* 18<=x<19 (262.14 us to 524.29 us) (1024.00 ns) 256 352
* 19<=x<20 (524.29 us to 1048.58 us) x=12 (4.10 us) 128 608
* 20<=x<21 (1048.58 us to 2.10 ms) ... (4.10 us) 256 736
* 21<=x<22 (2.10 ms to 4.19 ms) (4.10 us) 512 992
* 22<=x<23 (4.19 ms to 8.39 ms) (4.10 us) 1024 1504
* 23<=x<24 (8.39 ms to 16.78 ms) x=13 (8.19 us) 1024 2528
* 24<=x<25 (16.78 ms to 33.55 ms) (8.19 us) 2048 3552
* 25<=x<26 (33.55 ms to 67.11 ms) x=16 (65.54 us) 512 5600
* 26<=x<27 (67.11 ms to 134.22 ms) x=17 (131.07 us) 512 6112
* 27<=x<28 (134.22 ms to 268.44 ms) x=18 (262.14 us) 512 6624
* 28<=x<29 (268.44 ms to 536.87 ms) x=19 (524.29 us) 512 7136
* 29<=x<30 (536.87 ms to 1073.74 ms) x=20 (1048.58 us) 512 7648
* 30<=x<31 (1073.74 ms to 2147.48 ms) x=21 (2.10 ms) 512 8160
* 31<=x<32 (2147.48 ms to 4294.97 ms) x=22 (4.19 ms) 512 8672
*
* Total buckets = 9184
*/
class CreateBucketInfoListHelper
{
public:
//! Bucket specification
class BucketSpecification
{
public:
/**
* @brief Constructor.
*
* @param exponentMin the exponent min.
* @param exponentMax the exponent max.
* @param exponentIncrement the exponent increment.
*/
BucketSpecification(const uint32_t exponentMin, const uint32_t exponentMax, const uint32_t exponentIncrement) :
m_power2ExponentMin(exponentMin),
m_power2ExponentMax(exponentMax),
m_power2ExponentIncrement(exponentIncrement)
{
}
uint32_t m_power2ExponentMin;
uint32_t m_power2ExponentMax;
uint32_t m_power2ExponentIncrement;
};
typedef CxxYZ::vector<BucketSpecification> BucketSpecificationList; ///< The bucket specification list type.
typedef LatencyProfiler::Settings::BucketInfoList BucketInfoList; ///< The bucket info list type.
/**
* @brief Get.
*
* Get the bucket info list from an environment variable (string). If the environment variable does not exist,
* the default value will be returned instead.
*
* Format:
*
* "<exponent-max1>=<exponent-incr1>,<exponent-max2>=<exponent-incr2>,..."
*
* Explanation:
*
* "Everything upto 2^(max1) has bucket increment granularity of 2^(incr1)"
* "Everything between 2^(max1) and 2^(max2) has bucket increment granularity of 2^(incr2)"
* ...
*
* Example:
*
* "15=8,19=10,23=12,25=13,26=16,27=17,28=18,29=19,30=20,31=21,32=22"
*
* @param oBucketInfoString the optional bucket info list string.
* @param defaultBucketInfoList the default bucket info list.
*
* @throw Exception.
*
* @return the bucket info list
*/
ACTIV_FRAMEWORK_API static BucketInfoList Get(const Boost::optional<String> &oBucketInfoString,
const BucketInfoList &defaultBucketInfoList = GetDefault());
/**
* @brief Get the default bucket info list.
*
* 0 < range-exponent <= 15, increment-exponent=8
* 15 < range-exponent <= 19, increment-exponent=10
* 19 < range-exponent <= 23, increment-exponent=12
* 23 < range-exponent <= 25, increment-exponent=13
* 25 < range-exponent <= 26, increment-exponent=16
* 26 < range-exponent <= 27, increment-exponent=17
* 27 < range-exponent <= 28, increment-exponent=18
* 28 < range-exponent <= 29, increment-exponent=19
* 29 < range-exponent <= 30, increment-exponent=20
* 30 < range-exponent <= 31, increment-exponent=21
* 31 < range-exponent <= 32, increment-exponent=22
*/
ACTIV_FRAMEWORK_API static BucketInfoList GetDefault();
/**
* @brief Parse.
*
* Parse the bucket info list from an ini file section iterator.
*
* Format:
*
* [LatencyProfiler:HistogramBuckets]
* <exponent-max1> = <exponent-incr1>
("Everything upto 2^(max1) has bucket increment granularity of 2^(incr1)).
* <exponent-max2> = <exponent-incr2>
* ("Everything between 2^(max1) and 2^(max2) has bucket increment granularity of 2^(incr2)).
* ...
*
* Example:
*
* [LatencyProfiler:HistogramBuckets]
* 15 = 8
* 19 = 10
* 23 = 12
* 25 = 13
* 26 = 16
* 27 = 17
* 28 = 18
* 29 = 19
* 30 = 20
* 31 = 21
* 32 = 22
*
* @param sectionIterator the section iterator.
* @param bucketInfoList the bucket info list.
*
* @throw Exception
*/
static void Parse(const IniFileParser::ConstSectionIterator &sectionIterator, BucketInfoList &bucketInfoList);
/**
* @brief Create.
*
* A supplementary function, called through from Get, GetDefault and Parse.
*
* @param bucketInfoList the bucket info list.
* @param bucketSpecificationList the bucket specification.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_OUT_OF_RANGE
*/
ACTIV_FRAMEWORK_API static StatusCode Create(BucketInfoList &bucketInfoList,
const BucketSpecificationList &bucketSpecificationList);
private:
/**
* @brief Internal add bucket info layer.
*
* The range of latency values is determined by the power 2 exponent, which takes a start power-2
* exponent (inclusive) and an end power-2 exponent (exclusive). The increment size power-2 exponent
* determines the granularity of the range, which each bucket entry covers.
*
* @param bucketInfoList the bucket info list.
* @param bucketSpecification the bucket specification.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_OUT_OF_RANGE
*/
static StatusCode InternalAddBucketInfoLayer(BucketInfoList &bucketInfoList,
const BucketSpecification &bucketSpecification);
};
//! 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);
//! Copy constructor.
ACTIV_FRAMEWORK_API Settings(const Settings &rhs);
//! Copy assignment operator.
ACTIV_FRAMEWORK_API Settings &operator=(const Settings &rhs);
//! Is enabled.
bool IsEnabled() const;
//! Is percentile log enabled.
bool IsPercentileLogEnabled() const;
//! Get total number of histogram buckets.
size_t GetTotalNumberOfHistogramBuckets() const;
String m_logDirectory; ///< Default: 'latency'. The subdirectory to place log files in.
uint32_t m_logInterval; ///< Default: 1000ms. The log interval (ms).
uint32_t m_percentileLogInterval; ///< Default: 0 (disabled). The percentile log interval (ms).
uint32_t m_logNumberOfBackups; ///< Default: 14. The log number of backups.
uint64_t m_sampleFrequency; ///< Default: 0 (disabled). The sample frequency.
uint64_t m_sampleInterval; ///< Default: 5000. The sample interval (ms), forces an update when sampled message rates are low.
/**
* @brief Range of offset in ms to add to timer. A random offset within the range is chosen.
*
* If there is only one value then this is used as the offset.
*/
std::vector<int32_t> m_percentileLogTimerOffsetRange;
PercentileList m_percentileList; ///< The percentile list.
BucketInfoList m_bucketInfoList; ///< The bucket info list.
String m_additionalColumnName; ///< The optional name of an additional column in the log file.
};
// Latency statistics.
class Statistics
{
public:
//! Constructor.
Statistics();
//! Reset().
void Reset();
//! Update with latest measurement.
void Update(const int64_t latency);
//! Addition operator
Statistics &operator+=(const Statistics &rhs);
int64_t m_min; ///< The min latency value (nS).
int64_t m_max; ///< The max latency value (nS).
uint64_t m_count; ///< The latency count.
int64_t m_sum; ///< The (total latency) sum.
uint64_t m_negative; ///< The negative (count).
};
typedef CxxYZ::vector<uint64_t> HistogramFrequencies; ///< The histogram frequencies type.
class HistogramStatistics
{
public:
//Default Constructor
HistogramStatistics();
//! Constructor.
HistogramStatistics(const size_t histogramFrequenciesSize);
//! Update with latency.
void Update(const Settings::BucketInfoList &bucketInfoList, const uint64_t latency);
//! Is histogram frequencies initialized?
bool IsInitialized() const;
//! Initialize histogram frequencies.
void Initialize(const size_t histogramFrequenciesSize);
/**
* @brief Combine with @a rhs.
*
* Note this will clear the contents of @a rhs.
*
* @param rhs the statistics to combine with and clear.
*/
void Combine(HistogramStatistics &rhs);
size_t m_peakIndex; ///< The histogram frequency peak index.
size_t m_oversized; ///< The number of oversized histogram frequency updates.
HistogramFrequencies m_frequencies; ///< The histogram frequency list.
};
//! Percentile calculator.
class PercentileCalculator
{
public:
typedef CxxYZ::unique_ptr<PercentileCalculator> Ptr; ///< The percentile calculator pointer type.
typedef CxxYZ::map<uint16_t, HistogramStatistics> HistogramStatisticsMap; ///< The index to histogram statistics map type.
typedef CxxYZ::unordered_map<uint16_t, String> HistogramEntryNamesMap; ///< The index to histogram entry name map type.
ACTIV_FRAMEWORK_API static const uint16_t DEFAULT_HISTOGRAM_INDEX;
struct Statistics
{
HistogramFrequencies m_percentileResultsList;
uint64_t m_numberOfPercentileUpdates;
uint64_t m_numberOfOversizedUpdates;
double m_percentageBucketPeak;
};
typedef CxxYZ::function<void (const Settings::PercentileList &percentileList, const DateTime &dateTime,
const String &histogramName, const Statistics &statistics)> LogCallback;
/**
* @brief Constructor.
*
* @param name for the uniquely identifying the log file.
* @param component the component.
* @param settings the settings.
* @param isUsingInternalTimer is the logging driven by the internal timer?
* @param logCallback callback on log entry.
* @param indexToEntryNameMap map from entry indexes to entry names.
*/
ACTIV_FRAMEWORK_API PercentileCalculator(const String &name, Component &component, const Settings &settings,
const bool isUsingInternalTimer = true, const LogCallback &logCallback = LogCallback(),
const HistogramEntryNamesMap &indexToEntryNameMap = HistogramEntryNamesMap());
//! Destructor.
ACTIV_FRAMEWORK_API ~PercentileCalculator();
//! Update with a latency.
void Update(const uint64_t latency);
/**
* @brief Combine histogram stats with another histogram.
*
* Note this will clear the contents of @a rhs.
* This should not be used while the percentile calculator is being updated.
*
* @param rhs the statistics to combine with and clear.
* @param histogramindex the index of the histogram to combine with (empty for default).
*/
void CombineHistogram(HistogramStatistics &rhs, const uint16_t histogramindex = DEFAULT_HISTOGRAM_INDEX);
//! Start one round of logging.
ACTIV_FRAMEWORK_API void StartLogging();
//! Get state.
PercentileUpdateState GetState() const;
private:
//! On task.
bool OnTask();
//! On reset task.
bool OnResetTask();
//! On percentile log.
bool OnPercentileLog();
void InitializeLogging(HistogramStatistics &histogramStatistics);
const String m_name;
Component & m_component;
HistogramStatisticsMap m_histogramStatistics; ///< The statistics to work out the percentiles for.
HistogramStatistics & m_defaultHistogramStatistics; ///< Reference to the default histogram statistics.
HistogramFrequencies m_bufferedLatencyHistogramUpdates; ///< The buffered latency histogram updates.
const Settings::PercentileList & m_percentileList; ///< The percentile list.
const Settings::BucketInfoList & m_bucketInfoList; ///< The bucket info list.
const String & m_additionalColumnName; ///< The optional additional column name for the log file.
const LogCallback m_logCallback;
const HistogramEntryNamesMap m_entryIndexToNameMap;
PercentileUpdateState m_updateState;
ManagedEndPoint::ScopedPostEndPointProcessingTask
m_percentileCalculatorTask; ///< The background percentile calculator task.
size_t m_indexPositionDuringTask; ///< The index position during task.
DateTime m_cachedLocalDateTime; ///< The cached local date time.
Statistics m_cachedStatistics; ///< The cached statistics;
uint64_t m_numberOfBufferedUpdates; ///< The number of buffered updates.
HistogramStatisticsMap::iterator m_histogramStatisticsIterator; ///< The histogram statistics map iterator.
HistogramFrequencies::const_iterator m_histogramPivotIterator; ///< The histogram pivot iterator.
Settings::PercentileList::const_iterator
m_percentileListIterator; ///< The percentile list iterator.
const CxxYZ::vector<uint32_t> m_latencyAtBucketEntryList; ///< The latency index.
ScopedAddress m_logAddress; ///< The system latency log address.
Timer m_logTimer; ///< The log timer.
};
/**
* @brief Consrtructor.
*
* @param component the component.
* @param settings the settings.
* @param name the name.
*/
ACTIV_FRAMEWORK_API LatencyProfiler(Component &component, const Settings &settings, const String &name);
//! Destructor.
ACTIV_FRAMEWORK_API ~LatencyProfiler();
/**
* @brief Should update.
*
* m_sampleCounter is incremented by 1, and returns whether it exceeded the frequency
* threshold defined by Settings::m_sampleFrequency.
*
* @return Boolean.
*/
bool ShouldUpdate();
/**
* @brief Update.
*
* If sample frequency is required, ShouldUpdate(...) should be called before using this function.
*
* @param startTimespec the start timespec
*/
void Update(const timespec &startTimespec);
/**
* @brief Update.
*
* If sample frequency is required, ShouldUpdate(...) should be called before using this function.
*
* @param startTimespec the start timespec.
* @param endTimespec the end timespec.
*/
void Update(const timespec &startTimespec, const timespec &endTimespec);
/**
* @brief Update.
*
* If sample frequency is required, ShouldUpdate(...) should be called before using this function.
*
* @param startTimestamp the start timestamp in nanoseconds.
*/
void Update(const int64_t startTimestamp);
/**
* @brief Update with latency.
*
* The latency difference is already assumed to be pre-calculated.
* If sample frequency is required, ShouldUpdate(...) should be called before using this function.
*
* @param latency the latency in nanoseconds.
*/
void UpdateWithLatency(const int64_t latency);
/**
* @brief Possibly update.
*
* Internally calls ShouldUpdate(), and updates latency statistics if true.
*
* @param startTimespec the start timespec.
*/
void PossiblyUpdate(const timespec &startTimespec);
/**
* @brief Possibly update.
*
* Internally calls ShouldUpdate(), and updates latency statistics if true.
*
* @param startTimespec the start timespec.
* @param endTimespec the end timespec.
*/
void PossiblyUpdate(const timespec &startTimespec, const timespec &endTimespec);
/**
* @brief Possibly update.
*
* Internally calls ShouldUpdate(), and updates latency statistics if true.
*
* @param startTimestamp the start timestamp in nanoseconds.
*/
void PossiblyUpdate(const int64_t startTimestamp);
/**
* @brief Possibly update with latency.
*
* Internally calls ShouldUpdate(), and updates latency statistics if true.
*
* @param latency the latency in nanoseconds.
*/
void PossiblyUpdateWithLatency(const int64_t latency);
//! Get percentile update state,
PercentileUpdateState GetPercentileUpdateState() const;
//! Get name.
const String &GetName() const;
//! Display settings.
ACTIV_FRAMEWORK_API void UiDisplaySettings(const UiIo &uiIo) const;
private:
static const size_t PERCENTILE_ACCUMULATOR_INCREMENT = 256;
static const size_t PERCENTILE_CLEARDOWN_INCREMENT = 1024;
static const size_t PERCENTILE_ADD_BUFFERED_UPDATES_INCREMENT = 32;
//! Clear.
void Clear();
//! Process log timer.
void ProcessLogTimer();
//! Process sample interval timer.
void ProcessSampleIntervalTimer();
/**
* @brief Internal update.
*
* @param latency the latency.
*/
void InternalUpdate(const int64_t latency);
const Settings m_settings; ///< The settings.
const String m_name; ///< The name.
uint64_t m_sampleCounter; ///< The sample counter.
Statistics m_statistics;
Component & m_component; ///< The component.
ScopedAddress m_logAddress; ///< The system latency log address.
PercentileCalculator::Ptr m_pPercentileCalculator; ///< The percentile calculator component pointer.
Timer m_logTimer; ///< The log timer.
Timer m_sampleIntervalTimer; ///< The sample interval timer pointer.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool LatencyProfiler::Settings::IsEnabled() const
{
return (0 != m_sampleFrequency);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool LatencyProfiler::Settings::IsPercentileLogEnabled() const
{
return IsEnabled() && (0 != m_percentileLogInterval);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t LatencyProfiler::Settings::GetTotalNumberOfHistogramBuckets() const
{
return static_cast<size_t>(((UINT64_C(1) + UINT32_MAX) >> (m_bucketInfoList.back().m_granularityExponent + UINT64_C(1))) +
m_bucketInfoList.rbegin()->m_baseOffset) + 1;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool LatencyProfiler::ShouldUpdate()
{
if (m_sampleCounter >= m_settings.m_sampleFrequency)
{
m_sampleCounter = 1;
return true;
}
++m_sampleCounter;
return false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::Update(const timespec &startTimespec)
{
timespec nowTimespec;
(void) timespec_get(&nowTimespec, TIME_UTC);
Update(startTimespec, nowTimespec);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::Update(const timespec &startTimespec, const timespec &endTimespec)
{
const int64_t latency = (endTimespec.tv_sec - startTimespec.tv_sec) * 1000000000 +
(static_cast<int64_t>(endTimespec.tv_nsec) - startTimespec.tv_nsec);
InternalUpdate(latency);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::Update(const int64_t startTimestamp)
{
timespec nowTimespec;
(void) timespec_get(&nowTimespec, TIME_UTC);
const int64_t latency = ((static_cast<int64_t>(nowTimespec.tv_sec) * 1000000000)
+ nowTimespec.tv_nsec) - startTimestamp;
InternalUpdate(latency);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::UpdateWithLatency(const int64_t latency)
{
InternalUpdate(latency);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::PossiblyUpdate(const timespec &startTimespec)
{
if (ShouldUpdate())
Update(startTimespec);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::PossiblyUpdate(const timespec &startTimespec, const timespec &endTimespec)
{
if (ShouldUpdate())
Update(startTimespec, endTimespec);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::PossiblyUpdate(const int64_t startTimestamp)
{
if (ShouldUpdate())
Update(startTimestamp);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::PossiblyUpdateWithLatency(const int64_t latency)
{
if (ShouldUpdate())
UpdateWithLatency(latency);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline LatencyProfiler::PercentileUpdateState LatencyProfiler::GetPercentileUpdateState() const
{
return (m_pPercentileCalculator ? m_pPercentileCalculator->GetState() : PERCENTILE_UPDATE_STATE_DISABLED);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &LatencyProfiler::GetName() const
{
return m_name;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::Clear()
{
m_statistics.Reset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::ProcessSampleIntervalTimer()
{
m_sampleCounter = m_settings.m_sampleFrequency;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::InternalUpdate(const int64_t latency)
{
m_statistics.Update(latency);
if (m_pPercentileCalculator)
{
if (ACTIV_LIKELY(latency >= 0))
m_pPercentileCalculator->Update(static_cast<uint64_t>(latency));
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline LatencyProfiler::Statistics::Statistics() :
m_min(Boost::integer_traits<int64_t>::const_max),
m_max(Boost::integer_traits<int64_t>::const_min),
m_count(0),
m_sum(0),
m_negative(0)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::Statistics::Reset()
{
m_min = Boost::integer_traits<int64_t>::const_max;
m_max = Boost::integer_traits<int64_t>::const_min;
m_count = 0;
m_sum = 0;
m_negative = 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::Statistics::Update(const int64_t latency)
{
if (ACTIV_UNLIKELY(latency < m_min))
m_min = latency;
if (ACTIV_UNLIKELY(latency > m_max))
m_max = latency;
m_sum += latency;
++m_count;
// TODO: Should negative count to the other stats too?
if (ACTIV_UNLIKELY(latency < 0))
++m_negative;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline LatencyProfiler::Statistics &LatencyProfiler::Statistics::operator+=(const Statistics &rhs)
{
if (m_min > rhs.m_min)
m_min = rhs.m_min;
if (m_max < rhs.m_max)
m_max = rhs.m_max;
m_count += rhs.m_count;
m_sum += rhs.m_sum;
m_negative += rhs.m_negative;
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline LatencyProfiler::HistogramStatistics::HistogramStatistics() :
m_peakIndex(0),
m_oversized(0)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline LatencyProfiler::HistogramStatistics::HistogramStatistics(const size_t histogramFrequenciesSize) :
m_peakIndex(0),
m_oversized(0),
m_frequencies(histogramFrequenciesSize)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::HistogramStatistics::Update(const Settings::BucketInfoList &bucketInfoList, const uint64_t latency)
{
if (ACTIV_LIKELY(latency <= UINT32_MAX))
{
const size_t highestBitPos = HighestBitPosition<uint32_t>()(static_cast<uint32_t>(latency));
const Settings::BucketInfo &bucketInfo = bucketInfoList[highestBitPos];
const uint64_t latencyWithHighestBitCleared = (latency & ~(UINT64_C(1) << (highestBitPos - 1)));
const size_t latencyBucketOffset = static_cast<size_t>(latencyWithHighestBitCleared >> bucketInfo.m_granularityExponent);
const size_t frequencyIndex = bucketInfo.m_baseOffset + latencyBucketOffset;
++m_frequencies[frequencyIndex];
if (ACTIV_UNLIKELY(m_peakIndex < frequencyIndex))
m_peakIndex = frequencyIndex;
}
else
{
++m_oversized;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool LatencyProfiler::HistogramStatistics::IsInitialized() const
{
return m_frequencies.size() > 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::HistogramStatistics::Initialize(const size_t histogramFrequenciesSize)
{
assert(!IsInitialized());
m_frequencies.resize(histogramFrequenciesSize);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::HistogramStatistics::Combine(HistogramStatistics &rhs)
{
if (m_peakIndex < rhs.m_peakIndex)
m_peakIndex = rhs.m_peakIndex;
m_oversized += rhs.m_oversized;
if (ACTIV_UNLIKELY(m_peakIndex >= m_frequencies.size()))
m_frequencies.resize(m_peakIndex + 1);
for (size_t i = 0, endI = std::min(m_peakIndex, rhs.m_peakIndex); i <= endI; ++i)
{
m_frequencies[i] += rhs.m_frequencies[i];
rhs.m_frequencies[i] = 0;
}
rhs.m_peakIndex = 0;
rhs.m_oversized = 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::PercentileCalculator::Update(const uint64_t latency)
{
switch (m_updateState)
{
case PERCENTILE_UPDATE_STATE_ENABLED:
m_defaultHistogramStatistics.Update(m_bucketInfoList, latency);
break;
case PERCENTILE_UPDATE_STATE_LOGGING:
// Cache latencies when it is currently logging in the background.
m_bufferedLatencyHistogramUpdates.push_back(latency);
break;
default:
assert(false);
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void LatencyProfiler::PercentileCalculator::CombineHistogram(HistogramStatistics &rhs, const uint16_t histogramIndex)
{
HistogramStatisticsMap::iterator iter = m_histogramStatistics.find(histogramIndex);
if (ACTIV_UNLIKELY(m_histogramStatistics.end() == iter))
{
// Default histogram will always exist so just use its size for the histogram stats parameter.
iter = m_histogramStatistics.emplace(histogramIndex,
HistogramStatistics(m_histogramStatistics[DEFAULT_HISTOGRAM_INDEX].m_frequencies.size())).first;
}
iter->second.Combine(rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline LatencyProfiler::PercentileUpdateState LatencyProfiler::PercentileCalculator::GetState() const
{
return m_updateState;
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_LATENCY_PROFILER_H)
@@ -1,52 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/LicenseServiceApi.h
*
* @brief Header file for the license service api class.
*/
#if (!defined ACTIV_FRAMEWORK_LICENSE_SERVICE_API_H)
#define ACTIV_FRAMEWORK_LICENSE_SERVICE_API_H
#include "ActivMiddleware/ActivFramework/External.h"
//! Activ namespace.
namespace Activ
{
class Component;
class IniFileParser;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Api to agent's license service.
*/
class LicenseServiceApi
{
public:
/**
* @brief Get the ini file parser containing the license.
*
* @param component component that wishes to get the ini file parser.
* @param iniFileParser reference to object to receive the ini file parser.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode GetIniFileParser(const Component &component, IniFileParser &iniFileParser);
/**
* @brief Get name of the ini file section containing the license.
*
* @param component component that wishes to get the section name.
* @param sectionName reference to object to receive the section name.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode GetSectionName(const Component &component, String &sectionName);
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_LICENSE_SERVICE_API_H)
@@ -1,325 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/LoggerServiceApi.h
*
* @brief Header file for the logger service api class.
*/
#if (!defined ACTIV_FRAMEWORK_LOGGER_SERVICE_API_H)
#define ACTIV_FRAMEWORK_LOGGER_SERVICE_API_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include "ActivMiddleware/ActivBase/FieldTypes/SInt.h"
#include "ActivMiddleware/Misc/StringView.h"
//! Activ namespace.
namespace Activ
{
class Address;
class Component;
class MessageBuilder;
class ScatterBufferHelper;
class HeapMessage;
class PostMessageHelper;
class ScopedAddress;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Api to the agent's logger service.
*/
class LoggerServiceApi
{
public:
/**
* @brief Request helper class.
*
* @param REQUEST_TYPE the request type.
* @param PARAMETERS the type of request parameters.
*/
template<MessageType REQUEST_TYPE, typename PARAMETERS>
class RequestHelper
{
public:
typedef PARAMETERS Parameters; ///< The parameters typedef.
/**
* @brief Create a new log file (or open an existing log file).
*
* @param component the component wanting to open the log file.
* @param parameters the request parameters for the log file.
* @param address reference to a scoped address object to receive the address of the log file.
*/
ACTIV_FRAMEWORK_API static StatusCode Create(const Component &component, const Parameters &parameters,
ScopedAddress &address);
static const MessageType REQUEST = REQUEST_TYPE; ///< The request type.
};
/**
* @brief Request parameters for opening log file
*/
class LogParameters
{
public:
/**
* @brief The basic filename for the log file. Will get decorated according to the type of log file, time periods, etc.
* If the filename is absolute, it will be created in the location specified.
* If if starts ./ or .\ (as appropriate for the platform) it will be created relative to the working directory.
* Otherwise, it is created relative to the LoggerService's default log directory.
*/
String m_fileName;
String m_header; ///< The log file header. A newline will automatically be appended.
UInt m_nBackups; ///< Number of past increments (days, months, etc) for which to keep log files.
protected:
/**
* @brief Constructor.
*
* @param fileName the log file name.
*/
ACTIV_FRAMEWORK_API LogParameters(const String &fileName);
};
/**
* @brief Request parameters for opening a rolling log file. When a rolling log file reaches its maximum size,
* message logging rolls back to the beginning of the file.
*/
class RollingLogParameters : public LogParameters
{
public:
/**
* @brief Constructor.
*
* @param fileName the log file name.
* @param maxFileSize the maximum size of the log file.
* @param nBackups the number of old rolling log files (with the same name) to keep.
*/
ACTIV_FRAMEWORK_API RollingLogParameters(const String &fileName, const UInt &maxFileSize, const UInt &nBackups);
UInt m_maxFileSize; ///< Maximum size of the log file.
};
/**
* @brief Request parameters for opening a time-based log file (daily, weekly, monthly). These log files are
* splittable; when the file reaches its split file size, message logging continues in a new file.
*/
class SplittableLogParameters : public LogParameters
{
public:
/**
* @brief Constructor.
*
* @param fileName the log file name.
*/
ACTIV_FRAMEWORK_API SplittableLogParameters(const String &fileName);
UInt m_nIntervals; ///< Create a new log every N intervals (hour, day, week, month). Default is 1.
UInt m_maxTotalSizeOfBackupFiles; ///< Maximum total size of all associated backup files.
UInt m_splitFileSize; ///< Position at which logging should split and move to new file.
UInt m_fileType; ///< The file type. Default: FILE_TYPE_NORMAL.
SInt m_compressionLevel; ///< Compression level of the file.
};
// Available log types.
typedef RequestHelper<LOGGER_REQUEST_OPEN_ROLLING_LOG_FILE, RollingLogParameters> RollingLog;
typedef RequestHelper<LOGGER_REQUEST_OPEN_HOURLY_SPLITTABLE_LOG_FILE, SplittableLogParameters> HourlyLog;
typedef RequestHelper<LOGGER_REQUEST_OPEN_DAILY_SPLITTABLE_LOG_FILE, SplittableLogParameters> DailyLog;
typedef RequestHelper<LOGGER_REQUEST_OPEN_WEEKLY_SPLITTABLE_LOG_FILE, SplittableLogParameters> WeeklyLog;
typedef RequestHelper<LOGGER_REQUEST_OPEN_MONTHLY_SPLITTABLE_LOG_FILE, SplittableLogParameters> MonthlyLog;
/**
* @brief Log a message to a log file.
*
* @tparam T a string type convertable to CxxYZ::string_view using ToStringType.
*
* @param component that wishes to log.
* @param logAddress the address of a log file.
* @param message the message to log.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval ...
*/
template<typename T>
static StatusCode LogMessage(const Component &component, const Address &logAddress, const T &message);
/**
* @brief Log a message to a log file.
*
* @param component that wishes to log.
* @param logAddress the address of a log file.
* @param pMessage the message to log.
* @param messageLength the length of the message.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode LogMessage(const Component &component, const Address &logAddress,
const void *pMessage, const size_t messageLength);
/**
* @brief Log a message to a log file.
*
* @param component that wishes to log.
* @param logAddress the address of a log file.
* @param messageBuilder containing the message to log.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode LogMessage(const Component &component, const Address &logAddress,
const MessageBuilder &messageBuilder);
/**
* @brief Log a message to a log file.
*
* @param component that wishes to log.
* @param logAddress the address of a log file.
* @param scatterBufferHelper containing the message to log.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode LogMessage(const Component &component, const Address &logAddress,
const ScatterBufferHelper &scatterBufferHelper);
/**
* @brief Log a message to a log file.
*
* @param component that wishes to log.
* @param logAddress the address of a log file.
* @param heapMessage a HeapMessage containing the message to log.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode LogMessage(const Component &component, const Address &logAddress,
HeapMessage &heapMessage);
/**
* @brief Log a message to a log file via a PostMessageHelper object.
*
* @tparam T a string type convertable to CxxYZ::string_view using ToStringType.
*
* @param component that wishes to log.
* @param postMessageHelper reference to a PostMessageHelper. The message will be queued here
* and not immediately sent to the LoggerService for distribution. postMessageHelper.Flush() will
* need to be called at some point in order to push any queued messages to the LoggerService.
* @param logAddress the address of a log file.
* @param message the message to log.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval ...
*/
template<typename T>
static StatusCode LogMessage(const Component &component, PostMessageHelper &postMessageHelper, const Address &logAddress,
const T &message);
/**
* @brief Log a message to a log file via a PostMessageHelper object.
*
* @param component that wishes to log.
* @param postMessageHelper reference to a PostMessageHelper. The message will be queued here
* and not immediately sent to the LoggerService for distribution. postMessageHelper.Flush() will
* need to be called at some point in order to push any queued messages to the LoggerService.
* @param logAddress the address of a log file.
* @param pMessage the message to log.
* @param messageLength the length of the message.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode LogMessage(const Component &component, PostMessageHelper &postMessageHelper,
const Address &logAddress, const void *pMessage, const size_t messageLength);
/**
* @brief Log a message to a log file via a PostMessageHelper object.
*
* @param component that wishes to log.
* @param postMessageHelper reference to a PostMessageHelper. The message will be queued here
* and not immediately sent to the LoggerService for distribution. postMessageHelper.Flush() will
* need to be called at some point in order to push any queued messages to the LoggerService.
* @param logAddress the address of a log file.
* @param messageBuilder the message to log.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode LogMessage(const Component &component, PostMessageHelper &postMessageHelper,
const Address &logAddress, const MessageBuilder &messageBuilder);
/**
* @brief Log a message to a log file via a PostMessageHelper object.
*
* @param component that wishes to log.
* @param postMessageHelper reference to a PostMessageHelper. The message will be queued here
* and not immediately sent to the LoggerService for distribution. postMessageHelper.Flush() will
* need to be called at some point in order to push any queued messages to the LoggerService.
* @param logAddress the address of a log file.
* @param scatterBufferHelper the message to log.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode LogMessage(const Component &component, PostMessageHelper &postMessageHelper,
const Address &logAddress, const ScatterBufferHelper &scatterBufferHelper);
/**
* @brief Log a message to a log file via a PostMessageHelper object.
*
* @param component that wishes to log.
* @param postMessageHelper reference to a PostMessageHelper. The message will be queued here
* and not immediately sent to the LoggerService for distribution. postMessageHelper.Flush() will
* need to be called at some point in order to push any queued messages to the LoggerService.
* @param logAddress the address of a log file.
* @param heapMessage a HeapMessage containing the message to log.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode LogMessage(const Component &component, PostMessageHelper &postMessageHelper,
const Address &logAddress, HeapMessage &heapMessage);
/**
* @brief Get the default directory used by the LoggerService.
*
* @param component
* @param directory to receive the directory.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode GetDefaultDirectory(const Component &component, String &directory);
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
StatusCode LoggerServiceApi::LogMessage(const Component &component, const Address &logAddress, const T &message)
{
const CxxYZ::string_view logMessage(ToStringType<CxxYZ::string_view>(message));
return LogMessage(component, logAddress, logMessage.data(), logMessage.size());
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
StatusCode LoggerServiceApi::LogMessage(const Component &component, PostMessageHelper &postMessageHelper, const Address &logAddress,
const T &message)
{
const CxxYZ::string_view logMessage(ToStringType<CxxYZ::string_view>(message));
return LogMessage(component, postMessageHelper, logAddress, logMessage.data(), logMessage.size());
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_LOGGER_SERVICE_API_H)
@@ -1,714 +0,0 @@
/**
* @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 SimplePostMessageHelper;
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_timerServiceTickInterval; ///< 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;
/**
* @brief Get a simple post message helper for a destination endpoint.
*
* Must be called from the context of a thread processing this ManagedEndPoint.
*
* @param endPointId id of the destination endpoint.
*
* @return A reference to a simple post message helper.
*/
ACTIV_FRAMEWORK_API
SimplePostMessageHelper &GetSimplePostMessageHelper(const EndPointId endPointId);
//! 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)
@@ -1,70 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ManagedEndPointEventManagee.h
*
* @brief Header file for router ManagedEndPointEventManagee.
*/
#if (!defined ACTIV_FRAMEWORK_MANAGED_END_POINT_EVENT_MANAGEE_H)
#define ACTIV_FRAMEWORK_MANAGED_END_POINT_EVENT_MANAGEE_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/ManagedEndPoint.h"
#include "ActivMiddleware/ActivBase/Posix/EventManager.h"
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
//! Activ namespace.
namespace Activ
{
/**
* @brief Helper class that allows us to plug the notification event of an endpoint
* into an existing external EventManager.
*
* Note this differs from the ManagedEndPoint GetEventManager() functionality, which creates an EventManager internally to the
* ManagedEndPoint which can then be used externally to the ManagedEndPoint.
*/
class ManagedEndPointEventManagee : public EventManagee
{
public:
/**
* @brief Constructor.
*
* @param manangedEndPoint
* @param eventManager
* @param pRunHelper optional RunHelper. Only use if you want to call EventManager::Distribute() externally,
* rather than using Run().
*/
ACTIV_FRAMEWORK_API ManagedEndPointEventManagee(ManagedEndPoint &manangedEndPoint, EventManager &eventManager,
ManagedEndPoint::RunHelper * const pRunHelper = 0);
/**
* @brief Destructor.
*/
ACTIV_FRAMEWORK_API ~ManagedEndPointEventManagee();
/**
* @brief Run the EventManager.
*/
ACTIV_FRAMEWORK_API void Run();
protected:
/**
* @brief Called when there are no more messages on the endpoint.
*
* This default implementation does nothing.
*/
ACTIV_FRAMEWORK_API virtual void OnNoMessages();
private:
ACTIV_FRAMEWORK_API virtual void OnEvents(const Events events) ACTIV_OVERRIDE;
ManagedEndPoint & m_managedEndPoint;
EventManager & m_eventManager;
ManagedEndPoint::RunHelper * m_pRunHelper;
Boost::scoped_ptr<ManagedEndPoint::RunHelper> m_pScopedRunHelper;
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_MANAGED_END_POINT_EVENT_MANAGEE_H)
@@ -1,261 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/MessageImpl.h
*
* @brief Header file for message implementation class.
*/
#if (!defined ACTIV_FRAMEWORK_MESSAGE_IMPL_H)
#define ACTIV_FRAMEWORK_MESSAGE_IMPL_H
#include "ActivMiddleware/ActivFramework/MessageKey.h"
#include "ActivMiddleware/ActivFramework/Address.h"
#include "ActivMiddleware/ActivFramework/Subject.h"
#include "ActivMiddleware/ActivFramework/RequestId.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
//! Activ namespace.
namespace Activ
{
class EndPoint;
class Heap;
class HeapMessage;
class HeapMessageQueue;
class ManagedEndPointImpl;
class PrivateHeap;
class SharedHeap;
class SystemImpl;
class EndPointWalker;
class HeapWalker;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Message implementation class.
*/
class MessageImpl : private Boost::noncopyable
{
private:
// To avoid compiler issues with additional size_t parameter to placement new.
class BlockSizeWrapper
{
public:
BlockSizeWrapper(const size_t value) :
m_value(value)
{
}
size_t m_value;
};
/**
* @brief Allocate a message from local memory.
*
* @param basicSize size of the message class.
* @param blockSize the size of the data portion of this message.
*
* @return Pointer to allocated memory.
*/
static void *operator new(size_t basicSize, const BlockSizeWrapper &blockSize);
/**
* @brief Free a local memory message.
*
* @param p the allocated memory.
*/
static void operator delete(void *p);
/**
* @brief Free a local memory message.
*
* @param p the allocated memory.
* @param blockSize the size of the data portion of this message.
*/
static void operator delete(void *p, const BlockSizeWrapper &blockSize);
/**
* @brief Construct a shared memory message.
*
* @param heapId the id of the heap containing this message.
* @param bucketId the bucket within the heap containing this message.
* @param thisMessageId message id of this message.
* @param continuationMessageId message id of the next message in the heap.
* @param blockSize the size of the data portion of this message.
*/
MessageImpl(HeapId heapId, BucketId bucketId, MessageId thisMessageId, MessageId continuationMessageId, uint32_t blockSize);
/**
* @brief Construct a local memory message.
*
* @param heapId the id of the heap containing this message.
* @param bucketId the bucket within the heap containing this message.
* @param blockSize the size of the data portion of this message.
*/
MessageImpl(HeapId heapId, BucketId bucketId, uint32_t blockSize);
/**
* @brief Attach a continuation message.
*
* @param messageId the continuation message id.
*/
void AttachContinuationMessageId(const MessageId messageId);
/**
* @brief Attach a continuation message and return the old.
*
* @param messageId the continuation message id.
*
* @return The old continuation message id of this message.
*/
MessageId AttachNewContinuationMessageId(const MessageId messageId);
/**
* @brief Initialize a message after removing from a heap.
*
* @param totalSpace the total number of bytes available in the message (chain).
*/
void Initialize(uint32_t totalSpace);
/**
* @brief Get a pointer to the data portion of the message.
*
* @return A pointer to the data portion.
*/
void *GetDataPointer() const;
const MessageKey m_thisMessage; ///< Reference to ourself.
const uint32_t m_size; ///< Size of the single message block.
const BucketId m_bucketId; ///< Bucket this message belongs to in its heap.
StatusCode m_statusCode; ///< Message status.
MessageType m_type; ///< Message type.
MessageId m_continuationMessageId; ///< Next message in (free) chain. Always from the same heap as this message.
MessageKey m_nextMessage; ///< Next message in queue.
uint32_t m_totalSpace; ///< Total size of all blocks in the chain.
uint32_t m_freeSpace; ///< Total amount of free space in the message chain.
Address m_sourceAddress; ///< Source address of the message.
Address m_destinationAddress; ///< Destination address of the message.
Address m_returnAddress; ///< Address to implicitly route message when it is "returned" to its heap.
// The following are less likely to be needed. Possibly we should move them to the end of the shared memory region
// to get better cache usage.
#define ACTIV_MESSAGE_IMPL_END_OF_INTERESTING_DATA_MARKER m_requestId
RequestId m_requestId;
Subject m_subject;
IpAddress m_ipAddress;
friend class EndPoint;
friend class Heap;
friend class HeapMessage;
friend class HeapMessageQueue;
friend class ManagedEndPointImpl;
friend class PrivateHeap;
friend class SharedHeap;
friend class SystemImpl;
friend class EndPointWalker;
friend class HeapWalker;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline void *MessageImpl::operator new(size_t basicSize, const BlockSizeWrapper &blockSize)
{
return std::malloc(AlignValueToProcessorWordBoundary<size_t>(basicSize) + blockSize.m_value);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void MessageImpl::operator delete(void *p)
{
if (NULL != p)
std::free(p);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void MessageImpl::operator delete(void *p, const BlockSizeWrapper &blockSize)
{
if (NULL != p)
std::free(p);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageImpl::MessageImpl(HeapId heapId, BucketId bucketId, MessageId thisMessageId, MessageId continuationMessageId,
uint32_t blockSize) :
m_thisMessage(thisMessageId, heapId),
m_size(blockSize),
m_bucketId(bucketId),
m_continuationMessageId(continuationMessageId)
{
// Shared heap MessageImpl constructor.
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageImpl::MessageImpl(HeapId heapId, BucketId bucketId, uint32_t blockSize) :
// Two stage cast because on 32-bit, if the top bit is set of "this" there's some crazy sign extension stuff going on.
m_thisMessage(static_cast<MessageId>(reinterpret_cast<uintptr_t>(this)), heapId),
m_size(blockSize),
m_bucketId(bucketId),
m_continuationMessageId(MessageKey::INVALID_MESSAGE_ID)
{
// Private heap MessageImpl constructor.
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void MessageImpl::AttachContinuationMessageId(const MessageId messageId)
{
m_continuationMessageId = messageId;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageId MessageImpl::AttachNewContinuationMessageId(const MessageId messageId)
{
const MessageId previousContinuationMessageId = m_continuationMessageId;
AttachContinuationMessageId(messageId);
return previousContinuationMessageId;
}
// ---------------------------------------------------------------------------------------------------------------------------------
ACTIV_FORCE_INLINE void MessageImpl::Initialize(uint32_t totalSpace)
{
// Message has just been removed from a heap. Clear it down.
m_totalSpace = totalSpace;
m_freeSpace = totalSpace;
// NB a hack with memset() was tried here; performance was worse.
m_sourceAddress.Clear();
m_destinationAddress.Clear();
m_returnAddress.Clear();
m_statusCode = STATUS_CODE_SUCCESS;
m_requestId.Clear();
m_subject.Clear();
m_ipAddress.SetLength(0);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void *MessageImpl::GetDataPointer() const
{
// Data portion now just follows this object in memory.
return reinterpret_cast<byte_t *>(const_cast<MessageImpl *>(this)) +
StaticAlignValueToProcessorWordBoundary<size_t, sizeof(MessageImpl)>::value;
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_MESSAGE_IMPL_H)
@@ -1,159 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/MessageKey.h
*
* @brief Header file for message key class.
*/
#if (!defined ACTIV_FRAMEWORK_MESSAGE_KEY_H)
#define ACTIV_FRAMEWORK_MESSAGE_KEY_H
#include "ActivMiddleware/ActivFramework/BasicTypes.h"
#include "ActivMiddleware/Misc/BitFields.h"
#include ACTIV_BOOST_INCLUDE(utility/explicit_operator_bool.hpp)
//! Activ namespace.
namespace Activ
{
/**
* @brief Message key class.
*/
class MessageKey
{
private:
class InternalBitmap : public Bitmap<64, MsbOrigin>
{
public:
typedef BitField<InternalBitmap, 16> HeapId;
typedef TerminalBitField<HeapId> MessageId;
};
ACTIV_BOOST_STATIC_ASSERT(sizeof(MessageId) >= sizeof(void *));
ACTIV_BOOST_STATIC_ASSERT(sizeof(void *) <= sizeof(InternalBitmap::Type));
public:
static const MessageId INVALID_MESSAGE_ID = InternalBitmap::MessageId::maxValue;
//! Default constructor.
MessageKey();
/**
* @brief Constructor.
*
* @param messageId index of message within heap.
* @param heapId heap id.
*/
MessageKey(const MessageId messageId, const HeapId heapId);
//! Clear the message key.
void Clear();
/**
* @brief Equality operator.
*
* @return whether the two objects are equal.
*/
bool operator==(const MessageKey &rhs) const;
/**
* @brief Inequality operator.
*
* @return whether the two objects are not equal.
*/
bool operator!=(const MessageKey &rhs) const;
/**
* @brief Assign a new message id.
*
* @param messageId
*/
void Assign(const MessageId messageId);
//! Get message id.
MessageId GetMessageId() const;
//! Get heap id.
HeapId GetHeapId() const;
//! Is a message attached to this object?
ACTIV_BOOST_EXPLICIT_OPERATOR_BOOL()
//! Is a message not attached to this object?
bool operator!() const;
private:
InternalBitmap::Type m_internalBitmap; ///< Encoded heap id and message id.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageKey::MessageKey()
{
Clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageKey::MessageKey(const MessageId messageId, const HeapId heapId)
{
InternalBitmap::HeapId::Set(m_internalBitmap, heapId);
Assign(messageId);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void MessageKey::Clear()
{
m_internalBitmap = Boost::integer_traits<InternalBitmap::Type>::const_max;
// The same as:
// InternalBitmap::HeapId::Set(m_internalBitmap, INVALID_HEAP_ID);
// Assign(MessageKey::INVALID_MESSAGE_ID);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool MessageKey::operator==(const MessageKey &rhs) const
{
return (m_internalBitmap == rhs.m_internalBitmap);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool MessageKey::operator!=(const MessageKey &rhs) const
{
return !((*this) == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void MessageKey::Assign(const MessageId messageId)
{
InternalBitmap::MessageId::Set(m_internalBitmap, messageId);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline MessageId MessageKey::GetMessageId() const
{
return InternalBitmap::MessageId::GetShifted(m_internalBitmap);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline HeapId MessageKey::GetHeapId() const
{
return InternalBitmap::HeapId::GetShifted(m_internalBitmap);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool MessageKey::operator!() const
{
return (INVALID_MESSAGE_ID == GetMessageId());
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_MESSAGE_KEY_H)
@@ -1,634 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/MessageTypes.h
*
* @brief Message types.
*/
#if (!defined ACTIV_FRAMEWORK_MESSAGE_TYPES_H)
#define ACTIV_FRAMEWORK_MESSAGE_TYPES_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/Misc/Singleton.h"
#include "ActivMiddleware/CxxYZ/memory.h"
#if (!defined ACTIV_LITE_FRAMEWORK) && (!defined ACTIV_FRAMEWORK_MESSAGE_TYPES_NO_REGISTRY)
#define ACTIV_FRAMEWORK_MESSAGE_TYPES_USE_REGISTRY
#include <vector>
#endif
//! Activ namespace.
namespace Activ
{
//! Message class type.
typedef byte_t MessageClass;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Declare a constant message class value.
*
* @param value numeric value of message class.
* @param messageClass identifier for message class.
*/
#define ACTIV_DECLARE_MESSAGE_CLASS(value, messageClass) \
const Activ::MessageClass messageClass = value;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Declare a constant message type value.
*
* @param value message sub-type.
* @param messageClass
* @param name
*/
#define ACTIV_DECLARE_MESSAGE_TYPE(value, messageClass, name) \
const Activ::MessageType name = MakeMessageType(messageClass, value)
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Declare a constant request type value.
*
* @param value message sub-type.
* @param messageClass
* @param name
*/
#define ACTIV_DECLARE_REQUEST_TYPE(value, messageClass, name) \
const Activ::MessageType name = MakeMessageType(messageClass, value)
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Macro to make message type.
*
* @param messageClass the message class of the type.
* @param subType the message subtype within \a messageClass.
*/
#define MakeMessageType(messageClass, subType) \
((static_cast<Activ::MessageType>((messageClass)) << 8) | (subType))
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get the message class from a message type.
*
* @param messageType message type.
*
* @return Class of \a messageType.
*/
inline MessageClass GetMessageClass(const MessageType messageType)
{
return static_cast<MessageClass>(messageType >> 8);
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get the message subtype from from a message type.
*
* @param messageType message type.
*
* @return Subtype of \a messageType.
*/
inline byte_t GetSubType(const MessageType messageType)
{
return static_cast<byte_t>(messageType & 0xff);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Registry of message type names.
*/
class MessageTypeRegistry : private Singleton<MessageTypeRegistry>
{
public:
/**
* @brief Register a message class <-> name mapping.
*
* @param messageClass
* @param pName
*/
ACTIV_FRAMEWORK_API void RegisterMessageClass(const MessageClass messageClass, const char * const pName);
/**
* @brief Get a list of the currently registered message class strings.
*
* @return Vector of String.
*/
ACTIV_FRAMEWORK_API std::vector<String> GetRegisteredMessageClassList() const;
/**
* @brief Get the name of a message class.
*
* @param messageClass
*
* @return Name of the message class, or if not registered, the numeric message class formatted as a hex string.
*/
ACTIV_FRAMEWORK_API String MessageClassToString(const MessageClass messageClass) const;
/**
* @brief Attempt to convert a string to a message class.
*
* @param str
* @param messageClass to receive the message class on success.
*
* @return true if the mapping was successful.
*/
ACTIV_FRAMEWORK_API bool StringToMessageClass(const String &str, MessageClass &messageClass) const;
/**
* @brief Register a message type <-> name mapping.
*
* @param messageType
* @param pName
*/
ACTIV_FRAMEWORK_API void RegisterMessageType(const MessageType messageType, const char * const pName);
/**
* @brief Get a list of the currently registered message type strings.
*
* @return Vector of String.
*/
ACTIV_FRAMEWORK_API std::vector<String> GetRegisteredMessageTypeList() const;
/**
* @brief Get the name of a message type.
*
* @param messageType
*
* @return Name of the message, or if not registered, the numeric message type formatted as a hex string.
*/
ACTIV_FRAMEWORK_API String MessageTypeToString(const MessageType messageType) const;
/**
* @brief Attempt to convert a string to a message type.
*
* @param str
* @param messageType to receive the message type on success.
*
* @return true if the mapping was successful.
*/
ACTIV_FRAMEWORK_API bool StringToMessageType(const String &str, MessageType &messageType) const;
/**
* @brief Register a request/response type <-> name mapping.
*
* @param messageType
* @param pName
*/
ACTIV_FRAMEWORK_API void RegisterRequestType(const MessageType messageType, const char * const pName);
//! Get a list of the currently registered request type strings.
ACTIV_FRAMEWORK_API std::vector<String> GetRegisteredRequestTypeList() const;
/**
* @brief Get the name of a request/response type.
*
* @param messageType
*
* @return Name of the request/response, or if not registered, the numeric message type formatted as a hex string.
*/
ACTIV_FRAMEWORK_API String RequestTypeToString(const MessageType messageType) const;
/**
* @brief Attempt to convert a string to a request/response type.
*
* @param str
* @param messageType to receive the request/response type on success.
*
* @return true if the mapping was successful.
*/
ACTIV_FRAMEWORK_API bool StringToRequestType(const String &str, MessageType &messageType) const;
//! Get singleton instance.
ACTIV_FRAMEWORK_API static MessageTypeRegistry &GetInstance();
private:
//! Constructor.
MessageTypeRegistry();
class Impl;
CxxYZ::unique_ptr<Impl> m_pImpl;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
#if (defined ACTIV_FRAMEWORK_MESSAGE_TYPES_USE_REGISTRY)
/**
* @brief Helper to register a message class via MessageTypeRegistry.
*/
class RegisterMessageClassHelper
{
public:
RegisterMessageClassHelper(const MessageClass messageClass, const char * const pName)
{
MessageTypeRegistry::GetInstance().RegisterMessageClass(messageClass, pName);
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Helper to register a request/response type via MessageTypeRegistry.
*/
class RegisterMessageTypeHelper
{
public:
RegisterMessageTypeHelper(const MessageType messageType, const char * const pName)
{
MessageTypeRegistry::GetInstance().RegisterMessageType(messageType, pName);
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Helper to register a message type via MessageTypeRegistry.
*/
class RegisterRequestTypeHelper
{
public:
RegisterRequestTypeHelper(const MessageType messageType, const char * const pName)
{
MessageTypeRegistry::GetInstance().RegisterRequestType(messageType, pName);
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Declare a constant message class value and register its name.
*
* @param value message sub-type.
* @param name
*/
#define ACTIV_REGISTER_MESSAGE_CLASS(value, name) \
const Activ::MessageClass name = value; \
const Activ::RegisterMessageClassHelper __g_##name(name, ACTIV_STRINGIZE(name))
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Declare a constant message type value and register its name.
*
* @param value message sub-type.
* @param messageClass
* @param name
*/
#define ACTIV_REGISTER_MESSAGE_TYPE(value, messageClass, name) \
const Activ::MessageType name = MakeMessageType(messageClass, value); \
const Activ::RegisterMessageTypeHelper __g_##name(name, ACTIV_STRINGIZE(name))
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Declare a constant request/response type value and register its name.
*
* @param value message sub-type.
* @param messageClass
* @param name
*/
#define ACTIV_REGISTER_REQUEST_TYPE(value, messageClass, name) \
const Activ::MessageType name = MakeMessageType(messageClass, value); \
const Activ::RegisterRequestTypeHelper __g_##name(name, ACTIV_STRINGIZE(name))
#else
#define ACTIV_REGISTER_MESSAGE_CLASS(value, name) ACTIV_DECLARE_MESSAGE_CLASS(value, name)
#define ACTIV_REGISTER_MESSAGE_TYPE(value, messageClass, name) ACTIV_DECLARE_MESSAGE_TYPE(value, messageClass, name)
#define ACTIV_REGISTER_REQUEST_TYPE(value, messageClass, name) ACTIV_DECLARE_REQUEST_TYPE(value, messageClass, name)
#endif
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
ACTIV_REGISTER_MESSAGE_CLASS(0, MESSAGE_CLASS_SYSTEM);
ACTIV_REGISTER_MESSAGE_CLASS(1, MESSAGE_CLASS_TIMER);
ACTIV_REGISTER_MESSAGE_CLASS(2, MESSAGE_CLASS_LOGGER);
ACTIV_REGISTER_MESSAGE_CLASS(4, MESSAGE_CLASS_ROUTER);
ACTIV_REGISTER_MESSAGE_CLASS(5, MESSAGE_CLASS_PUBSUB);
ACTIV_REGISTER_MESSAGE_CLASS(6, MESSAGE_CLASS_MQ);
ACTIV_REGISTER_MESSAGE_CLASS(7, MESSAGE_CLASS_UI);
ACTIV_REGISTER_MESSAGE_CLASS(8, MESSAGE_CLASS_DATABASE);
ACTIV_REGISTER_MESSAGE_CLASS(9, MESSAGE_CLASS_SERVICE);
ACTIV_REGISTER_MESSAGE_CLASS(10, MESSAGE_CLASS_UDP);
ACTIV_REGISTER_MESSAGE_CLASS(11, MESSAGE_CLASS_TCP);
ACTIV_REGISTER_MESSAGE_CLASS(12, MESSAGE_CLASS_MONITOR);
ACTIV_REGISTER_MESSAGE_CLASS(14, MESSAGE_CLASS_LICENSE);
ACTIV_REGISTER_MESSAGE_CLASS(15, MESSAGE_CLASS_RDMA);
ACTIV_REGISTER_MESSAGE_CLASS(16, MESSAGE_CLASS_PACKET_SERVER);
ACTIV_REGISTER_MESSAGE_CLASS(17, MESSAGE_CLASS_REPLICATOR);
ACTIV_REGISTER_MESSAGE_CLASS(18, MESSAGE_CLASS_API_INTERNAL);
ACTIV_REGISTER_MESSAGE_CLASS(64, MESSAGE_CLASS_USER_BASE);
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of MESSAGE_CLASS_SYSTEM request types.
*/
ACTIV_REGISTER_REQUEST_TYPE(0, MESSAGE_CLASS_SYSTEM, SYSTEM_REQUEST_FIND_COMPONENT);
ACTIV_REGISTER_REQUEST_TYPE(1, MESSAGE_CLASS_SYSTEM, SYSTEM_REQUEST_PING_COMPONENT);
ACTIV_REGISTER_REQUEST_TYPE(2, MESSAGE_CLASS_SYSTEM, SYSTEM_REQUEST_TOKEN);
ACTIV_REGISTER_REQUEST_TYPE(3, MESSAGE_CLASS_SYSTEM, SYSTEM_REQUEST_GET_COMPONENT_INFO_LIST);
ACTIV_REGISTER_REQUEST_TYPE(4, MESSAGE_CLASS_SYSTEM, SYSTEM_REQUEST_PROCESS_STARTUP);
ACTIV_REGISTER_REQUEST_TYPE(5, MESSAGE_CLASS_SYSTEM, SYSTEM_REQUEST_HEAP_STARTUP);
ACTIV_REGISTER_REQUEST_TYPE(6, MESSAGE_CLASS_SYSTEM, SYSTEM_REQUEST_ENDPOINT_STARTUP);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of MESSAGE_CLASS_SYSTEM message types.
*/
ACTIV_REGISTER_MESSAGE_TYPE(0, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_THREAD_EXIT);
ACTIV_REGISTER_MESSAGE_TYPE(1, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_CTRL_EVENT);
ACTIV_REGISTER_MESSAGE_TYPE(2, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_SYSTEM_SHUTDOWN);
ACTIV_REGISTER_MESSAGE_TYPE(4, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_PROCESS_SHUTDOWN);
ACTIV_REGISTER_MESSAGE_TYPE(6, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_ENDPOINT_SHUTDOWN);
ACTIV_REGISTER_MESSAGE_TYPE(7, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_ENDPOINT_DIE);
ACTIV_REGISTER_MESSAGE_TYPE(9, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_ENDPOINT_PAUSE);
ACTIV_REGISTER_MESSAGE_TYPE(10, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_ENDPOINT_RESUME);
ACTIV_REGISTER_MESSAGE_TYPE(11, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_CLOSE_ADDRESS);
ACTIV_REGISTER_MESSAGE_TYPE(12, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_KILL_PROCESSES);
ACTIV_REGISTER_MESSAGE_TYPE(13, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_NOP);
ACTIV_REGISTER_MESSAGE_TYPE(14, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_ENABLE_COMPONENT);
ACTIV_REGISTER_MESSAGE_TYPE(15, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_PROCESS_STATE_CHANGE);
ACTIV_REGISTER_MESSAGE_TYPE(16, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_ENABLE_RESTART);
ACTIV_REGISTER_MESSAGE_TYPE(17, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_NEW_CHILD_ENDPOINT);
ACTIV_REGISTER_MESSAGE_TYPE(18, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_PING);
ACTIV_REGISTER_MESSAGE_TYPE(19, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_TASK);
ACTIV_REGISTER_MESSAGE_TYPE(20, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_SET_HEAP_FAST_PATH_GET_THREAD);
ACTIV_REGISTER_MESSAGE_TYPE(21, MESSAGE_CLASS_SYSTEM, SYSTEM_MESSAGE_SET_HEAP_FAST_PATH_RETURN_THREAD);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of MESSAGE_CLASS_TIMER request types.
*/
ACTIV_REGISTER_REQUEST_TYPE(0, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_LOCAL_ALARM);
ACTIV_REGISTER_REQUEST_TYPE(1, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_COUNTDOWN);
ACTIV_REGISTER_REQUEST_TYPE(2, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_TICK_BASED_MILLISECOND_CHIME);
ACTIV_REGISTER_REQUEST_TYPE(3, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_TICK_BASED_SECOND_CHIME);
ACTIV_REGISTER_REQUEST_TYPE(4, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_TICK_BASED_MINUTE_CHIME);
ACTIV_REGISTER_REQUEST_TYPE(5, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_TICK_BASED_HOUR_CHIME);
ACTIV_REGISTER_REQUEST_TYPE(6, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_LOCAL_CLOCK_BASED_SECOND_CHIME);
ACTIV_REGISTER_REQUEST_TYPE(7, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_LOCAL_CLOCK_BASED_MINUTE_CHIME);
ACTIV_REGISTER_REQUEST_TYPE(8, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_LOCAL_CLOCK_BASED_HOUR_CHIME);
ACTIV_REGISTER_REQUEST_TYPE(9, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_LOCAL_CLOCK_BASED_DAY_CHIME);
//ACTIV_REGISTER_REQUEST_TYPE(10, MESSAGE_CLASS_TIMER, TIMER_REQUEST_GET_CURRENT_TIME_OBJECT);
ACTIV_REGISTER_REQUEST_TYPE(11, MESSAGE_CLASS_TIMER, TIMER_REQUEST_ADJUST_SYSTEM_TIME);
ACTIV_REGISTER_REQUEST_TYPE(12, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_UTC_CLOCK_BASED_SECOND_CHIME);
ACTIV_REGISTER_REQUEST_TYPE(13, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_UTC_CLOCK_BASED_MINUTE_CHIME);
ACTIV_REGISTER_REQUEST_TYPE(14, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_UTC_CLOCK_BASED_HOUR_CHIME);
ACTIV_REGISTER_REQUEST_TYPE(15, MESSAGE_CLASS_TIMER, TIMER_REQUEST_SET_UTC_CLOCK_BASED_DAY_CHIME);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of MESSAGE_CLASS_TIMER message types.
*/
ACTIV_REGISTER_MESSAGE_TYPE(0, MESSAGE_CLASS_TIMER, TIMER_MESSAGE_ON_TIMER);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of MESSAGE_CLASS_LOGGER message types.
*/
ACTIV_REGISTER_MESSAGE_TYPE(0, MESSAGE_CLASS_LOGGER, LOGGER_MESSAGE_LOG_MESSAGE);
ACTIV_REGISTER_MESSAGE_TYPE(1, MESSAGE_CLASS_LOGGER, LOGGER_MESSAGE_SYSTEM_LOG_MESSAGE);
ACTIV_REGISTER_MESSAGE_TYPE(2, MESSAGE_CLASS_LOGGER, LOGGER_MESSAGE_ALERT_MESSAGE);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of MESSAGE_CLASS_LOGGER request types.
*/
ACTIV_REGISTER_REQUEST_TYPE(0, MESSAGE_CLASS_LOGGER, LOGGER_REQUEST_OPEN_ROLLING_LOG_FILE);
ACTIV_REGISTER_REQUEST_TYPE(1, MESSAGE_CLASS_LOGGER, LOGGER_REQUEST_OPEN_DAILY_SPLITTABLE_LOG_FILE);
ACTIV_REGISTER_REQUEST_TYPE(2, MESSAGE_CLASS_LOGGER, LOGGER_REQUEST_OPEN_WEEKLY_SPLITTABLE_LOG_FILE);
ACTIV_REGISTER_REQUEST_TYPE(3, MESSAGE_CLASS_LOGGER, LOGGER_REQUEST_OPEN_MONTHLY_SPLITTABLE_LOG_FILE);
ACTIV_REGISTER_REQUEST_TYPE(4, MESSAGE_CLASS_LOGGER, LOGGER_REQUEST_OPEN_SYSTEM_LOG_FILE);
ACTIV_REGISTER_REQUEST_TYPE(5, MESSAGE_CLASS_LOGGER, LOGGER_REQUEST_OPEN_HOURLY_SPLITTABLE_LOG_FILE);
ACTIV_REGISTER_REQUEST_TYPE(6, MESSAGE_CLASS_LOGGER, LOGGER_REQUEST_GET_DEFAULT_DIRECTORY);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief MESSAGE_CLASS_ROUTER request types.
*/
ACTIV_REGISTER_REQUEST_TYPE(0, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_ASYNC_CONNECT);
ACTIV_REGISTER_REQUEST_TYPE(1, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_ALLOCATE_CLIENT);
ACTIV_REGISTER_REQUEST_TYPE(2, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_INITIATE_CONNECT);
ACTIV_REGISTER_REQUEST_TYPE(3, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_INITIATE_DISCONNECT);
ACTIV_REGISTER_REQUEST_TYPE(4, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_START_LISTEN);
ACTIV_REGISTER_REQUEST_TYPE(5, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_ADD_DIRECTORY_WATCH);
ACTIV_REGISTER_REQUEST_TYPE(6, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_INTERNAL_ACCEPT_FORWARD);
ACTIV_REGISTER_REQUEST_TYPE(7, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_INTERNAL_SYN);
ACTIV_REGISTER_REQUEST_TYPE(8, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_INTERNAL_FIN);
ACTIV_REGISTER_REQUEST_TYPE(9, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_NOTIFY_ACCEPT_CONNECTION);
ACTIV_REGISTER_REQUEST_TYPE(10, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_INIT);
ACTIV_REGISTER_REQUEST_TYPE(11, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_SHUTDOWN);
ACTIV_REGISTER_REQUEST_TYPE(12, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_GET_SOCKET_HANDLE);
ACTIV_REGISTER_REQUEST_TYPE(13, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_CONNECT);
ACTIV_REGISTER_REQUEST_TYPE(14, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_DISCONNECT);
ACTIV_REGISTER_REQUEST_TYPE(15, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_MULTICAST_JOIN);
ACTIV_REGISTER_REQUEST_TYPE(16, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_MULTICAST_LEAVE);
ACTIV_REGISTER_REQUEST_TYPE(17, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_SET_MULTICAST_TTL);
ACTIV_REGISTER_REQUEST_TYPE(18, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_SET_UNICAST_TTL);
ACTIV_REGISTER_REQUEST_TYPE(19, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_SET_MULTICAST_INTERFACE);
ACTIV_REGISTER_REQUEST_TYPE(20, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_SET_RX_BUFFER_SIZE);
ACTIV_REGISTER_REQUEST_TYPE(21, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_SET_TX_BUFFER_SIZE);
ACTIV_REGISTER_REQUEST_TYPE(22, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_SET_MULTICAST_LOOPBACK);
ACTIV_REGISTER_REQUEST_TYPE(23, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_CLEAR_MULTICAST_LOOPBACK);
ACTIV_REGISTER_REQUEST_TYPE(24, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_GET_RX_BUFFER_SIZE);
ACTIV_REGISTER_REQUEST_TYPE(25, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_GET_TX_BUFFER_SIZE);
//ACTIV_REGISTER_REQUEST_TYPE(26, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_GET_TUNNEL_TYPE);
ACTIV_REGISTER_REQUEST_TYPE(27, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_UDP_SET_TYPE_OF_SERVICE);
ACTIV_REGISTER_REQUEST_TYPE(28, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_GET_LOCAL_IP_ADDRESS);
ACTIV_REGISTER_REQUEST_TYPE(29, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_GET_ENDPOINT_ID_SET);
ACTIV_REGISTER_REQUEST_TYPE(30, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_GET_MAX_TX_QUEUE_SIZE);
ACTIV_REGISTER_REQUEST_TYPE(31, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_ADD_NETWORK_AFFINITY_FILTER);
ACTIV_REGISTER_REQUEST_TYPE(32, MESSAGE_CLASS_ROUTER, ROUTER_REQUEST_USER_REMOVE_NETWORK_AFFINITY_FILTER);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief MESSAGE_CLASS_ROUTER message types.
*/
ACTIV_REGISTER_MESSAGE_TYPE(0, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_INTERNAL_SOCKET_CONNECT);
ACTIV_REGISTER_MESSAGE_TYPE(1, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_INTERNAL_SOCKET_CONNECT_FAILED);
ACTIV_REGISTER_MESSAGE_TYPE(2, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_INTERNAL_SOCKET_CONNECT_ABORTED);
ACTIV_REGISTER_MESSAGE_TYPE(3, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_INTERNAL_SOCKET_ACCEPT);
ACTIV_REGISTER_MESSAGE_TYPE(4, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_INTERNAL_SOCKET_ACCEPT_FAILED);
ACTIV_REGISTER_MESSAGE_TYPE(5, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_INTERNAL_SOCKET_ACCEPT_ABORTED);
ACTIV_REGISTER_MESSAGE_TYPE(6, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_INTERNAL_SOCKET_BREAK);
ACTIV_REGISTER_MESSAGE_TYPE(7, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_INTERNAL_SOCKET_DISCONNECT);
ACTIV_REGISTER_MESSAGE_TYPE(8, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_INITIATE_DISCONNECT);
ACTIV_REGISTER_MESSAGE_TYPE(9, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_BREAK_CONNECTION);
ACTIV_REGISTER_MESSAGE_TYPE(10, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_BREAK_ACCEPTED);
ACTIV_REGISTER_MESSAGE_TYPE(11, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_STOP_LISTEN);
ACTIV_REGISTER_MESSAGE_TYPE(12, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_NOTIFY_CIRCUIT_UP);
ACTIV_REGISTER_MESSAGE_TYPE(13, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_NOTIFY_CIRCUIT_DOWN);
ACTIV_REGISTER_MESSAGE_TYPE(14, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_NOTIFY_CIRCUIT_BREAK);
ACTIV_REGISTER_MESSAGE_TYPE(15, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_DATA);
ACTIV_REGISTER_MESSAGE_TYPE(17, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_SET_MAX_TX_QUEUE_SIZE);
ACTIV_REGISTER_MESSAGE_TYPE(18, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_UDP_READ);
ACTIV_REGISTER_MESSAGE_TYPE(19, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_UDP_READ_WITH_PURGE);
ACTIV_REGISTER_MESSAGE_TYPE(20, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_STOP_LISTEN_AND_BREAK_ACCEPTED);
ACTIV_REGISTER_MESSAGE_TYPE(26, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_NOTIFY_UDP_SOCKET_ERROR);
ACTIV_REGISTER_MESSAGE_TYPE(27, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_NOTIFY_UDP_SOCKET_SHUTDOWN);
ACTIV_REGISTER_MESSAGE_TYPE(30, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_SET_HEAP);
ACTIV_REGISTER_MESSAGE_TYPE(31, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_NOTIFY_CIRCUIT_FAILED);
ACTIV_REGISTER_MESSAGE_TYPE(32, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_INTERNAL_SOCKET_LISTENER_CLOSED);
ACTIV_REGISTER_MESSAGE_TYPE(33, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_CLEAR_SOCKET_STATS_HIGHS);
ACTIV_REGISTER_MESSAGE_TYPE(34, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_INTERNAL_DIRECTORY_WATCH_CLOSED);
ACTIV_REGISTER_MESSAGE_TYPE(36, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_NOTIFY_DIRECTORY_WATCH_EVENTS);
ACTIV_REGISTER_MESSAGE_TYPE(37, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_ENABLE_SOCKET_STATS);
ACTIV_REGISTER_MESSAGE_TYPE(38, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_NOTIFY_SOCKET_STATS);
ACTIV_REGISTER_MESSAGE_TYPE(39, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_SOCKET_TOKEN);
ACTIV_REGISTER_MESSAGE_TYPE(40, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_ADD_NETWORK_AFFINITY_FILTER);
ACTIV_REGISTER_MESSAGE_TYPE(41, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_REMOVE_NETWORK_AFFINITY_FILTER);
ACTIV_REGISTER_MESSAGE_TYPE(42, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_SERIALIZED_PAYLOAD);
ACTIV_REGISTER_MESSAGE_TYPE(43, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_USER_ENABLE_BUFFER_TOKENS);
ACTIV_REGISTER_MESSAGE_TYPE(44, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_BUFFER_TOKEN);
ACTIV_REGISTER_MESSAGE_TYPE(45, MESSAGE_CLASS_ROUTER, ROUTER_MESSAGE_CONNECTION_TX_BYTES);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of MESSAGE_CLASS_SERVICE message types.
*/
ACTIV_REGISTER_MESSAGE_TYPE(0, MESSAGE_CLASS_SERVICE, SERVICE_MESSAGE_REGISTER);
ACTIV_REGISTER_MESSAGE_TYPE(1, MESSAGE_CLASS_SERVICE, SERVICE_MESSAGE_DEREGISTER);
ACTIV_REGISTER_MESSAGE_TYPE(2, MESSAGE_CLASS_SERVICE, SERVICE_MESSAGE_UPDATE_ATTRIBUTES);
ACTIV_REGISTER_MESSAGE_TYPE(3, MESSAGE_CLASS_SERVICE, SERVICE_MESSAGE_REMOTE_REGISTER);
ACTIV_REGISTER_MESSAGE_TYPE(4, MESSAGE_CLASS_SERVICE, SERVICE_MESSAGE_REMOTE_DEREGISTER);
ACTIV_REGISTER_MESSAGE_TYPE(5, MESSAGE_CLASS_SERVICE, SERVICE_MESSAGE_REMOTE_UPDATE_ATTRIBUTES);
ACTIV_REGISTER_MESSAGE_TYPE(6, MESSAGE_CLASS_SERVICE, SERVICE_MESSAGE_DIRECTORY_ANNOUNCEMENT);
ACTIV_REGISTER_MESSAGE_TYPE(7, MESSAGE_CLASS_SERVICE, SERVICE_MESSAGE_DIRECTORY_DISCOVERY);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of MESSAGE_CLASS_SERVICE request types.
*/
ACTIV_REGISTER_REQUEST_TYPE(0, MESSAGE_CLASS_SERVICE, SERVICE_REQUEST_FIND_SERVICES);
ACTIV_REGISTER_REQUEST_TYPE(1, MESSAGE_CLASS_SERVICE, SERVICE_REQUEST_INITIAL_CLONE_REMOTE_DATABASE);
ACTIV_REGISTER_REQUEST_TYPE(2, MESSAGE_CLASS_SERVICE, SERVICE_REQUEST_CONTINUE_CLONE_REMOTE_DATABASE);
ACTIV_REGISTER_REQUEST_TYPE(3, MESSAGE_CLASS_SERVICE, SERVICE_REQUEST_ADD_DIRECTORY_SERVICE_ATTRIBUTE);
ACTIV_REGISTER_REQUEST_TYPE(4, MESSAGE_CLASS_SERVICE, SERVICE_REQUEST_ADD_REMOTE_DIRECTORY_SERVICE_ATTRIBUTE_QUERY);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of MESSAGE_CLASS_UI request types.
*/
ACTIV_REGISTER_REQUEST_TYPE(0, MESSAGE_CLASS_UI, UI_REQUEST_NEW_USER);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of MESSAGE_CLASS_UI message types.
*/
ACTIV_REGISTER_MESSAGE_TYPE(0, MESSAGE_CLASS_UI, UI_MESSAGE_REGISTER_COMPONENT);
ACTIV_REGISTER_MESSAGE_TYPE(1, MESSAGE_CLASS_UI, UI_MESSAGE_DEREGISTER_COMPONENT);
ACTIV_REGISTER_MESSAGE_TYPE(2, MESSAGE_CLASS_UI, UI_MESSAGE_USER_INPUT);
ACTIV_REGISTER_MESSAGE_TYPE(3, MESSAGE_CLASS_UI, UI_MESSAGE_DESTROY);
ACTIV_REGISTER_MESSAGE_TYPE(4, MESSAGE_CLASS_UI, UI_MESSAGE_OUTPUT);
ACTIV_REGISTER_MESSAGE_TYPE(5, MESSAGE_CLASS_UI, UI_MESSAGE_SWITCH_TO_COMPONENT);
ACTIV_REGISTER_MESSAGE_TYPE(6, MESSAGE_CLASS_UI, UI_MESSAGE_RETURN_TO_MAIN_COMPONENT);
ACTIV_REGISTER_MESSAGE_TYPE(7, MESSAGE_CLASS_UI, UI_MESSAGE_RESET_MENU);
ACTIV_REGISTER_MESSAGE_TYPE(8, MESSAGE_CLASS_UI, UI_MESSAGE_LOG_OUTPUT);
ACTIV_REGISTER_MESSAGE_TYPE(9, MESSAGE_CLASS_UI, UI_MESSAGE_SHARED_OUTPUT);
ACTIV_REGISTER_MESSAGE_TYPE(10, MESSAGE_CLASS_UI, UI_MESSAGE_SHARED_SESSION_CLOSED);
ACTIV_REGISTER_MESSAGE_TYPE(11, MESSAGE_CLASS_UI, UI_MESSAGE_PARTIAL_USER_INPUT);
ACTIV_REGISTER_MESSAGE_TYPE(12, MESSAGE_CLASS_UI, UI_MESSAGE_SET_INPUT);
ACTIV_REGISTER_MESSAGE_TYPE(13, MESSAGE_CLASS_UI, UI_MESSAGE_UNBUFFERED_OUTPUT);
ACTIV_REGISTER_MESSAGE_TYPE(14, MESSAGE_CLASS_UI, UI_MESSAGE_CLEAR_INPUT);
ACTIV_REGISTER_MESSAGE_TYPE(15, MESSAGE_CLASS_UI, UI_MESSAGE_USER_UPDATE);
ACTIV_REGISTER_MESSAGE_TYPE(16, MESSAGE_CLASS_UI, UI_MESSAGE_INITIATE_TUNNEL);
ACTIV_REGISTER_MESSAGE_TYPE(17, MESSAGE_CLASS_UI, UI_MESSAGE_CLOSE_TUNNEL);
ACTIV_REGISTER_MESSAGE_TYPE(18, MESSAGE_CLASS_UI, UI_MESSAGE_COMPONENT_LIST);
ACTIV_REGISTER_MESSAGE_TYPE(19, MESSAGE_CLASS_UI, UI_MESSAGE_PROMPT);
ACTIV_REGISTER_MESSAGE_TYPE(20, MESSAGE_CLASS_UI, UI_MESSAGE_LOG_OPTION_SELECTION);
ACTIV_REGISTER_MESSAGE_TYPE(21, MESSAGE_CLASS_UI, UI_MESSAGE_RESET_COMPONENT);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Messages used internally by udp users (pub sub, udp transmitter etc).
*/
ACTIV_REGISTER_MESSAGE_TYPE(0, MESSAGE_CLASS_UDP, UDP_MESSAGE_DATA);
ACTIV_REGISTER_MESSAGE_TYPE(1, MESSAGE_CLASS_UDP, UDP_MESSAGE_SOCKET_OPEN);
ACTIV_REGISTER_MESSAGE_TYPE(2, MESSAGE_CLASS_UDP, UDP_MESSAGE_SOCKET_CLOSED);
ACTIV_REGISTER_MESSAGE_TYPE(3, MESSAGE_CLASS_UDP, UDP_MESSAGE_SHUTDOWN);
ACTIV_REGISTER_MESSAGE_TYPE(4, MESSAGE_CLASS_UDP, UDP_MESSAGE_FLUSH);
ACTIV_REGISTER_MESSAGE_TYPE(6, MESSAGE_CLASS_UDP, UDP_MESSAGE_NON_CRITICAL_DATA);
ACTIV_REGISTER_MESSAGE_TYPE(7, MESSAGE_CLASS_UDP, UDP_MESSAGE_RETRANSMIT);
ACTIV_REGISTER_MESSAGE_TYPE(8, MESSAGE_CLASS_UDP, UDP_MESSAGE_RETRANSMISSION_PORT_CHANGE);
//ACTIV_REGISTER_MESSAGE_TYPE(9, MESSAGE_CLASS_UDP, UDP_MESSAGE_PUBSUB_DATA);
ACTIV_REGISTER_MESSAGE_TYPE(10, MESSAGE_CLASS_UDP, UDP_MESSAGE_SOURCE_STATE);
ACTIV_REGISTER_MESSAGE_TYPE(11, MESSAGE_CLASS_UDP, UDP_MESSAGE_RETRANSMISSION_INFO);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Requests used internally by udp users (pub sub, udp transmitter etc).
*/
ACTIV_REGISTER_REQUEST_TYPE(0, MESSAGE_CLASS_UDP, UDP_REQUEST_GET_STATS);
ACTIV_REGISTER_REQUEST_TYPE(1, MESSAGE_CLASS_UDP, UDP_REQUEST_IS_RETRANSMISSION_ENABLED);
ACTIV_REGISTER_REQUEST_TYPE(2, MESSAGE_CLASS_UDP, UDP_REQUEST_ENABLE_RETRANSMISSION);
ACTIV_REGISTER_REQUEST_TYPE(3, MESSAGE_CLASS_UDP, UDP_REQUEST_DISABLE_RETRANSMISSION);
ACTIV_REGISTER_REQUEST_TYPE(4, MESSAGE_CLASS_UDP, UDP_REQUEST_GET_PREVIOUS_STATS);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Messages used internally by rdma.
*/
ACTIV_REGISTER_MESSAGE_TYPE(0, MESSAGE_CLASS_RDMA, RDMA_MESSAGE_ASYNC_EVENT);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Messages used internally by Packet Server.
*/
ACTIV_REGISTER_MESSAGE_TYPE(0, MESSAGE_CLASS_PACKET_SERVER, PACKET_SERVER_RESPONSE);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Requests used internally by the replication service.
*/
ACTIV_REGISTER_REQUEST_TYPE(0, MESSAGE_CLASS_REPLICATOR, REPLICATOR_REQUEST_OPEN_LOG_FILE);
ACTIV_REGISTER_REQUEST_TYPE(1, MESSAGE_CLASS_REPLICATOR, REPLICATOR_REQUEST_LOG_MESSAGE);
ACTIV_REGISTER_REQUEST_TYPE(2, MESSAGE_CLASS_REPLICATOR, REPLICATOR_REQUEST_GET_MESSAGES);
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_MESSAGE_TYPES_H)
@@ -1,87 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/Messages.h
*
* @brief Header file for exported framework message classes.
*/
#if (!defined ACTIV_FRAMEWORK_MESSAGES_H)
#define ACTIV_FRAMEWORK_MESSAGES_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/ISerializableMessage.h"
#include "ActivMiddleware/ActivFramework/ServiceId.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Open service request.
*/
class OpenServiceRequest : public ISerializableMessage
{
public:
/**
* @brief Default constructor.
*
* m_version is set to m_currentVersion, but can be overridden if required.
*/
ACTIV_FRAMEWORK_API OpenServiceRequest();
ACTIV_FRAMEWORK_API virtual StatusCode Serialize(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual StatusCode Deserialize(MessageValidator &messageValidator) ACTIV_OVERRIDE;
static const byte_t m_highestVersion = 3; ///< Highest supported version.
ACTIV_FRAMEWORK_API static const byte_t m_currentVersion; ///< Current version used by client side.
byte_t m_version;
ServiceId m_serviceId;
private:
StatusCode SerializeGeneric(MessageBuilder &messageBuilder) const;
StatusCode SerializeVersioned(MessageBuilder &messageBuilder) const;
StatusCode DeserializeGeneric(MessageValidator &messageValidator);
StatusCode DeserializeVersioned(MessageValidator &messageValidator);
class Message;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Open service response. The response implicitly matches the version of the request.
*/
class OpenServiceResponse : public ISerializableMessage
{
public:
/**
* @brief Default constructor.
*/
ACTIV_FRAMEWORK_API OpenServiceResponse();
/**
* @brief Constructor.
*
* @param serviceId id for the service.
*/
ACTIV_FRAMEWORK_API OpenServiceResponse(const ServiceId &serviceId);
ACTIV_FRAMEWORK_API virtual StatusCode Serialize(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual StatusCode Deserialize(MessageValidator &messageValidator) ACTIV_OVERRIDE;
ServiceId m_serviceId;
private:
StatusCode SerializeGeneric(MessageBuilder &messageBuilder) const;
StatusCode SerializeVersioned(MessageBuilder &messageBuilder) const;
StatusCode DeserializeGeneric(MessageValidator &messageValidator);
StatusCode DeserializeVersioned(MessageValidator &messageValidator);
class Message;
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_MESSAGES_H)
@@ -1,99 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/NetworkAffinityFilterApi.h
*
* @brief Header file for the network affinity filter api.
*/
#if (!defined ACTIV_FRAMEWORK_NETWORK_AFFINITY_FILTER_API_H)
#define ACTIV_FRAMEWORK_NETWORK_AFFINITY_FILTER_API_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/CxxYZ/memory.h"
//! Activ namespace.
namespace Activ
{
class Component;
class NetworkAffinityFilter;
// ---------------------------------------------------------------------------------------------------------------------------------
//! Api to the agent's network affinity filter service.
class NetworkAffinityFilterApi
{
public:
//! Scoped filter class.
class ScopedFilter
{
public:
/**
* @brief Constructor.
*
* @param component
*/
ACTIV_FRAMEWORK_API ScopedFilter(const Component &component);
//! Destructor.
ACTIV_FRAMEWORK_API ~ScopedFilter();
/**
* @brief Add filter.
*
* @param networkAffinityFilter
* @param shouldSendSyncRequest
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode AddFilter(const NetworkAffinityFilter &networkAffinityFilter,
const bool shouldSendSyncRequest = true);
/**
* @brief Remove filter.
*
* @param shouldSendSyncRequest
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode RemoveFilter(const bool shouldSendSyncRequest = true);
//! Get network affinity filter.
ACTIV_FRAMEWORK_API const NetworkAffinityFilter &GetNetworkAffinityFilter() const;
//! Is active.
ACTIV_FRAMEWORK_API bool IsActive() const;
private:
const Component & m_component;
CxxYZ::unique_ptr<NetworkAffinityFilter> m_pNetworkAffinityFilter;
};
/**
* @brief Add network affinity filter.
*
* @param component component to send the message from.
* @param networkAffinityFilter
* @param shouldSendSyncRequest
*
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode AddFilter(const Component &component,
const NetworkAffinityFilter &networkAffinityFilter, const bool shouldSendSyncRequest = true);
/**
* @brief Remove network affinity filter.
*
* @param component component to send the message from.
* @param networkAffinityFilter
* @param shouldSendSyncRequest
*
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode RemoveFilter(const Component &component,
const NetworkAffinityFilter &networkAffinityFilter, const bool shouldSendSyncRequest = true);
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_NETWORK_AFFINITY_FILTER_API_H)
@@ -1,367 +0,0 @@
/**
* @file source/ActivMiddleware/ActivFramework/PacketServerHelper.h
*
* @brief Header file for Packet Server Messages, Subscriber and Publisher.
*/
#if (!defined ACTIV_FRAMEWORK_PACKET_SERVER_HELPER_H)
#define ACTIV_FRAMEWORK_PACKET_SERVER_HELPER_H
#include "ActivMiddleware/ActivBase/ISerializableMessage.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include "ActivMiddleware/ActivBase/MessageValidator.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include "ActivMiddleware/ActivFramework/ManagedEndPoint.h"
//! Activ namespace.
namespace Activ
{
namespace PacketServerHelper
{
/**
* @brief The list of possible packet server request types and their strings.
*
* Note this list is converted to an enum using the ACTIV_DECLARE_ELEMENT_1 macro in ActivMiddleware.h
*/
#define ACTIV_FRAMEWORK_PACKET_SERVER_REQUEST_LIST(d) \
d(PACKET_SERVER_SUBSCRIBER, "subscriber") \
d(PACKET_SERVER_PUBLISHER, "publisher") \
d(PACKET_SERVER_UNKNOWN, "unknown")
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief The list of possible packet server tcp connection states and their strings.
*
* Note this list is converted to an enum using the ACTIV_DECLARE_ELEMENT_1 macro in ActivMiddleware.h
*/
#define PACKET_SERVER_CONNECTION_STATES(d) \
d(STATE_UNKNOWN, "Unknown") \
d(STATE_INITIALIZED, "Initialized") \
d(STATE_DISCONNECTED, "Disconnected") \
d(STATE_W4_CONNECT, "W4 Connect") \
d(STATE_W4_BREAK, "W4 Break") \
d(STATE_W4_DISCONNECT, "W4 Disconnect") \
d(STATE_CONNECTED, "Connected")
// ---------------------------------------------------------------------------------------------------------------------------------
//! The list of possible packet server tcp connection states and their strings.
enum State
{
PACKET_SERVER_CONNECTION_STATES(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
NUM_STATES
};
/**
* @brief Return tcp state name.
*
* @param state the state.
*
* @return tcp connection state description.
*/
ACTIV_FRAMEWORK_API const String &StateToString(State state);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Subscriber or publisher settings class.
*/
class Settings
{
public:
static const uint32_t defaultSwitchTimeout = 5;
static const uint32_t defaultConnectFailSleep = 5;
/**
* @brief Default constructor.
*/
ACTIV_FRAMEWORK_API Settings();
/**
* @brief Return true if is initialized.
*
* @retval true if packet server subscriber setting is initialized.
* @retval false if packet server subscriber setting is not initialized.
*/
ACTIV_FRAMEWORK_API bool IsInitialized() const;
/**
* @brief Read settings from ini file.
*
* @param section Ini file section to read.
* @param prefix the prefix for INI key.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API void Read(const IniFileParser::ConstSectionIterator &section, const String &prefix = String());
String m_name; ///< Name of connection.
std::vector<String> m_tcpUrls; ///< Input url of tcp server to connect to.
uint32_t m_switchTimeout; ///< Time to wait before switching when no data received.
uint32_t m_connectFailSleep; ///< How long to sleep when we fail to connect to all urls.
uint32_t m_ttl; ///< Default: 30. Time to live.
IHeap::Settings m_heapSettings; ///< The heap settings.
};
/**
* @brief Packet Server request message from publisher or subscriber to Packet Server.
*/
class PacketServerRequest : public ISerializableMessage
{
public:
/**
* @brief Enumeration of all packet server request types.
*/
enum Type
{
ACTIV_FRAMEWORK_PACKET_SERVER_REQUEST_LIST(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
NUM_TYPES
};
/**
* @brief Constructor.
*
* @param requestType the request type (subscriber / publisher).
* @param clientIpAddress the ip address of requestor (subscriber / publisher).
* @param name the name. For same publisher name there is same udp output port.
*/
ACTIV_FRAMEWORK_API PacketServerRequest(const Type requestType = PACKET_SERVER_UNKNOWN,
const IpAddress &clientIpAddress = IpAddress(), const String &name = String());
/**
* @brief Constructor.
*/
ACTIV_FRAMEWORK_API virtual ~PacketServerRequest() ACTIV_OVERRIDE;
/**
* @brief Serialize.
*
* @param messageBuilder the message builder.
*/
ACTIV_FRAMEWORK_API virtual StatusCode Serialize(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
/**
* @brief Deserialize.
*
* @param messageValidator the message validator.
*/
ACTIV_FRAMEWORK_API virtual StatusCode Deserialize(MessageValidator &messageValidator) ACTIV_OVERRIDE;
/**
* @brief Return request type name.
*
* @param type the request type.
*
* @return request type description.
*/
ACTIV_FRAMEWORK_API static const String &TypeToString(Type type);
Type m_requestType; ///< The request type.
IpAddress m_clientIpAddress; ///< The ip address of client.
String m_name; ///< The name.
private:
class Message;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Packet Server response message from Packet Server to subscriber or publisher.
*/
class PacketServerResponse : public ISerializableMessage
{
public:
/**
* @brief Constructor.
*
* @param serverIpAddress the packet server ip address.
*/
ACTIV_FRAMEWORK_API PacketServerResponse(const IpAddress &serverIpAddress = IpAddress());
/**
* @brief Constructor.
*
* @param message the message.
*/
ACTIV_FRAMEWORK_API PacketServerResponse(const HeapMessage &message);
/**
* @brief Constructor.
*/
ACTIV_FRAMEWORK_API virtual ~PacketServerResponse() ACTIV_OVERRIDE;
/**
* @brief Serialize.
*
* @param messageBuilder the message builder.
*/
ACTIV_FRAMEWORK_API virtual StatusCode Serialize(MessageBuilder &messageBuilder) const ACTIV_OVERRIDE;
/**
* @brief Deserialize.
*
* @param messageValidator the message validator.
*/
ACTIV_FRAMEWORK_API virtual StatusCode Deserialize(MessageValidator &messageValidator) ACTIV_OVERRIDE;
IpAddress m_serverIpAddress; ///< The ip address of the packet server.
private:
class Message;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
class PacketServerCommonImpl;
/**
* @brief Packet server publisher class. Connect to udp Packet Server application.
*/
class Publisher
{
public:
typedef CxxYZ::function<void(const IpAddress&)> OnRemoteUdpIpAddress;
/**
* @brief Constructor.
*
* @param name the name. For same publisher name there is same udp output port.
* @param managedEndPoint endpoint to receive messages on.
* @param settings the packet server settings.
* @param timeout if nonzero timeout initiate a synchronous connect. If timeout zero then initiate an asynchronous connect.
* @param onRemoteUdpIpAddress event functor called when remote udp packet server ip address provided.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API Publisher(const String &name, ManagedEndPoint &managedEndPoint,
const PacketServerHelper::Settings &settings, const TimeoutPeriod timeout = 0,
OnRemoteUdpIpAddress onRemoteUdpIpAddress = OnRemoteUdpIpAddress());
//! Destructor.
ACTIV_FRAMEWORK_API virtual ~Publisher();
//! Perform shutdown work.
ACTIV_FRAMEWORK_API void Shutdown();
//! Get settings.
ACTIV_FRAMEWORK_API const PacketServerHelper::Settings &GetSettings() const;
//! Get remote udp packet server ip address.
ACTIV_FRAMEWORK_API const IpAddress &GetRemoteUdpIpAddress();
/**
* @brief Returns current tcp connecntion url.
*
* @return Current tcp connection url.
*
* @throw StatusCodeException.
*/
ACTIV_FRAMEWORK_API const String &GetCurrentUrl() const;
/**
* @brief Returns current tcp connecntion url index.
*
* @return Current tcp connection url index.
*/
ACTIV_FRAMEWORK_API size_t GetCurrentUrlIndex() const;
//! Return current state.
ACTIV_FRAMEWORK_API State GetState() const;
/**
* @brief Break existing tcp connection end connect to new url index.
*
* @param urlIndex new url index.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SwitchUrl(const size_t urlIndex);
private:
CxxYZ::unique_ptr<PacketServerCommonImpl> m_pImpl; ///< Implementation details.
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Packet server subscriber class. Connect to udp Packet Server application.
*/
class Subscriber
{
public:
typedef CxxYZ::function<StatusCode(const void * const, const size_t, const IpAddress &)> UdpPostFunction;
/**
* @brief Constructor.
*
* @param managedEndPoint endpoint to receive messages on.
* @param settings the settings for the packet server subscriber.
* @param interfaceAddress the interface address.
* @param portNumber the port number.
* @param timeout On nonzero timeout initiate a synchronous connect. If timeout zero then initiate an asynchronous connect.
* @param udpPostFunction the udp post function.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API Subscriber(ManagedEndPoint &managedEndPoint, const PacketServerHelper::Settings &settings,
const String &interfaceAddress, const uint16_t portNumber, const TimeoutPeriod timeout = 0,
UdpPostFunction udpPostFunction = UdpPostFunction());
//! Destructor.
ACTIV_FRAMEWORK_API virtual ~Subscriber();
//! Perform shutdown work.
ACTIV_FRAMEWORK_API void Shutdown();
//! Get settings.
ACTIV_FRAMEWORK_API const PacketServerHelper::Settings &GetSettings() const;
/**
* @brief Returns current tcp connecntion url.
*
* @return Current tcp connection url.
*
* @throw StatusCodeException.
*/
ACTIV_FRAMEWORK_API const String &GetCurrentUrl() const;
/**
* @brief Returns current tcp connecntion url index.
*
* @return Current tcp connection url index.
*/
ACTIV_FRAMEWORK_API size_t GetCurrentUrlIndex() const;
//! Return current state.
ACTIV_FRAMEWORK_API State GetState() const;
/**
* @brief Break existing tcp connection end connect to new url index.
*
* @param urlIndex new url index.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SwitchUrl(const size_t urlIndex);
private:
CxxYZ::unique_ptr<PacketServerCommonImpl> m_pImpl; ///< Implementation details.
};
} // namespace PacketServerHelper
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_PACKET_SERVER_HELPER_H)
@@ -1,847 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/PostMessageHelper.h
*
* @brief Header file for PostMessageHelper.
*/
#if (!defined ACTIV_FRAMEWORK_POST_MESSAGE_HELPER_H)
#define ACTIV_FRAMEWORK_POST_MESSAGE_HELPER_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/Component.h"
#include "ActivMiddleware/ActivFramework/HeapMessage.h"
#include "ActivMiddleware/ActivBase/IniFileParser.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include "ActivMiddleware/CxxYZ/memory.h"
//! Activ namespace.
namespace Activ
{
class EndPoint;
class SystemImpl;
class ManagedEndPointImpl;
/**
* @brief Helper class to post messages.
*
* This class provides a similar interface to the Component message posting functions. In addition,
* it will post multiple messages to a target endpoint in one go, saving multiple acquiring
* of locks, kernel transitions, etc.
*
* The intended use is when the processing of a single message will result in the sending of
* multiple messages. For example:
*
* MyComponent::ProcessMyMessage(heapMessage)
* {
* for (...)
* {
* HeapMessage heapMessage2;
* heapMessage2.Clone(heapMessage);
* m_postMessageHelper.PostMessage(*this, m_targetAddress, MY_TYPE, heapMessage2);
* }
* m_postMessageHelper.Flush();
* }
*
* The class is not thread-safe and is only intended to be used from a single thread.
*/
class PostMessageHelper : private Boost::noncopyable
{
public:
//! PostMessageHelper Flush() helper.
class ScopedFlush : private Boost::noncopyable
{
public:
/**
* @brief Constructor.
*
* @param postMessageHelper
*/
ScopedFlush(PostMessageHelper &postMessageHelper);
/**
* @brief Destructor.
*
* Calls Flush() on the PostMessageHelper passed to the constructor.
*/
~ScopedFlush();
private:
PostMessageHelper &m_postMessageHelper;
};
//! Scoped PostMessageHelper TryFlush() helper.
class ScopedTryFlush : private Boost::noncopyable
{
public:
/**
* @brief Constructor.
*
* @param postMessageHelper
*/
ScopedTryFlush(PostMessageHelper &postMessageHelper);
/**
* @brief Destructor.
*
* Calls TryFlush() on the PostMessageHelper passed to the constructor.
*/
~ScopedTryFlush();
private:
PostMessageHelper &m_postMessageHelper;
};
//! Settings.
class Settings
{
public:
//! Default constructor.
ACTIV_FRAMEWORK_API
Settings();
/**
* @brief Read settings from an ini-file section.
*
* @param sectionIterator
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API
void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
UInt m_maximumNumberOfFailedTryFlushes; ///< Default: 8. How many TryFlush() calls should fail before TryFlush() calls Flush() implicitly. Ini-file key: MaxFailedTryFlushes
UInt m_maximumNumberOfPostsBeforeImplicitFlush; ///< Default: undefined (no limit; otherwise implicitly Flush() or TryFlush() after this number of any PostMessage() calls). Ini-file key: MaxPostsBeforeFlush
bool m_shouldTryFlushAfterMaximumPosts; ///< Default: false (Flush() rather than TryFlush() when m_maximumNumberOfPostsBeforeImplicitFlush PostMessage()s have been called). Ini-file key: ShouldTryFlushAfterMaxPosts
bool m_shouldProcessEndPointsUntilFailureOnTryFlush; ///< Default: true. When true endpoint iteration during a TryFlush is repeated until none succeed or all are empty. Ini-file key: ProcessEndPointsUntilFailureOnTryFlush
};
//! Statistics.
class Statistics
{
public:
//! Default constructor.
ACTIV_FRAMEWORK_API
Statistics();
//! Reset.
ACTIV_FRAMEWORK_API
void Reset();
size_t m_numberOfForcedFlushesDuringTryFlush; ///< Number of times a TryFlush has resulted in a forced flush to an endpoint.
};
/**
* @brief Constructor.
*
* @param managedEndPoint the ManagedEndPoint containing all Components from which messages are to be sent.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API
explicit PostMessageHelper(const ManagedEndPoint &managedEndPoint);
/**
* @brief Constructor.
*
* @param managedEndPoint the ManagedEndPoint containing all Components from which messages are to be sent.
* @param settings
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API
explicit PostMessageHelper(const ManagedEndPoint &managedEndPoint, const Settings &settings);
/**
* @brief Constructor.
*
* @param managedEndPoint the ManagedEndPoint containing all Components from which messages are to be sent.
* @param maximumNumberOfFailedTryFlushes how many TryFlush() calls should fail before TryFlush() calls Flush() implicitly.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API
explicit PostMessageHelper(const ManagedEndPoint &managedEndPoint, const size_t maximumNumberOfFailedTryFlushes);
//! Destructor.
ACTIV_FRAMEWORK_API
~PostMessageHelper();
/**
* @brief Post an asynchronous request.
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param requestType the request type.
* @param requestId the message identification (to match up the response).
* @param messageBuilder reference to a MessageBuilder containing the message body to post.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
*/
StatusCode PostRequest(const Component &component, const Address &destinationAddress, const MessageType requestType,
const RequestId &requestId, const MessageBuilder &messageBuilder);
/**
* @brief Post an asynchronous request.
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param requestType the request type.
* @param requestId the message identification (to match up the response).
* @param pRequest the request message buffer.
* @param requestLength the length of the request message buffer.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
*/
StatusCode PostRequest(const Component &component, const Address &destinationAddress, const MessageType requestType,
const RequestId &requestId, const void *pRequest = ACTIV_NULLPTR, const size_t requestLength = 0);
/**
* @brief Post an asynchronous request.
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param requestType the request type.
* @param requestId the message identification (to match up the response).
* @param request the HeapMessage containing the request body.
*/
ACTIV_FRAMEWORK_API
void PostRequest(const Component &component, const Address &destinationAddress, const MessageType requestType,
const RequestId &requestId, HeapMessage &request);
/**
* @brief Send a synchronous request and wait for the response.
*
* If this returns STATUS_CODE_SUCCESS, the value of response.GetStatusCode()
* will contain the actual return status of the request (the return value from SendRequest() just
* determines whether the actual message transmission was successful).
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param requestType the request type.
* @param messageBuilder reference to a MessageBuilder containing the message body to post.
* @param response HeapMessage to receive the response.
* @param timeout in milliseconds.
*
* @retval STATUS_CODE_SUCCESS a response has been received.
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
* @retval STATUS_CODE_TIMEOUT no response received in the timeout period.
*/
ACTIV_FRAMEWORK_API
StatusCode SendRequest(const Component &component, const Address &destinationAddress, const MessageType requestType,
const MessageBuilder &messageBuilder, HeapMessage &response, const TimeoutPeriod timeout = Component::defaultTimeout);
/**
* @brief Send a synchronous request and wait for the response.
*
* If this returns STATUS_CODE_SUCCESS, the value of response.GetStatusCode()
* will contain the actual return status of the request (the return value from SendRequest() just
* determines whether the actual message transmission was successful).
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param requestType the request type.
* @param pRequest the request message buffer.
* @param requestLength the length of the request message buffer.
* @param response HeapMessage to receive the response.
* @param timeout in milliseconds.
*
* @retval STATUS_CODE_SUCCESS a response has been received.
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
* @retval STATUS_CODE_TIMEOUT no response received in the timeout period.
*/
ACTIV_FRAMEWORK_API
StatusCode SendRequest(const Component &component, const Address &destinationAddress, const MessageType requestType,
const void *pRequest, const size_t requestLength, HeapMessage &response,
const TimeoutPeriod timeout = Component::defaultTimeout);
/**
* @brief Send a synchronous request and wait for the response.
*
* If this returns STATUS_CODE_SUCCESS, the value of request.GetStatusCode()
* will contain the actual return status of the request (the return value from SendRequest() just
* determines whether the actual message transmission was successful).
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param requestType the request type.
* @param request the request message and container for the response. If request is an empty HeapMessage, a
* request will be sent with no message body.
* @param timeout in milliseconds.
*
* @retval STATUS_CODE_SUCCESS a response has been received.
* @retval STATUS_CODE_HEAP_EMPTY if request was empty and no message could be allocated for the outgoing request.
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
* @retval STATUS_CODE_TIMEOUT no response received in the timeout period.
*/
ACTIV_FRAMEWORK_API
StatusCode SendRequest(const Component &component, const Address &destinationAddress, const MessageType requestType,
HeapMessage &request, const TimeoutPeriod timeout = Component::defaultTimeout);
/**
* @brief Send a synchronous request but do not wait for the response.
*
* If this returns STATUS_CODE_SUCCESS, the response can be obtained by calling syncRequestId.GetResponse().
* The actual return status of the request can then be obtained by GetStatusCode() on the message returned from
* syncRequestId.GetResponse().
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param requestType the request type.
* @param syncRequestId reference to a SyncRequestId object that can be used later to wait (or poll) for the response.
* @param messageBuilder reference to a MessageBuilder containing the message body to post.
*
* @retval STATUS_CODE_SUCCESS the request was sent successfully.
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
*/
ACTIV_FRAMEWORK_API
StatusCode SendRequest(const Component &component, const Address &destinationAddress, const MessageType requestType,
SyncRequestId &syncRequestId, const MessageBuilder &messageBuilder);
/**
* @brief Send a synchronous request but do not wait for the response.
*
* If this returns STATUS_CODE_SUCCESS, the response can be obtained by calling syncRequestId.GetResponse().
* The actual return status of the request can then be obtained by GetStatusCode() on the message returned from
* syncRequestId.GetResponse().
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param requestType the request type.
* @param syncRequestId reference to a SyncRequestId object that can be used later to wait (or poll) for the response.
* @param pRequest the request message buffer.
* @param requestLength the length of the request message buffer.
*
* @retval STATUS_CODE_SUCCESS the request was sent successfully.
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
*/
ACTIV_FRAMEWORK_API
StatusCode SendRequest(const Component &component, const Address &destinationAddress, const MessageType requestType,
SyncRequestId &syncRequestId, const void *pRequest, const size_t requestLength);
/**
* @brief Send a synchronous request but do not wait for the response.
*
* If this returns STATUS_CODE_SUCCESS, the response can be obtained by calling syncRequestId.GetResponse().
* The actual return status of the request can then be obtained by GetStatusCode() on the message returned from
* syncRequestId.GetResponse().
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param requestType the request type.
* @param syncRequestId reference to a SyncRequestId object that can be used later to wait (or poll) for the response.
* @param request the request message. If request is an empty HeapMessage, a
* request will be sent with no message body.
*
* @retval STATUS_CODE_SUCCESS the request was sent successfully.
* @retval STATUS_CODE_HEAP_EMPTY if request was empty and no message could be allocated for the outgoing request.
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
*/
ACTIV_FRAMEWORK_API
StatusCode SendRequest(const Component &component, const Address &destinationAddress, const MessageType requestType,
SyncRequestId &syncRequestId, HeapMessage &request);
/**
* @brief Post a response to a request.
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address (the source address of the request).
* @param requestType the request type.
* @param requestId the message identification (to match up the response).
* @param responseStatus the response status.
* @param messageBuilder reference to a MessageBuilder containing the message body to post.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
*/
StatusCode PostResponse(const Component &component, const Address &destinationAddress, const MessageType requestType,
const RequestId &requestId, const StatusCode responseStatus, const MessageBuilder &messageBuilder);
/**
* @brief Post a response to a request.
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address (the source address of the request).
* @param requestType the request type.
* @param requestId the message identification (to match up the response).
* @param responseStatus the response status.
* @param pResponse the response message buffer.
* @param responseLength the length of the response message buffer.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
*/
StatusCode PostResponse(const Component &component, const Address &destinationAddress, const MessageType requestType,
const RequestId &requestId, const StatusCode responseStatus, const void *pResponse = ACTIV_NULLPTR,
const size_t responseLength = 0);
/**
* @brief Post a response to a request. Use this call when the response message is a newly allocated
* HeapMessage and is not the original request.
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address (the source address of the request).
* @param requestType the request type.
* @param requestId the message identification (to match up the response).
* @param responseStatus the response status.
* @param response the response message.
*/
ACTIV_FRAMEWORK_API
void PostResponse(const Component &component, const Address &destinationAddress, const MessageType requestType,
const RequestId &requestId, const StatusCode responseStatus, HeapMessage &response);
/**
* @brief Post a response to a request where the request HeapMessage still has the original request id
* and message type of the request. The contents of the request HeapMessage are overridden with
* the provided MessageBuilder contents.
*
* @param component reference to the Component to post from.
* @param responseStatus the response status.
* @param request the original request.
* @param messageBuilder reference to a MessageBuilder containing the message body to post.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
*/
StatusCode PostResponse(const Component &component, const StatusCode responseStatus, HeapMessage &request,
const MessageBuilder &messageBuilder);
/**
* @brief Post a response to a request where the request HeapMessage still has the original request id
* and message type of the request. The contents of the request HeapMessage are overridden with
* the provided buffer.
*
* @param component reference to the Component to post from.
* @param responseStatus the response status.
* @param request the original request.
* @param pResponse the response message buffer.
* @param responseLength the length of the response message buffer.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
* @retval STATUS_CODE_INVALID_ENDPOINT the destination endpoint does not exist.
* @retval STATUS_CODE_DISABLED the endpoint is not accepting messages.
*/
StatusCode PostResponse(const Component &component, const StatusCode responseStatus, HeapMessage &request,
const void *pResponse, const size_t responseLength);
/**
* @brief Post a response to a request where the request HeapMessage still has the original request id
* and message type of the request. The provided response HeapMessage contains the response body.
*
* @param component reference to the Component to post from.
* @param responseStatus the response status.
* @param request the original request.
* @param response a second HeapMessage containing the response body.
*/
void PostResponse(const Component &component, const StatusCode responseStatus, HeapMessage &request, HeapMessage &response);
/**
* @brief Post a response to a request where the original request message has been filled in with the response.
* All other members of the response message must be as received (request id, type, addresses).
*
* @param component reference to the Component to post from.
* @param responseStatus the response status.
* @param request the original request message filled in with the response data.
*/
ACTIV_FRAMEWORK_API
void PostResponse(const Component &component, const StatusCode responseStatus, HeapMessage &request);
/**
* @brief Post an empty response to a request. The response will be sent to the source address of the request.
*
* If replying to a request and the contents of the response are unimportant, it is preferable to use PostEmptyResponse()
* as if the request was made remotely, there will be no serializing of message body over the network.
*
* @param component reference to the Component to post from.
* @param responseStatus the response status.
* @param request the original request message. Any data in the message is truncated.
*/
void PostEmptyResponse(const Component &component, const StatusCode responseStatus, HeapMessage &request);
/**
* @brief Post an empty response to a request. Use this call when the response message is a newly allocated
* HeapMessage and is not the original request.
*
* If replying to a request and the contents of the response are unimportant, it is preferable to use PostEmptyResponse()
* as if the request was made remotely, there will be no serializing of message body over the network.
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address (the source address of the original request).
* @param requestType the request type of the original request.
* @param requestId the message identification (to match up the response).
* @param responseStatus the response status.
* @param response the response message. Data will be truncated.
*/
void PostEmptyResponse(const Component &component, const Address &destinationAddress, const MessageType requestType,
const RequestId &requestId, const StatusCode responseStatus, HeapMessage &response);
/**
* @brief Post a message, setting destination address and type.
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param messageType the message type.
* @param messageBuilder reference to a MessageBuilder containing the message body to post.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
*/
StatusCode PostMessage(const Component &component, const Address &destinationAddress, const MessageType messageType,
const MessageBuilder &messageBuilder);
/**
* @brief Post a message, setting destination address and type.
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param messageType the message type.
* @param pMessage the message buffer.
* @param messageLength the length of the message buffer.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMPTY
*/
StatusCode PostMessage(const Component &component, const Address &destinationAddress, const MessageType messageType,
const void *pMessage = ACTIV_NULLPTR, const size_t messageLength = 0);
/**
* @brief Post a message, setting destination address and type.
*
* @param component reference to the Component to post from.
* @param destinationAddress the target address.
* @param messageType the message type.
* @param message the message.
*/
ACTIV_FRAMEWORK_API
void PostMessage(const Component &component, const Address &destinationAddress, const MessageType messageType,
HeapMessage &message);
/**
* @brief Post a fully initialized message (type, src, dest addresses set as appropriate).
*
* @param heapMessage the message.
*/
ACTIV_FRAMEWORK_API
void PostMessage(HeapMessage &heapMessage);
//! Flush the queued messages to their target endpoints.
ACTIV_FRAMEWORK_API
void Flush();
/**
* @brief Try to flush the queued messages to their target endpoints.
*
* If unable to acquire the mutex protecting each target endpoint, messages are left queued in this object (the
* intention being that a later TryFlush() call will likely succeed).
*
* @return true if there is no data queued in this object.
*/
ACTIV_FRAMEWORK_API
bool TryFlush();
/**
* @brief Is the object empty?
*
* @return True if no messages are cached waiting to be flushed.
*/
bool IsEmpty() const;
//! Get statistics.
const Statistics &GetStatistics() const;
//! Reset statistics.
void ResetStatistics();
private:
//! Settings derived from those provided to the constructor.
class PrivateSettings
{
public:
PrivateSettings(const Settings &settings);
PrivateSettings(const size_t maximumNumberOfFailedTryFlushes);
size_t m_maximumNumberOfFailedTryFlushes;
size_t m_maximumNumberOfPostsBeforeImplicitFlush;
bool m_shouldTryFlushAfterMaximumPosts;
bool m_shouldProcessEndPointsUntilFailureOnTryFlush;
};
//! Info stored per endpoint.
class Info
{
public:
Info();
~Info();
CxxYZ::shared_ptr<EndPoint> m_pEndPoint;
size_t m_failedTryFlushCount;
bool m_isInUse;
};
/**
* @brief Extend lists and create local endpoint.
*
* @param endPointId
*
* @return IEndPoint.
*/
EndPoint *ExtendLists(const EndPointId endPointId);
/**
* @brief Create local endpoint.
*
* @param endPointId
* @param info
*
* @return IEndPoint.
*/
EndPoint *CreateLocalEndPoint(const EndPointId endPointId, Info &info);
/**
* @brief Add an endpoint id to the lists of in-use endpoints.
*
* @param endPointId
* @param info
*/
void AddEndPointIdToInUseList(const EndPointId endPointId, Info &info);
/**
* @brief Post a response message to an endpoint.
*
* This overrides the destination address if RequestId::ATTRIBUTE_USE_RESPONSE_ADDRESS is set in @a response.
*
* @param component reference to the Component to post from.
* @param response
*/
void PostResponse(const Component &component, HeapMessage &response);
/**
* @brief Flush a local endpoint before a sync call to that endpoint.
*
* @param endPointId if the target endpoint's local endpoint to flush. Range checked.
*/
void PreSyncFlush(const EndPointId endPointId);
/**
* @brief Flush a local endpoint.
*
* @param endPointId if the target endpoint's local endpoint to flush.
* @param info Info for @a endPointId.
*/
void InternalFlush(const EndPointId endPointId, Info &info);
typedef std::vector<Info> InfoList;
typedef std::vector<EndPointId> EndPointIdList;
const ManagedEndPointImpl & m_managedEndPointImpl;
SystemImpl & m_systemImpl;
const PrivateSettings m_settings;
InfoList m_infoList;
size_t m_infoListSize;
EndPointIdList m_endPointIdList;
EndPointIdList m_failedFlushEndPointIdList;
size_t m_numberOfUnflushedPosts;
Statistics m_statistics;
friend class ManagedEndPointImpl;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode PostMessageHelper::PostRequest(const Component &component, const Address &destinationAddress,
const MessageType requestType, const RequestId &requestId, const MessageBuilder &messageBuilder)
{
return PostRequest(component, destinationAddress, requestType, requestId, messageBuilder.GetMessage(),
messageBuilder.GetLength());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode PostMessageHelper::PostRequest(const Component &component, const Address &destinationAddress,
const MessageType requestType, const RequestId &requestId, const void *pRequest, const size_t requestLength)
{
HeapMessage request(*component.GetHeap(), pRequest, requestLength);
if (ACTIV_UNLIKELY(!request))
return STATUS_CODE_HEAP_EMPTY;
PostRequest(component, destinationAddress, requestType, requestId, request);
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode PostMessageHelper::PostResponse(const Component &component, const Address &destinationAddress,
const MessageType requestType, const RequestId &requestId, const StatusCode responseStatus,
const MessageBuilder &messageBuilder)
{
return PostResponse(component, destinationAddress, requestType, requestId, responseStatus, messageBuilder.GetMessage(),
messageBuilder.GetLength());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode PostMessageHelper::PostResponse(const Component &component, const Address &destinationAddress,
const MessageType requestType, const RequestId &requestId, const StatusCode responseStatus, const void *pResponse,
const size_t responseLength)
{
HeapMessage response(*component.GetHeap(), pResponse, responseLength);
if (!response)
return STATUS_CODE_HEAP_EMPTY;
PostResponse(component, destinationAddress, requestType, requestId, responseStatus, response);
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode PostMessageHelper::PostResponse(const Component &component, const StatusCode responseStatus, HeapMessage &request,
const MessageBuilder &messageBuilder)
{
return PostResponse(component, responseStatus, request, messageBuilder.GetMessage(), messageBuilder.GetLength());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode PostMessageHelper::PostResponse(const Component &component, const StatusCode responseStatus, HeapMessage &request,
const void *pResponse, const size_t responseLength)
{
HeapMessage response(*component.GetHeap(), pResponse, responseLength);
if (!response)
return STATUS_CODE_HEAP_EMPTY;
PostResponse(component, responseStatus, request, response);
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void PostMessageHelper::PostResponse(const Component &component, const StatusCode responseStatus, HeapMessage &request,
HeapMessage &response)
{
PostResponse(component, request.GetSourceAddress(), request.GetType(), request.GetRequestId(), responseStatus, response);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void PostMessageHelper::PostEmptyResponse(const Component &component, const StatusCode responseStatus, HeapMessage &request)
{
request.SetLength(0);
PostResponse(component, responseStatus, request);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void PostMessageHelper::PostEmptyResponse(const Component &component, const Address &destinationAddress,
const MessageType requestType, const RequestId &requestId, const StatusCode responseStatus, HeapMessage &response)
{
response.SetLength(0);
PostResponse(component, destinationAddress, requestType, requestId, responseStatus, response);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode PostMessageHelper::PostMessage(const Component &component, const Address &destinationAddress,
const MessageType messageType, const MessageBuilder &messageBuilder)
{
return PostMessage(component, destinationAddress, messageType, messageBuilder.GetMessage(), messageBuilder.GetLength());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode PostMessageHelper::PostMessage(const Component &component, const Address &destinationAddress,
const MessageType messageType, const void *pMessage, const size_t messageLength)
{
HeapMessage message(*component.GetHeap(), pMessage, messageLength);
if (ACTIV_UNLIKELY(!message))
return STATUS_CODE_HEAP_EMPTY;
PostMessage(component, destinationAddress, messageType, message);
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool PostMessageHelper::IsEmpty() const
{
return m_endPointIdList.empty();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const PostMessageHelper::Statistics &PostMessageHelper::GetStatistics() const
{
return m_statistics;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void PostMessageHelper::ResetStatistics()
{
return m_statistics.Reset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline PostMessageHelper::ScopedFlush::ScopedFlush(PostMessageHelper &postMessageHelper) :
m_postMessageHelper(postMessageHelper)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline PostMessageHelper::ScopedFlush::~ScopedFlush()
{
m_postMessageHelper.Flush();
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline PostMessageHelper::ScopedTryFlush::ScopedTryFlush(PostMessageHelper &postMessageHelper) :
m_postMessageHelper(postMessageHelper)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline PostMessageHelper::ScopedTryFlush::~ScopedTryFlush()
{
m_postMessageHelper.TryFlush();
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_POST_MESSAGE_HELPER_H)
@@ -1,335 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/PubSubServiceApi.h
*
* @brief Header file for the pubsub service api.
*/
#if (!defined ACTIV_FRAMEWORK_PUB_SUB_SERVICE_API_H)
#define ACTIV_FRAMEWORK_PUB_SUB_SERVICE_API_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include "ActivMiddleware/ActivBase/ProcessorAffinity.h"
#include "ActivMiddleware/ActivFramework/Subject.h"
#include <map>
#include <set>
#include <vector>
//! Activ namespace.
namespace Activ
{
class Address;
class Component;
class HeapMessage;
class MessageBuilder;
class PostMessageHelper;
class Subject;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Api to the agent's pubsub service.
*/
class PubSubServiceApi
{
public:
typedef std::set<Address> AddressSet; ///< address set type
typedef std::vector<AddressSet> AddressSetList; ///< address set list. Index is AgentScope
typedef std::map<Subject, AddressSetList> SubscriptionMap; ///< subscription map
/**
* @brief Multicast settings.
*
* This describes an instance of a multicast input/output.
*/
class Multicast
{
public:
//! Compression types.
enum CompressionType
{
COMPRESSION_TYPE_NONE,
COMPRESSION_TYPE_NULL,
COMPRESSION_TYPE_RDC,
COMPRESSION_TYPE_ZLIB,
NUM_COMPRESSION_TYPES ///< Number of compression types.
};
//! Default constructor.
ACTIV_FRAMEWORK_API Multicast();
String m_url; ///< Of the form: apd://multicast-group:port.
String m_interfaceAddress; ///< Local interface to bind to.
UInt m_socketTxBufferSize; ///< Default undefined; leave as OS default.
UInt m_socketRxBufferSize; ///< Default 1MB.
uint16_t m_flushByteThreshold; ///< Default: 1472. Flush tx buffer when >= this; set to the MTU if 0.
TimeoutPeriod m_blockingTimeout; ///< Default 50ms.
bool m_shouldTransmit; ///< Transmit on this group? Default true.
bool m_shouldListen; ///< Receive on this group? Default false.
size_t m_ttl; ///< Ttl for transmission. Default is 4.
CompressionType m_txCompressionType; ///< Default COMPRESSION_TYPE_NONE.
ProcessorAffinity m_threadProcessorAffinity; ///< Default: do not adjust.
};
/**
* @brief Subscribe to a subject.
*
* Note subscriptions from a component are not cumulative at the same scope level. However, subscribing to the
* same subject at more than one scope requires unsubscribing at each scope.
*
* @param component the component wishing to subscribe.
* @param agentScope AGENT_SCOPE_LOCAL only receive messages published within this agent space,
* AGENT_SCOPE_GLOBAL receive both local and messages published onto the network, AGENT_SCOPE_REMOTE only receive
* messages published remotely.
* @param subject subject to subscribe to.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode Subscribe(const Component &component, const AgentScope agentScope,
const Subject &subject);
/**
* @brief Unsubscribe from a subject.
*
* @param component the component wishing to unsubscribe.
* @param agentScope the scope from which to unsubscribe.
* @param subject the subject to unsubscribe from.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode Unsubscribe(const Component &component, const AgentScope agentScope,
const Subject &subject);
/**
* @brief Publish a message.
*
* @param component the component wishing to publish.
* @param agentScope AGENT_SCOPE_LOCAL only publish locally within this agent space, AGENT_SCOPE_REMOTE
* only publish onto the network, AGENT_SCOPE_GLOBAL publish locally & remotely.
* @param subject subject of published message.
* @param type type of published message.
* @param messageBuilder reference to a MessageBuilder containing the message body to publish.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode Publish(const Component &component, const AgentScope agentScope, const Subject &subject,
const MessageType type, const MessageBuilder &messageBuilder);
/**
* @brief Publish a message.
*
* @param component the component wishing to publish.
* @param agentScope AGENT_SCOPE_LOCAL only publish locally within this agent space, AGENT_SCOPE_REMOTE
* only publish onto the network, AGENT_SCOPE_GLOBAL publish locally & remotely.
* @param subject subject of published message.
* @param type type of published message.
* @param pData pointer to message body.
* @param dataLength length of message body.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode Publish(const Component &component, const AgentScope agentScope, const Subject &subject,
const MessageType type, const void *pData = 0, const size_t dataLength = 0);
/**
* @brief Publish a message.
*
* @param component the component wishing to publish.
* @param agentScope AGENT_SCOPE_LOCAL only publish locally within this agent space, AGENT_SCOPE_REMOTE
* only publish onto the network, AGENT_SCOPE_GLOBAL publish locally & remotely.
* @param subject subject of published message.
* @param type type of published message.
* @param heapMessage HeapMessage containing message body to publish.
*
* @retval STATUS_CODE_SUCCESS. heapMessage will no longer have a message attached.
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode Publish(const Component &component, const AgentScope agentScope, const Subject &subject,
const MessageType type, HeapMessage &heapMessage);
/**
* @brief Publish a message via a PostMessageHelper object.
*
* @param component the component wishing to publish.
* @param postMessageHelper reference to a PostMessageHelper. The published message will be queued here
* and not immediately sent to the PubSubService for distribution. postMessageHelper.Flush() will
* need to be called at some point in order to push any queued messages to the PubSubService.
* @param agentScope AGENT_SCOPE_LOCAL only publish locally within this agent space, AGENT_SCOPE_REMOTE
* only publish onto the network, AGENT_SCOPE_GLOBAL publish locally & remotely.
* @param subject subject of published message.
* @param type type of published message.
* @param messageBuilder reference to a MessageBuilder containing the message body to publish.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMTPY
*/
ACTIV_FRAMEWORK_API static StatusCode Publish(const Component &component, PostMessageHelper &postMessageHelper,
const AgentScope agentScope, const Subject &subject, const MessageType type, const MessageBuilder &messageBuilder);
/**
* @brief Publish a message via a PostMessageHelper object.
*
* @param component the component wishing to publish.
* @param postMessageHelper reference to a PostMessageHelper. The published message will be queued here
* and not immediately sent to the PubSubService for distribution. postMessageHelper.Flush() will
* need to be called at some point in order to push any queued messages to the PubSubService.
* @param agentScope AGENT_SCOPE_LOCAL only publish locally within this agent space, AGENT_SCOPE_REMOTE
* only publish onto the network, AGENT_SCOPE_GLOBAL publish locally & remotely.
* @param subject subject of published message.
* @param type type of published message.
* @param pData pointer to message body.
* @param dataLength length of message body.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_HEAP_EMTPY
*/
ACTIV_FRAMEWORK_API static StatusCode Publish(const Component &component, PostMessageHelper &postMessageHelper,
const AgentScope agentScope, const Subject &subject, const MessageType type, const void *pData = 0,
const size_t dataLength = 0);
/**
* @brief Publish a message via a PostMessageHelper object.
*
* @param component the component wishing to publish.
* @param postMessageHelper reference to a PostMessageHelper. The published message will be queued here
* and not immediately sent to the PubSubService for distribution. postMessageHelper.Flush() will
* need to be called at some point in order to push any queued messages to the PubSubService.
* @param agentScope AGENT_SCOPE_LOCAL only publish locally within this agent space, AGENT_SCOPE_REMOTE
* only publish onto the network, AGENT_SCOPE_GLOBAL publish locally & remotely.
* @param subject subject of published message.
* @param type type of published message.
* @param heapMessage HeapMessage containing message body to publish.
*/
ACTIV_FRAMEWORK_API static void Publish(const Component &component, PostMessageHelper &postMessageHelper,
const AgentScope agentScope, const Subject &subject, const MessageType type, HeapMessage &heapMessage);
/**
* @brief Get subscriptions.
*
* @param component the component requesting subscriptions.
* @param subject the subject to get the subscriptions for.
* @param shouldRecurseTree whether to get subscriptions for entire subject tree.
* @param subscriptionMap reference to the subscription map to receive subscriptions.
* @param timeout timeout in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode GetSubscriptions(const Component &component, const Subject &subject,
const bool shouldRecurseTree, SubscriptionMap &subscriptionMap, const TimeoutPeriod timeout = COMPONENT_DEFAULT_TIMEOUT);
/**
* @brief Add a multicast input/output.
*
* If the provided name is already configured as a multicast output, an error is returned.
*
* @param component
* @param name a name for the multicast.
* @param multicast describing the group, port, interface, etc.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode AddMulticast(const Component &component, const String &name,
const Multicast &multicast);
/**
* @brief Republish a Subject on a given named multicast output.
*
* @param component
* @param subject the Subject to publish output on the multicast @a multicastName.
* @param multicastName as passed to AddMulticast() or from static configuration of the PubSubService.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode AddSubjectToMulticast(const Component &component, const Subject &subject,
const String &multicastName);
/**
* @brief Append a trailing Subject::SEPARATOR_CHAR to a subject if required.
*
* @param subject subject string to modify in-place.
*
* @return false if the subject is invalid.
*/
ACTIV_FRAMEWORK_API static bool BuildFullyQualifiedSubject(String &subject);
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Scoped subscription helper.
*/
class ScopedSubscription : private Boost::noncopyable
{
public:
/**
* @brief Constructor.
*
* @param component
*/
ACTIV_FRAMEWORK_API ScopedSubscription(const Component &component);
/**
* @brief Constructor.
*
* Subscribes the component to the given subject at the given scope.
*
* @param component
* @param agentScope
* @param subject
*
* @throw Exception if unable to subscribe.
*/
ACTIV_FRAMEWORK_API ScopedSubscription(const Component &component, const AgentScope agentScope, const Subject &subject);
/**
* @brief Destructor.
*
* Unsubscribes if the subscription is still in place.
*/
ACTIV_FRAMEWORK_API ~ScopedSubscription();
/**
* @brief Subscribes. Will unsubscribe if already subscribed.
*
* @return STATUS_CODE_SUCCESS or reason for failed subscription.
*/
ACTIV_FRAMEWORK_API StatusCode Subscribe(const AgentScope agentScope, const Subject &subject);
/**
* @brief Unsubscribes.
*
* @return STATUS_CODE_SUCCESS or reason for failed unsubscription.
*/
ACTIV_FRAMEWORK_API StatusCode Unsubscribe();
//! Is subscribed.
bool IsSubscribed() const;
private:
const Component & m_component;
AgentScope m_agentScope;
Subject m_subject;
bool m_isSubscribed;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool ScopedSubscription::IsSubscribed() const
{
return m_isSubscribed;
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_PUB_SUB_SERVICE_API_H)
@@ -1,603 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/RequestId.h
*
* @brief Header file for request id class.
*/
#if (!defined ACTIV_FRAMEWORK_REQUEST_ID_H)
#define ACTIV_FRAMEWORK_REQUEST_ID_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/ActivBase.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/ActivFramework/Address.h"
#include "ActivMiddleware/Misc/MemoryHelper.h"
#include ACTIV_BOOST_INCLUDE(typeof/typeof.hpp)
#include <cassert>
//! Activ namespace.
namespace Activ
{
class SyncRequestId;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Request id class.
*/
class RequestId
{
public:
typedef uint32_t SendId; ///< Request id type for synchronous calls.
typedef byte_t Attribute; ///< Attribute type.
static const Attribute ATTRIBUTE_NONE = 0x00;
static const Attribute ATTRIBUTE_ON = 0x01;
static const Attribute ATTRIBUTE_RESPONSE = 0x02;
static const Attribute ATTRIBUTE_USE_RESPONSE_ADDRESS = 0x04;
static const byte_t MAX_LENGTH = 16; ///< Large enough for a UUID.
//! Default constructor.
RequestId();
/**
* @brief Constructor.
*
* @param pData data to set
* @param dataSize size of data in pData.
*/
RequestId(const void *pData, const size_t dataSize);
/**
* @brief Constructor.
*
* @param pData data to set.
* @param dataSize size of data in pData.
* @param responseAddress address to route response to request.
*/
RequestId(const void *pData, const size_t dataSize, const Address &responseAddress);
/**
* @brief Constructor.
*
* @param value to set.
*/
template<typename T>
RequestId(const T value, typename Boost::enable_if<Boost::is_integral<T> >::type* dummy = 0);
/**
* @brief Constructor.
*
* @param value to set.
* @param responseAddress address to route response to request.
*/
template<typename T>
RequestId(const T value, const Address &responseAddress, typename Boost::enable_if<Boost::is_integral<T> >::type* dummy = 0);
/**
* @brief Copy constructor.
*
* @param requestId to copy from.
*/
RequestId(const RequestId &requestId);
//! Clear the id.
void Clear();
//! Get the length of request id data.
size_t GetLength() const;
/**
* @brief Set the length of data. Truncated if over maxLength.
*
* @param dataLength length to set to.
*/
void SetLength(const size_t dataLength);
//! Get a pointer to request id data.
const byte_t *Get() const;
/**
* @brief Get integral value.
*
* @param value
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_LENGTH
*/
template<typename T>
typename Boost::enable_if<Boost::is_integral<T>, StatusCode>::type Get(T &value) const;
/**
* @brief Get integral value.
*
* @return value
*
* @throw StatusCodeException
*/
template<typename T>
typename Boost::enable_if<Boost::is_integral<T>, T>::type Get() const;
/**
* @brief Set the data.
*
* @param pData data to set
* @param dataLength size of data in pData.
*/
void Set(const void *pData, const size_t dataLength);
/**
* @brief Set the data.
*
* @param pData data to set
* @param dataLength size of data in pData.
* @param responseAddress address to route response to request.
*/
void Set(const void *pData, const size_t dataLength, const Address &responseAddress);
/**
* @brief Set an integral value.
*
* @param value
*/
template<typename T>
typename Boost::enable_if<Boost::is_integral<T> >::type Set(const T value);
/**
* @brief Set an integral value.
*
* @param value
* @param responseAddress address to route response to request.
*/
template<typename T>
typename Boost::enable_if<Boost::is_integral<T> >::type Set(const T value, const Address &responseAddress);
/**
* @brief Equality operator.
*
* @return true if this is equal to rhs.
*/
bool operator==(const RequestId &rhs) const;
/**
* @brief Inequality operator.
*
* @return true if this is not equal to rhs.
*/
bool operator!=(const RequestId &rhs) const;
/**
* @brief Less than operator.
*
* @param rhs RequestId to compare with.
*
* @retval true if this is less than rhs.
* @retval false if this is greater than or equal to rhs.
*/
bool operator<(const RequestId &rhs) const;
/**
* @brief Assignment operator.
*
* @param rhs to assign from.
*/
RequestId &operator=(const RequestId &rhs);
//! Get the attribute bits.
Attribute GetAttributes() const;
/**
* @brief Set the attribute bits.
*
* @param attributes the attributes.
*/
void SetAttributes(Attribute attributes);
//! Get the response address.
const Address &GetResponseAddress() const;
//! Set the response address.
void SetResponseAddress(const Address &responseAddress);
//! Get the serialized length of the RequestId.
size_t GetSerializedLength() const;
/**
* @brief Serialize the request id.
*
* @param messageBuilder reference to MessageBuilder to serialize with.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode Serialize(MessageBuilder &messageBuilder) const;
/**
* @brief Deserialize the request id.
*
* @param messageValidator reference to MessageValidator to deserialize with.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode Deserialize(MessageValidator &messageValidator);
//! Convert the request id to a printable string.
String ToString() const;
//! Is the message model request/response?
bool IsRequestOrResponse() const;
//! Get a string representation of the message model (req/resp or other).
String MessageModelToString() const;
/**
* @brief Get a string representation of the message model (req/resp or other).
*
* @param attributes attributes from a request id.
*
* @return String representation of the message model.
*/
static String MessageModelToString(const Attribute attributes);
ACTIV_FRAMEWORK_API
static const RequestId emptyRequestId; ///< An empty request id.
private:
/**
* @brief Set the data.
*
* @param pData data to set
* @param dataLength size of data in pData.
*/
void CommonSet(const void *pData, const size_t dataSize);
/**
* @brief Compare this with another RequestId.
*
* @param rhs RequestId to compare with.
*
* @retval -ve if this is less than rhs.
* @retval 0 if this equal to rhs.
* @retval +ve if this is greater than rhs.
*/
int Compare(const RequestId &rhs) const;
Attribute m_attributes; ///< Attribute byte.
Address m_responseAddress; ///< Optional response address.
byte_t m_length; ///< Bytes used in buffer.
byte_t m_buffer[MAX_LENGTH]; ///< The request id buffer.
friend class SyncRequestId;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline RequestId::RequestId()
{
Clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline RequestId::RequestId(const void *pData, const size_t dataSize)
{
Set(pData, dataSize);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline RequestId::RequestId(const void *pData, const size_t dataLength, const Address &responseAddress)
{
Set(pData, dataLength, responseAddress);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline RequestId::RequestId(const T t, typename Boost::enable_if<Boost::is_integral<T> >::type* dummy)
{
Set(t);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline RequestId::RequestId(const T t, const Address &responseAddress,
typename Boost::enable_if<Boost::is_integral<T> >::type* dummy)
{
Set(t, responseAddress);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline RequestId::RequestId(const RequestId &requestId)
{
*this = requestId;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RequestId::Clear()
{
m_attributes = 0;
m_responseAddress.Clear();
m_length = 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t RequestId::GetLength() const
{
return m_length;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RequestId::SetLength(const size_t dataLength)
{
m_length = static_cast<byte_t>(std::min<size_t>(dataLength, sizeof(m_buffer)));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const byte_t *RequestId::Get() const
{
return m_buffer;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_integral<T>, StatusCode>::type RequestId::Get(T &value) const
{
if (ACTIV_UNLIKELY(sizeof(T) != GetLength()))
return STATUS_CODE_INVALID_LENGTH;
value = GetValueFromUnalignedPointer<T>(Get());
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_integral<T>, T>::type RequestId::Get() const
{
if (ACTIV_UNLIKELY(sizeof(T) != GetLength()))
ACTIV_THROW(StatusCodeException, STATUS_CODE_INVALID_LENGTH);
return GetValueFromUnalignedPointer<T>(Get());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RequestId::Set(const void *pData, const size_t dataLength)
{
CommonSet(pData, dataLength);
m_responseAddress.Clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RequestId::Set(const void *pData, const size_t dataLength, const Address &responseAddress)
{
CommonSet(pData, dataLength);
if (responseAddress.IsValid())
{
m_attributes |= ATTRIBUTE_USE_RESPONSE_ADDRESS;
m_responseAddress = responseAddress;
}
else
{
m_responseAddress.Clear();
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_integral<T> >::type RequestId::Set(const T value)
{
Set(&value, sizeof(value));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline typename Boost::enable_if<Boost::is_integral<T> >::type RequestId::Set(const T value, const Address &responseAddress)
{
Set(&value, sizeof(value), responseAddress);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool RequestId::operator==(const RequestId &rhs) const
{
return 0 == Compare(rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool RequestId::operator!=(const RequestId &rhs) const
{
return 0 != Compare(rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool RequestId::operator<(const RequestId &rhs) const
{
return Compare(rhs) < 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline RequestId &RequestId::operator=(const RequestId &rhs)
{
if (this != &rhs)
{
m_attributes = rhs.m_attributes;
m_responseAddress = rhs.m_responseAddress;
m_length = rhs.m_length;
MemoryCopy(m_buffer, rhs.m_buffer, m_length);
}
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline RequestId::Attribute RequestId::GetAttributes() const
{
return m_attributes;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RequestId::SetAttributes(Attribute attributes)
{
m_attributes = attributes;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const Address &RequestId::GetResponseAddress() const
{
return m_responseAddress;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RequestId::SetResponseAddress(const Address &responseAddress)
{
m_responseAddress = responseAddress;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t RequestId::GetSerializedLength() const
{
return sizeof(m_attributes) + m_responseAddress.GetSerializedLength() + sizeof(m_length) + m_length;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode RequestId::Serialize(MessageBuilder &messageBuilder) const
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageBuilder.Append<MessageBuilder::ENDIAN_LITTLE>(m_attributes));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, m_responseAddress.Serialize(messageBuilder));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageBuilder.Append<MessageBuilder::ENDIAN_LITTLE>(m_length));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageBuilder.AppendBuffer(m_buffer, m_length));
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode RequestId::Deserialize(MessageValidator &messageValidator)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=,
(messageValidator.ValidateBinaryIntegral<sizeof(m_attributes), MessageValidator::ENDIAN_LITTLE>(m_attributes)));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, m_responseAddress.Deserialize(messageValidator));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, (messageValidator.ValidateBinaryIntegralRange<
sizeof(m_length), MessageValidator::ENDIAN_LITTLE, ACTIV_DECLTYPE(m_length), 0, sizeof(m_buffer)>(m_length)));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageValidator.ValidateBytesCopy(m_length, &m_buffer));
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline String RequestId::ToString() const
{
char buff[4];
String output;
for (size_t i = 0; i < m_length; ++i)
{
(void) Snprintf(buff, ACTIV_ARRAY_SIZE(buff), "%s%02x", (i > 0) ? " " : "", m_buffer[i]);
output += buff;
}
return output;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool RequestId::IsRequestOrResponse() const
{
return (m_attributes & ATTRIBUTE_ON);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline String RequestId::MessageModelToString() const
{
return MessageModelToString(m_attributes);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline String RequestId::MessageModelToString(const Attribute attributes)
{
if (attributes & ATTRIBUTE_ON)
{
if (attributes & ATTRIBUTE_RESPONSE)
return "response";
else
return "request";
}
else
{
return "message";
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RequestId::CommonSet(const void *pData, const size_t dataLength)
{
assert(dataLength <= sizeof(m_buffer));
// Clear down attributes. Request / response is set by Component Send/Post methods.
m_attributes = ATTRIBUTE_NONE;
m_length = static_cast<byte_t>(std::min<size_t>(dataLength, sizeof(m_buffer)));
MemoryCopy(m_buffer, pData, m_length);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline int RequestId::Compare(const RequestId &rhs) const
{
// The attribute bits do not take part in the comparison operation (a returned request id may have
// different bits set). Same applies for response address. Comparison is only on the body of the request id.
if (m_length != rhs.m_length)
{
const size_t compareLength = std::min<>(m_length, rhs.m_length);
const int compareValue = ::memcmp(m_buffer, rhs.m_buffer, compareLength);
if (0 == compareValue)
return (m_length == compareLength) ? -1 : 1;
else
return compareValue;
}
else
{
return ::memcmp(m_buffer, rhs.m_buffer, m_length);
}
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_REQUEST_ID_H)
@@ -1,812 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/RingBuffer.h
*
* @brief Header for the RingBuffer class.
*/
#if (!defined ACTIV_FRAMEWORK_RING_BUFFER_H)
#define ACTIV_FRAMEWORK_RING_BUFFER_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/IEvent.h"
#include "ActivMiddleware/ActivBase/IMappedMemory.h"
#include "ActivMiddleware/ActivBase/Timeout.h"
#include "ActivMiddleware/ActivFramework/ManagedEndPoint.h"
#include "ActivMiddleware/ActivFramework/Timer.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#include "ActivMiddleware/CxxYZ/memory.h"
#include "ActivMiddleware/CxxYZ/atomic.h"
//! Activ namespace.
namespace Activ
{
class EventManagee;
class RingBufferHelper;
/**
* @brief Ring buffer class.
*
* Supports reading/writing variable length messages up to ((size / 2) - sizeof(uint32_t)) bytes.
*/
class RingBuffer
{
public:
//! Atomic type.
typedef CxxYZ::atomic<uint32_t> AtomicUint32;
class OpenTag {};
class CreateTag{};
class Reader;
//! Writer class.
class Writer
{
public:
//! Back pressure mode enumeration.
enum BackPressureMode
{
BACK_PRESSURE_MODE_SPIN, ///< If ring fills, busy wait until space becomes available.
BACK_PRESSURE_MODE_DROP ///< If ring fills, drop message.
};
//! Statistics class.
class Statistics
{
public:
//! Default constructor.
Statistics();
uint64_t m_byteCount;
uint64_t m_messageCount;
/**
* @brief Get the back pressure count.
*
* When in BACK_PRESSURE_MODE_SPIN this is the number of times a busy wait has been required to wait for space.
*
* When in BACK_PRESSURE_MODE_DROP this is the number of messages dropped as a result of back pressure.
*/
uint64_t m_backPressureCount;
uint32_t m_intervalPeak;
uint32_t m_peak;
DateTime m_peakDateTime;
};
/**
* @brief Construct a writer to write to a reader object.
*
* @param managedEndPoint ManagedEndPoint this Writer is associated with.
* @param OpenTag the writer will be opening the ring buffer.
* @param reader the reader to write to.
* @param backPressureMode the back pressure mode to use.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API Writer(ManagedEndPoint &managedEndPoint, const OpenTag, const Reader &reader,
const BackPressureMode backPressureMode);
/**
* @brief Construct a writer to write to a shared memory buffer.
*
* Opens the shared memory buffer.
*
* @param managedEndPoint ManagedEndPoint this Writer is associated with.
* @param OpenTag the writer will be opening the ring buffer.
* @param name name of the memory mapped file to open.
* @param backPressureMode the back pressure mode to use.
* @param timeoutPeriod how long to wait, in ms.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API Writer(ManagedEndPoint &managedEndPoint, const OpenTag, const String &name,
const BackPressureMode backPressureMode, const TimeoutPeriod timeoutPeriod = ACTIV_WAIT_INFINITE);
/**
* @brief Construct a writer to write to a shared memory buffer.
*
* Creates the shared memory buffer.
*
* @param managedEndPoint ManagedEndPoint this Writer is associated with.
* @param CreateTag the writer will be creating the ring buffer.
* @param name name of the memory mapped file to create.
* @param size size of the data portion of the ring buffer.
* @param backPressureMode the back pressure mode to use.
* @param isUsingTimestamps whether the writer will transmit timestamps, requires support in the reader.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API Writer(ManagedEndPoint &managedEndPoint, const CreateTag, const String &name, const size_t size,
const BackPressureMode backPressureMode, const bool isUsingTimestamps);
//! Destructor.
ACTIV_FRAMEWORK_API virtual ~Writer();
/**
* @brief Allocate a write buffer. Any Write*() function will invalidate the buffer.
*
* @param pBuffer
* @param length
*
* @retval true if the write can proceed.
*
* @throw Exception
*/
bool AllocateWriteBuffer(void *&pBuffer, const size_t length);
/**
* @brief Commit write buffer. Previously allocated via AllocateWriteBuffer.
*
* @param length
*
* @throw Exception
*/
void CommitWriteBuffer(const size_t length);
/**
* @brief Write a buffer to the ring buffer.
*
* @param pData
* @param length
* @param pTimestamp optional timestamp to attach with the message.
*
* @retval true if the buffer was successfully written.
*
* @throw Exception
*/
bool WriteBuffer(const void *pData, const size_t length, const timespec *pTimestamp = ACTIV_NULLPTR);
/**
* @brief Write a fixed length message to the ring buffer.
*
* F must be a callable type accepting a signature of void (void *pData, uint32_t length). The data written into the memory
* must be exactly @a length bytes long.
*
* @param function
* @param length
* @param pTimestamp optional timestamp to attach with the message.
*
* @retval true if the buffer was successfully written.
*
* @throw Exception
*/
template <typename F>
bool WriteFixedMessage(const F &function, const size_t length, const timespec *pTimestamp = ACTIV_NULLPTR);
/**
* @brief Write a variable length message to the ring buffer.
*
* F must be a callable type accepting a signature of size_t (void *pData, size_t length). The data written into
* the memory must be at most @a length bytes long. The number of bytes actually written must be returned.
*
* @param function
* @param length
* @param pTimestamp optional timestamp to attach with the message.
*
* @retval true if the buffer was successfully written.
*
* @throw Exception
*/
template <typename F>
bool WriteVariableMessage(const F &function, const size_t length, const timespec *pTimestamp = ACTIV_NULLPTR);
//! Flush.
void Flush();
/**
* @brief Set a callback function to be invoked when the interval peak has been updated.
*
* @param callbackFunction the callback function.
*/
void SetOnIntervalPeakUpdateCallback(const CxxYZ::function<void()> &callbackFunction);
//! Get the statistics.
const Statistics &GetStatistics() const;
private:
//! Initialize the writer.
void Initialize();
/**
* @brief Initialize a write of up to @a length bytes.
*
* @param length the number of bytes to make write.
*
* @return true if write can proceed, false otherwise (dropped).
*/
ACTIV_FRAMEWORK_API bool InitializeWrite(const size_t length);
/**
* @brief Prepare to write up to @a length bytes.
*
* @param length the number of bytes to make write.
*
* @return whether the write can be performed.
*/
bool PrepareWrite(const uint32_t length);
/**
* @brief Initialize a write of up to @a length bytes.
*
* @param pHeader pointer to the message header in the ring buffer to update.
* @param pBuffer pointer to the message data.
* @param length the number of bytes written.
*/
void FinalizeWrite(uint32_t *pHeader, void *pBuffer, const uint32_t length);
/**
* @brief Initialize message header, write timestamp and return pointers to header and message buffer.
*
* @param pHeader
* @param pBuffer
* @param pTimestamp
*/
void InitializeHeader(uint32_t *&pHeader, void *&pBuffer, const timespec *pTimestamp);
//! Check and set event if necessary.
ACTIV_FRAMEWORK_API void CheckAndSetEvent();
/**
* @brief Check blocking loop timeout.
*
* @param loopCount
* @param blockingWriteStartTickCount
*
* @retval Boolean
*/
bool CheckBlockingLoopTimeout(size_t &loopCount, Boost::optional<uint32_t> &oBlockingWriteStartTickCount);
//! Process interval peak timer.
void ProcessIntervalPeakTimer();
//! Process monitor timer.
void ProcessMonitorTimer();
//! Process the reset timer.
void ProcessResetTimer();
//! On post end point processing callback.
bool OnPostEndPointProcessing();
//! On event timer callback.
void OnEventTimer();
ManagedEndPoint & m_managedEndPoint;
RingBufferHelper & m_ringBufferHelper;
const String m_name;
const BackPressureMode m_backPressureMode;
const bool m_isUsingTimestamps;
CxxYZ::unique_ptr<RingBuffer> m_pRingBuffer;
uint32_t m_cachedReadOffset;
uint32_t m_cachedWriteOffset;
uint32_t m_cachedReaderCompletionEventCount;
Statistics m_statistics;
uint32_t m_monitorIntervalPeak;
bool m_hasAlertedForBlockingWriteDrop;
bool m_hasBlockingWriteDroppedSinceLastSuccess;
//! Byte count when the event was last checked.
uint64_t m_lastEventCheckByteCount;
//! Threshold to check ring buffer event (if not checked due to idleness).
const uint32_t m_eventByteThreshold;
Timer m_intervalPeakTimer;
CxxYZ::function<void()> m_onIntervalPeakUpdateCallback;
Timer m_monitorTimer;
String m_monitorName;
uint64_t m_backPressureCountAtReset;
Timer m_resetTimer;
bool m_hasUpdatedWritePointerSinceLastPostEndPointProcessing;
bool m_hasEventBeenCheckedSinceLastUpdate;
uint32_t m_messagesPerWritePointerUpdate; ///< The current total number of messages before the write pointer will update.
uint32_t m_messagesUntilWritePointerUpdate; ///< The remaining number of messages before the next write pointer update.
uint32_t m_maxFlushFrequency; ///< 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.
friend class RingBufferHelper;
};
class MessageReader;
//! Reader class.
class Reader
{
public:
//! Callback function signature for event notification.
typedef CxxYZ::function<bool (void)> CallbackFunction;
/**
* @brief Construct a reader to read from private memory.
*
* @param managedEndPoint ManagedEndPoint this Reader is associated with.
* @param CreateTag the reader will be creating the ring buffer.
* @param callbackFunction function for notification of data.
* @param size size of the data buffer to create.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API Reader(ManagedEndPoint &managedEndPoint, const CreateTag, const CallbackFunction &callbackFunction,
const size_t size);
/**
* @brief Construct a reader to read from shared memory.
*
* Creates the shared memory buffer.
*
* @param managedEndPoint ManagedEndPoint this Reader is associated with.
* @param CreateTag the reader will be creating the ring buffer.
* @param callbackFunction function for notification of data.
* @param name name of the memory mapped file to create.
* @param size size of the data portion of the ring buffer.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API Reader(ManagedEndPoint &managedEndPoint, const CreateTag, const CallbackFunction &callbackFunction,
const String &name, const size_t size);
/**
* @brief Construct a reader to read from shared memory.
*
* Opens the shared memory buffer.
*
* @param managedEndPoint ManagedEndPoint this Reader is associated with.
* @param OpenTag the reader will be opening the ring buffer.
* @param callbackFunction function for notification of data.
* @param name name of the memory mapped file to open.
* @param timeoutPeriod how long to wait, in ms.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API Reader(ManagedEndPoint &managedEndPoint, const OpenTag, const CallbackFunction &callbackFunction,
const String &name, const TimeoutPeriod timeoutPeriod = ACTIV_WAIT_INFINITE);
//! Destructor.
ACTIV_FRAMEWORK_API ~Reader();
//! Process read event.
void ProcessReadEvent();
//! Get the number of blocking reads.
size_t GetNumberOfBlockingReads() const;
//! Get the number of attempted blocking reads that were re-enabled.
size_t GetNumberOfTimesEventHasReenabled() const;
//! Get the current number of bytes queued.
ACTIV_FRAMEWORK_API uint32_t GetCurrentBytesQueued();
private:
/**
* @brief Read a data block from the ring buffer.
*
* @param pData
* @param length
* @param timestamp reference to receive a timestamp, tv_sec is set to zero if a timestamp is not available.
*
* @return whether data was available to read.
*/
ACTIV_FRAMEWORK_API bool Read(const void *&pData, size_t &length, timespec &timestamp);
//! Initialize the reader.
void Initialize(ManagedEndPoint &managedEndPoint);
void UpdateCachedBytesQueued();
//! Reset event.
void ResetEvent();
//! Read from buffer using cached write offset.
bool InternalCachedRead(const void *&pData, size_t &length, timespec &timestamp);
//! Read from buffer using atomic write offset.
bool InternalRead(const void *&pData, size_t &length, timespec &timestamp);
//! Process lazy timer.
void ProcessLazyTimer();
ManagedEndPoint & m_managedEndPoint;
CxxYZ::unique_ptr<RingBuffer> m_pRingBuffer;
uint32_t m_cachedWriteOffset;
uint32_t m_currentPosition;
uint32_t m_cachedBytesQueued;
bool m_shouldTriggerPeakQueuedBytesTrace;
uint64_t m_lastEmptyTimestamp;
ScopedTracePoint m_processTracePoint;
size_t m_numberOfBlockingReads;
size_t m_numberOfTimesEventHasReenabled;
CallbackFunction m_callbackFunction;
CxxYZ::unique_ptr<EventManagee> m_pEventManagee;
Timer m_lazyTimer;
const String m_monitorName;
ManagedEndPoint::ScopedPostEndPointProcessingTask
m_scopedPostEndPointProcessingTask;
friend class MessageReader;
friend class Writer;
};
//! Message reader class to access messages from the buffer. Used to enforce trace processing at the beginning.
class MessageReader
{
public:
//! Constructs the reader and records a trace event.
MessageReader(Reader &reader);
/**
* @brief Reads a message.
*
* @param pData
* @param length
* @param timestamp reference to receive a timestamp, tv_sec is set to zero if a timestamp is not available.
*/
bool operator()(const void *&pData, size_t &length, timespec &timestamp) const;
private:
Reader & m_reader;
};
//! Get cache line size.
uint32_t GetCacheLineSize() const;
//! Get maximum ring buffer size.
uint32_t GetMaximumRingBufferSize();
/**
* @brief Round offset to the next cache line.
*
* @param offset
*
* @return rounded offset.
*/
template<typename T>
T RoundOffsetToNextCacheLineT(const T offset) const;
private:
//! Class to trace queuing.
struct ProcessTraceEvent : TraceEvent
{
public:
ACTIV_FRAMEWORK_API String Decode(const String &name) const;
uint32_t m_cachedBytesQueued;
};
//! Default constructor.
RingBuffer();
/**
* @brief Create a private memory ring buffer.
*
* @param size size of the data portion of the ring buffer.
*
* @throw Exception
*/
void Create(const size_t size);
/**
* @brief Create a shared memory ring buffer.
*
* @param name name of the memory mapped file to create.
* @param size size of the data portion of the ring buffer.
* @param version protocol version to use.
*
* @throw Exception
*/
void Create(const String &name, const size_t size, const uint32_t version = VERSION_0);
/**
* @brief Open a private memory ring buffer.
*
* @param ringBuffer the ring buffer to open.
*
* @throw Exception
*/
void Open(const RingBuffer &ringBuffer);
/**
* @brief Open a shared memory ring buffer.
*
* @param name name of the memory mapped file to open.
* @param timeout object specifying how long to wait for the object to exist, in ms.
*
* @throw Exception
*/
void Open(const String &name, Timeout &timeout);
/**
* @brief Initial the shared data.
*
* @param isCreator whether the ring buffer is being created.
* @param creatorVersion protocol version to set for the creator.
*/
void InitializeSharedData(const bool isCreator, const uint32_t creatorVersion = VERSION_0);
//! Get memory map size before the version was added.
size_t GetOldMemoryMapSize() const;
//! Get memory map size after the version was added.
size_t GetNewMemoryMapSize() const;
//! Value written to indicate the next message will not fit into the end of the ring. Jump back to the beginning.
static const uint32_t WRAP = Boost::integer_traits<uint32_t>::const_max;
//! Top bit of length indicates either a wrap or a timestamp is present.
static const uint32_t TIMESTAMP_OR_WRAP_BIT = (1 << 31);
//! Size of the timestamp.
static const size_t TIMESTAMP_SIZE = sizeof(uint32_t) + sizeof(uint32_t);
static const uint32_t VERSION_0 = 0;
//! Version 1 adds support for transmit timestamps.
static const uint32_t VERSION_1 = 1;
ACTIV_BOOST_STATIC_ASSERT(sizeof(size_t) >= sizeof(uint32_t));
IEvent * m_pDataEvent;
CxxYZ::unique_ptr<IMappedMemory> m_pMappedMemory;
CxxYZ::shared_ptr<std::vector<uint8_t> > m_pPrivateBuffer;
uint8_t * m_pBuffer;
uint32_t m_bufferSize;
AtomicUint32 * m_pReadOffset;
AtomicUint32 * m_pWriteOffset;
AtomicUint32 * m_pReaderCompletionEventCount;
AtomicUint32 * m_pBufferSize;
AtomicUint32 * m_pVersion;
AtomicUint32 * m_pReaderPeakSize;
CxxYZ::shared_ptr<IEvent> m_pInitializationEvent;
CxxYZ::shared_ptr<IEvent> m_pSharedDataEvent;
const uint32_t m_l1CacheLineSize;
const uint64_t m_cacheLineMask;
const bool m_isHugePagesEnabled;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint32_t RingBuffer::GetCacheLineSize() const
{
return m_l1CacheLineSize;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
inline T RingBuffer::RoundOffsetToNextCacheLineT(const T offset) const
{
const T cacheLineMask = static_cast<T>(m_cacheLineMask);
return (offset + cacheLineMask) & ~cacheLineMask;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool RingBuffer::Writer::AllocateWriteBuffer(void *&pBuffer, const size_t length)
{
// If false the message has been dropped.
if (ACTIV_UNLIKELY(!InitializeWrite(length)))
return false;
uint32_t *pHeader;
InitializeHeader(pHeader, pBuffer, ACTIV_NULLPTR);
return true;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RingBuffer::Writer::CommitWriteBuffer(const size_t length)
{
assert(length <= Boost::integer_traits<uint32_t>::const_max);
uint32_t *pHeader = reinterpret_cast<uint32_t *>(m_pRingBuffer->m_pBuffer + m_cachedWriteOffset);
FinalizeWrite(pHeader, pHeader + 1, static_cast<uint32_t>(length));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool RingBuffer::Writer::WriteBuffer(const void *pData, const size_t length, const timespec *pTimestamp)
{
// If false the message has been dropped.
if (ACTIV_UNLIKELY(!InitializeWrite(length)))
return false;
uint32_t *pHeader;
void *pBuffer;
InitializeHeader(pHeader, pBuffer, pTimestamp);
if (ACTIV_LIKELY(length > 0))
::memcpy(pBuffer, pData, length);
FinalizeWrite(pHeader, pBuffer, static_cast<uint32_t>(length));
return true;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename F>
inline bool RingBuffer::Writer::WriteFixedMessage(const F &function, const size_t length, const timespec *pTimestamp)
{
// If false the message has been dropped.
if (ACTIV_UNLIKELY(!InitializeWrite(length)))
return false;
uint32_t *pHeader;
void *pBuffer;
InitializeHeader(pHeader, pBuffer, pTimestamp);
function(pBuffer, length);
FinalizeWrite(pHeader, pBuffer, static_cast<uint32_t>(length));
return true;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename F>
inline bool RingBuffer::Writer::WriteVariableMessage(const F &function, const size_t length, const timespec *pTimestamp)
{
// If false the message has been dropped.
if (ACTIV_UNLIKELY(!InitializeWrite(length)))
return false;
uint32_t *pHeader;
void *pBuffer;
InitializeHeader(pHeader, pBuffer, pTimestamp);
const size_t writtenLength = function(pBuffer);
// writtenLength can't validly be >= UINT32_MAX unless their function is broken.
assert(writtenLength < Boost::integer_traits<uint32_t>::const_max);
FinalizeWrite(pHeader, pBuffer, static_cast<uint32_t>(writtenLength));
return true;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RingBuffer::Writer::Flush()
{
CheckAndSetEvent();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RingBuffer::Writer::SetOnIntervalPeakUpdateCallback(const CxxYZ::function<void()> &callbackFunction)
{
m_onIntervalPeakUpdateCallback = callbackFunction;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const RingBuffer::Writer::Statistics &RingBuffer::Writer::GetStatistics() const
{
return m_statistics;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RingBuffer::Writer::FinalizeWrite(uint32_t *pHeader, void *pBuffer, const uint32_t length)
{
// The timestamp bit may be set, just update the length.
*pHeader |= length;
const uint32_t headerLength = static_cast<uint32_t>(uintptr_t(pBuffer) - uintptr_t(pHeader));
const uint32_t totalLength = m_pRingBuffer->RoundOffsetToNextCacheLineT<uint32_t>(headerLength + length);
m_cachedWriteOffset += totalLength;
// Only update the write pointer after receiving a certain number of messages. The number of messages required
// between updates scales directly with the current rate of messages being received.
if (!(--m_messagesUntilWritePointerUpdate))
{
m_pRingBuffer->m_pWriteOffset->store(m_cachedWriteOffset, CxxYZ::memory_order_release);
// Each time the write pointer is updated, increase the number of messages required for the next
// update up to the configured maximum.
m_messagesPerWritePointerUpdate = std::min(m_messagesPerWritePointerUpdate << 1, m_maxFlushFrequency);
m_messagesUntilWritePointerUpdate = m_messagesPerWritePointerUpdate;
m_hasUpdatedWritePointerSinceLastPostEndPointProcessing = true;
}
m_statistics.m_byteCount += totalLength;
++m_statistics.m_messageCount;
#if (defined ACTIV_FRAMEWORK_RING_BUFFER_DEBUG)
LogMessage(LOG_TYPE_DEBUG, Fmt::Format("{}: wrote {} bytes, write-offset={}, read-offset={}", __FUNCTION__,
totalLength, m_cachedWriteOffset, m_cachedReadOffset));
#endif
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void RingBuffer::Writer::InitializeHeader(uint32_t *&pHeader, void *&pBuffer, const timespec *pTimestamp)
{
pHeader = reinterpret_cast<uint32_t *>(m_pRingBuffer->m_pBuffer + m_cachedWriteOffset);
if (!pTimestamp)
{
// Set the header to zero. Later the length will be OR'ed with this value.
*pHeader = 0;
pBuffer = pHeader + 1;
return;
}
else
{
assert(m_isUsingTimestamps);
// Set the timestamp bit. Later the length will be OR'ed with this value.
*pHeader = TIMESTAMP_OR_WRAP_BIT;
pHeader[1] = static_cast<uint32_t>(pTimestamp->tv_sec);
pHeader[2] = static_cast<uint32_t>(pTimestamp->tv_nsec);
pBuffer = pHeader + 3;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline RingBuffer::Writer::Statistics::Statistics() :
m_byteCount(0),
m_messageCount(0),
m_backPressureCount(0),
m_intervalPeak(0),
m_peak(0)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t RingBuffer::Reader::GetNumberOfBlockingReads() const
{
return m_numberOfBlockingReads;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t RingBuffer::Reader::GetNumberOfTimesEventHasReenabled() const
{
return m_numberOfTimesEventHasReenabled;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline RingBuffer::MessageReader::MessageReader(Reader &reader) :
m_reader(reader)
{
// Record the current cached bytes queued.
ProcessTraceEvent &event = m_reader.m_processTracePoint.Record<ProcessTraceEvent>();
event.m_cachedBytesQueued = m_reader.m_cachedBytesQueued;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool RingBuffer::MessageReader::operator()(const void *&pData, size_t &length, timespec &timestamp) const
{
return m_reader.Read(pData, length, timestamp);
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_RING_BUFFER_H)
@@ -1,350 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/RouterService.h
*
* @brief Header file for router service class.
*/
#if (!defined ACTIV_FRAMEWORK_ROUTER_SERVICE_H)
#define ACTIV_FRAMEWORK_ROUTER_SERVICE_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/Ip/INetworkAffinityHelper.h"
#include "ActivMiddleware/ActivBase/Ip/IpManager.h"
#include "ActivMiddleware/ActivBase/Ip/NetworkAffinityFilter.h"
#include "ActivMiddleware/ActivBase/Uuid.h"
#include "ActivMiddleware/ActivFramework/Component.h"
#include "ActivMiddleware/ActivFramework/HeapPool.h"
#include "ActivMiddleware/ActivFramework/ManagedEndPoint.h"
#include "ActivMiddleware/ActivFramework/PostMessageHelper.h"
#include "ActivMiddleware/ActivFramework/UiComponent.h"
#if (defined ACTIV_PLATFORM_LINUX)
#include "ActivMiddleware/ActivBase/Linux/OnloadHelper.h"
#endif
#include "ActivMiddleware/CxxYZ/vector.h"
//! Activ namespace.
namespace Activ
{
class UiIo;
/**
* @brief Router service class.
*/
class RouterService : private ManagedEndPoint, public Component
{
public:
using Component::GetApplication;
using ManagedEndPoint::GetEndPointName;
/**
* @brief Settings.
*/
class Settings : public IpManager::Settings
{
public:
/**
* @brief Constructor.
*
* @param defaultServiceName
*/
ACTIV_FRAMEWORK_API Settings(const String &defaultServiceName);
/**
* @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);
/**
* @brief How to distribute sockets across threads.
*/
enum ThreadDistributionMode
{
THREAD_DISTRIBUTION_MODE_BY_HEAP_ID, ///< Distribute sockets across threads by user's heap id.
THREAD_DISTRIBUTION_MODE_BY_ENDPOINT_ID, ///< Distribute sockets across threads by user's endpoint id.
THREAD_DISTRIBUTION_MODE_LEAST_REQUESTS, ///< Distribute to thread that has handled the least number of user requests.
THREAD_DISTRIBUTION_MODE_DEFINED_THREAD, ///< Distribute to the thread defined by url parameter or DefaultDistributionThread if configured in settings.
THREAD_DISTRIBUTION_MODE_DEFAULT = THREAD_DISTRIBUTION_MODE_BY_HEAP_ID
};
String m_serviceName;
ManagedEndPoint::Settings m_managerManagedEndPointSettings; ///< Settings for the main RouterService endpoint.
ManagedEndPoint::Settings m_managedEndPointSettings; ///< Settings for the impl RouterService endpoints.
/**
* @brief Default: true. When true the ProcessorAffinity in @a m_managedEndPointSettings will be used to tie each
* IpManager to a single core. When false all IpManagers will be bound to the same set of cores.
*/
bool m_assignPerCoreAffinity;
IHeap::Settings m_serviceHeapSettings; ///< Properties for main heap.
IHeap::Settings m_notificationHeapSettings; ///< Properties for notification heaps.
IHeap::Settings m_implNotificationHeapSettings; ///< Properties for impl notification heaps.
uint32_t m_lazyTimerInterval; ///< Interval of the lazy timer.
size_t m_numberOfIpManagers; ///< How many ip managers to use.
ThreadDistributionMode m_threadDistributionMode; ///< How to distribute sockets across threads.
size_t m_defaultDistributionThread; ///< Default: 0. If using THREAD_DISTRIBUTION_MODE_DEFINED_THREAD, use this thread for all connections unless overridden.
PostMessageHelper::Settings m_rxPostMessageHelperSettings; ///< Settings for buffering of received messages.
UInt m_noHeartbeatBreakInterval; ///< Default: uninitialized. Break a connection if a heartbeat isn't received in this number of seconds (on supported protocols).
uint32_t m_bufferTokenBytesInterval; ///< Default: 128KB. Interval (in bytes) to send buffer tokens.
uint32_t m_bufferTokenTimerInterval; ///< Default: 100. Interval (in ms) to send buffer tokens.
uint32_t m_bufferTokenHeapMessageCount; ///< Default: 10000. Number of buffer token heap messages, needs to be 1 per connection.
bool m_shouldAllowLocalCircuitShortcut; ///< Default: true. If two TCP connected components are in the same system use endpoint comms and avoid the IP layer.
size_t m_serverConnectionCircuitLimit; ///< Default: 1000. Maximum number of circuits allowed on a single server connection.
// Proxy configuration.
enum ProxyMode
{
PROXY_MODE_NONE, ///< No proxy for HTTP tunnelling.
PROXY_MODE_AUTO_CONFIGURE_FROM_DEFAULT_BROWSER, ///< Attempt to determine proxy settings from default browser.
PROXY_MODE_AUTO_CONFIGURE_FROM_IE, ///< Attempt to determine proxy settings from Internet Explorer.
PROXY_MODE_MANUAL ///< From m_proxyAddress.
};
ProxyMode m_proxyMode;
String m_proxyAddress; ///< For PROXY_MODE_MANUAL.
String m_proxyUser; ///< Optional for other than PROXY_MODE_NONE.
String m_proxyPassword; ///< Ditto.
bool m_shouldTryHttpConnect; ///< Whether to try HTTP CONNECT in automatic tunnelling protocols. Requires a proxy. Default: false.
String m_clientAccessPolicyFilename; ///< For Silverlight clients.
size_t m_heartbeatInterval; ///< Interval (in ms) between heartbeats for pure connections. Default 10000.
size_t m_heartbeatIntervalHttpT2; ///< Interval (in ms) between heartbeats for HTTP t2 tunnelled connections from the client-side. Default 60000.
size_t m_connectTimeout; ///< Time (in ms) to give client-side connections to establish. 0 to leave as OS default. Default 0.
NetworkAffinityFilter::Settings m_networkAffinityFilterSettings; ///< Default network affinity filter to apply to all RouterService sockets.
};
/**
* @brief Router service ui component.
*/
class UiComponent ACTIV_FINAL : public Activ::UiComponent
{
public:
/**
* @brief Constructor for system-wide RouterService ui.
*
* @param routerService the router service to have the ui.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API UiComponent(RouterService &routerService, const String &uiServiceName);
/**
* @brief Constructor for process-local RouterService ui.
*
* @param routerService the router service to have the ui.
* @param parentUiComponent UiComponent to contain this component.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API UiComponent(RouterService &routerService, const Activ::UiComponent &parentUiComponent,
const String &uiServiceName);
private:
virtual void Run(UiUser &uiUser) ACTIV_OVERRIDE;
RouterService & m_routerService;
CxxYZ::vector<CxxYZ::shared_ptr<Activ::UiComponent> > m_implUiComponentList;
// Last member.
Component::Enabler m_componentEnabler;
};
/**
* @brief Constructor.
*
* @param application the application to run in.
* @param settings settings for service.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API RouterService(Application &application, const Settings &settings);
/**
* @brief Destructor.
*/
ACTIV_FRAMEWORK_API ~RouterService();
/**
* @brief Subscribe all implementation objects to endpoint notification messages.
*/
ACTIV_FRAMEWORK_API void SubscribeToEndPointMessages();
/**
* @brief Unsubscribe all implementation objects from endpoint notification messages.
*/
ACTIV_FRAMEWORK_API void UnsubscribeFromEndPointMessages();
class Impl;
protected:
virtual StatusCode OnMessage(HeapMessage &message) ACTIV_OVERRIDE;
virtual StatusCode OnRequest(HeapMessage &request) ACTIV_OVERRIDE;
virtual void OnThreadStart() ACTIV_OVERRIDE;
private:
/**
* @brief Process endpoint die message.
*
* @param message
* @param type string to display ("shutdown" or "died").
*/
void ProcessSystemEndPointIdSetMessage(HeapMessage &message, const char * const type);
/**
* @brief Process a request and distribute it to a worker thread based on heap id in the request.
*
* @param request
*
* @throw Exception.
*/
template<typename T>
void ProcessRequest(HeapMessage &request);
/**
* @brief Process a start listening request.
*
* @param request
*
* @throw Exception.
*/
void ProcessStartListenRequest(HeapMessage &request);
/**
* @brief Forward a request to an Impl determined by heap or endpoint id.
*
* @param heapMessage
* @param heapId
* @param threadDistributionMode
*/
void ForwardRequest(HeapMessage &heapMessage, const HeapId heapId,
const Settings::ThreadDistributionMode threadDistributionMode);
/**
* @brief Forward a request to a specified Impl index.
*
* @param heapMessage
* @param impleIndex
*/
void ForwardRequest(HeapMessage &heapMessage, const size_t implIndex);
/**
* @brief Process a get endpoint id set request from the user.
*
* @param request
*/
void ProcessUserGetEndPointIdSetRequest(HeapMessage &request) const;
/**
* @brief Process an add network affinity filter request from the user.
*
* @param request
* @param isRequest
*/
void ProcessUserAddNetworkAffinityFilterRequest(HeapMessage &request, const bool isRequest);
/**
* @brief Process a remove network affinity filter request from the user.
*
* @param request
* @param isRequest
*/
void ProcessUserRemoveNetworkAffinityFilterRequest(HeapMessage &request, const bool isRequest);
/**
* @brief Get the Impl to use based on heap or endpoint id.
*
* @param heapId
* @param endPointId
* @param threadDistributionMode
*
* @return Index of the Impl.
*/
size_t GetImplIndex(const HeapId heapId, const EndPointId endPointId,
const Settings::ThreadDistributionMode threadDistributionMode);
//! Display statistics.
void UiDisplayStatistics(const UiIo &uiIo) const;
#if (defined ACTIV_PLATFORM_POSIX)
//! Display servers summary.
void UiDisplayServersSummary(const UiIo &uiIo) const;
//! Display server details.
void UiDisplayServerDetails(const UiIo &uiIo) const;
#endif
//! Display network affinity filters.
void UiDisplayNetworkAffinityFilters(const UiIo &uiIo) const;
//! Display unsupported affinity filters.
void UiDisplayUnsupportedNetworkAffinityFilters(const UiIo &uiIo) const;
class ServerComponent;
/**
* @brief Info about the Impl objects maintained in the main thread.
*/
class ImplInfo
{
public:
/**
* @brief Default constructor.
*/
ImplInfo();
size_t m_numberOfForwardedRequests;
};
typedef CxxYZ::shared_ptr<Impl> ImplPtr;
typedef std::pair<ImplInfo, ImplPtr> ImplPair;
typedef std::vector<ImplPair> ImplList;
typedef std::map<size_t, size_t> ImplIndexMap;
typedef CxxYZ::shared_ptr<ServerComponent> ServerComponentPtr;
typedef std::map<Address, ServerComponentPtr> ServerComponentMap;
const Uuid m_uuid; ///< Unique ID of this router.
const Settings::ThreadDistributionMode m_threadDistributionMode; ///< How to distribute sockets across threads.
const size_t m_defaultDistributionThread; ///< If using THREAD_DISTRIBUTION_MODE_DEFINED_THREAD, use this thread for all connections unless overridden.
ImplList m_implList;
ImplIndexMap m_implIndexMap; ///< Heap/endpoint id to Impl index map.
ServerComponentMap m_serverComponentMap;
typedef std::set<NetworkAffinityFilter> NetworkAffinityFilterSet;
NetworkAffinityFilterSet m_networkAffinityFilterSet; ///< Set of active network affinity filters.
NetworkAffinityFilterSet m_unsupportedNetworkAffinityFilterSet; ///< Set of requested but unsupported network affinity filters.
const CxxYZ::unique_ptr<INetworkAffinityHelper>
m_pNetworkAffinityHelper;
#if (defined ACTIV_PLATFORM_POSIX)
IpManager m_ipManager;
HeapPool m_implNotificationHeapPool; ///< Pool of heaps for critical impl notifications.
#if (defined ACTIV_ENABLE_ONLOAD)
OnloadHelper m_onloadHelper;
#endif // (defined ACTIV_ENABLE_ONLOAD)
#endif // (defined ACTIV_PLATFORM_POSIX)
// Last member.
Component::Enabler m_componentEnabler;
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_ROUTER_SERVICE_H)
@@ -1,782 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/RouterServiceApi.h
*
* @brief Header file for router api.
*/
#if (!defined ACTIV_FRAMEWORK_ROUTER_SERVICE_API_H)
#define ACTIV_FRAMEWORK_ROUTER_SERVICE_API_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/ISerializableMessage.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Boolean.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include "ActivMiddleware/ActivFramework/Address.h"
//! Activ namespace.
namespace Activ
{
class Address;
class Component;
class HeapMessage;
class IHeap;
// ---------------------------------------------------------------------------------------------------------------------------------
//! Api to the agent's router service.
namespace RouterServiceApi
{
/**
* @brief Get the complete set of RouterService endpoints available.
*
* @param component component to send message from.
* @param endPointIdSet
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
*/
ACTIV_FRAMEWORK_API StatusCode GetEndPointIdSet(const Component &component, EndPointIdSet &endPointIdSet);
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Tcp related apis.
namespace Tcp
{
//! List of available tunnelling types.
#define ACTIV_ROUTER_SERVICE_API_TUNNEL_TYPE_LIST(d) \
d(TUNNEL_TYPE_NONE, "none") \
d(TUNNEL_TYPE_AUTO, "auto") \
d(TUNNEL_TYPE_PROXY_CONNECT, "CONNECT") \
d(TUNNEL_TYPE_HTTP_T2, "HTTPt2") \
d(TUNNEL_TYPE_WEBSOCKET, "WebSocket")
//! Enumeration of available tunnelling types.
enum TunnelType
{
ACTIV_ROUTER_SERVICE_API_TUNNEL_TYPE_LIST(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
TUNNEL_TYPE_COUNT,
TUNNEL_TYPE_UNKNOWN = -1
};
//! Protocol type.
typedef uint8_t Protocol;
//! List of available tcp protocol types.
#define ACTIV_ROUTER_SERVICE_API_PROTOCOL_LIST(d) \
d(PROTOCOL_AMS, 0, "ams") \
d(PROTOCOL_BMS, 1, "bms") \
d(PROTOCOL_BASIC, 2, "basic") \
d(PROTOCOL_UNKNOWN, -1, "unknown")
#define ACTIV_DECLARE_CONSTANT(a, b, c) ACTIV_BOOST_CONSTEXPR_OR_CONST Protocol a = b;
ACTIV_ROUTER_SERVICE_API_PROTOCOL_LIST(ACTIV_DECLARE_CONSTANT)
#undef ACTIV_DECLARE_CONSTANT
// ---------------------------------------------------------------------------------------------------------------------------------
//! Socket stats.
class SocketStats
{
public:
//! Default constructor.
ACTIV_FRAMEWORK_API SocketStats();
static const MessageType MESSAGE_TYPE = ROUTER_MESSAGE_USER_NOTIFY_SOCKET_STATS;
size_t m_txQueueBytes; ///< Current size of to transmit queue in bytes.
size_t m_txQueueMessages; ///< Current size of to transmit queue in number of messages.
size_t m_txQueueHighBytes; ///< High size of to transmit queue in bytes.
size_t m_txQueueHighMessages; ///< High size of to transmit queue in number of messages.
size_t m_inTxQueueBytes; ///< Current size of currently transmitting queue in bytes.
size_t m_inTxQueueMessages; ///< Current size of currently transmitting queue in number of messages.
size_t m_inTxQueueHighBytes; ///< High size of currently transmitting queue in bytes.
size_t m_inTxQueueHighMessages; ///< High size of currently transmitting queue in number of messages.
uint64_t m_rxBytes; ///< Total rx bytes.
uint64_t m_txBytes; ///< Total tx bytes.
size_t m_mutexContentionCount; ///< Approx. contentions on the socket's mutex.
// OS-level stats; may not be defined.
UInt m_txRtt;
UInt m_txCongestionWindowSize;
UInt m_totalRetransmissions;
UInt m_reorders;
Boolean m_isNagleEnabled;
UInt m_txCompressionPercent; ///< If compressing, compression ratio as % (compressed-bytes / source-bytes).
uint64_t m_millisecondTimeStamp; ///< The time stamp when these stats were created, referenced to the system up time.
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Connection info. Optionally provided during OnAccept and OnConnect callbacks.
struct ConnectionInfo
{
Protocol m_protocol;
IpAddress m_localIpAddress;
IpAddress m_remoteIpAddress;
TunnelType m_tunnelType;
size_t m_maxTxQueueSize;
Address m_remoteDestinationAddress;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// CLIENT SIDE
/**
* @brief Create a circuit and initiate a synchronous connect.
*
* @param component component to initiate the connection from.
* @param url of the form protocol://host:port/location?unique.
* @param connectResponse reference to a HeapMessage object to receive connect response. Source address of this
* message for a successful connect will be the circuit address.
* @param pHeap the heap to use for received messages. Default is this component's heap.
* @param timeout How long to wait for the circuit to establish, in ms.
* @param pUserData optional userdata.
* @param pConnectionInfo optional pointer to receive the connection info.
*
* @retval STATUS_CODE_SUCCESS circuit is up.
* @retval STATUS_CODE_TIMEOUT circuit did not establish in the timeout period.
* @retval STATUS_CODE_HOST_DEVICE_NOT_FOUND unknown destination machine.
* @retval STATUS_CODE_INVALID_ENDPOINT_COMPONENT unknown endpoint-component on target system.
* @retval STATUS_CODE_FAILURE ...
*/
ACTIV_FRAMEWORK_API StatusCode Connect(const Component &component, const String &url, HeapMessage &connectResponse,
IHeap * const pHeap, const TimeoutPeriod timeout, const ISerializableMessage * const pUserData = ACTIV_NULLPTR,
ConnectionInfo *pConnectionInfo = ACTIV_NULLPTR);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Create a circuit and initiate an asynchronous connect.
*
* @param component component to initiate the connection from.
* @param url of the form protocol://host:port/location?unique.
* @param circuitAddress reference to an Address object to receive the address of the circuit.
* @param pHeap the heap to use for received messages. Default is this component's heap.
* @param pUserData optional userdata.
*
* @retval STATUS_CODE_SUCCESS OnConnect() will be invoked when the circuit is up.
* @retval STATUS_CODE_HOST_DEVICE_NOT_FOUND unknown destination machine.
* @retval STATUS_CODE_INVALID_ENDPOINT_COMPONENT unknown endpoint-component on target system.
* @retval STATUS_CODE_FAILURE ...
*/
ACTIV_FRAMEWORK_API StatusCode Connect(const Component &component, const String &url, Address &circuitAddress,
IHeap * const pHeap = ACTIV_NULLPTR, const ISerializableMessage * const pUserData = ACTIV_NULLPTR);
// ---------------------------------------------------------------------------------------------------------------------------------
// SERVER SIDE
/**
* @brief Allow an address to be accessible through a server.
*
* @param component component to allow access to.
* @param url of the form protocol://host:port?unique,accepts=n
* @param serverAddress reference to an Address object to receive the address of the server.
* @param accessUrlList to receive the urls that a client can use to access the server.
* @param pHeap the heap to use for received messages. Default is this component's heap.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_SHAREABLE unique not specified for an non-multiplexable protocol.
* @retval STATUS_CODE_INVALID_PROTOCOL server already exists on the given address and port with a different protocol.
* @retval STATUS_CODE_SHUTTING_DOWN can't add new user as server is shutting down.
* @retval STATUS_CODE_ALREADY_LISTENING user already added.
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode Listen(const Component &component, const String &url, Address &serverAddress,
std::vector<String> &accessUrlList, IHeap * const pHeap = ACTIV_NULLPTR);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Allow an address to be accessible through a server.
*
* @param component component to allow access to.
* @param url of the form protocol://host:port?unique,accepts=n
* @param serverAddress reference to an Address object to receive the address of the server.
* @param pHeap the heap to use for received messages. Default is this component's heap.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_SHAREABLE unique not specified for an non-multiplexable protocol.
* @retval STATUS_CODE_INVALID_PROTOCOL server already exists on the given address and port with a different protocol.
* @retval STATUS_CODE_SHUTTING_DOWN can't add new user as server is shutting down.
* @retval STATUS_CODE_ALREADY_LISTENING user already added.
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode Listen(const Component &component, const String &url, Address &serverAddress,
IHeap * const pHeap = ACTIV_NULLPTR);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Remove access to an address through a server.
*
* @param component component to stop listening.
* @param serverAddress address of the server to remove access from.
* @param shouldBreakAccepted whether to break existing accepted connections as well as stop listening.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
*/
ACTIV_FRAMEWORK_API StatusCode Stop(const Component &component, const Address &serverAddress,
const bool shouldBreakAccepted = false);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Break all accepted connections by a server.
*
* @param component component to send message from.
* @param serverAddress address of the server to close the accepted connections of.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
*/
ACTIV_FRAMEWORK_API StatusCode BreakAll(const Component &component, const Address &serverAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get the set of RouterService endpoints that will be handling a server.
*
* @param component component to send message from.
* @param serverAddress address of the server.
* @param endPointIdSet
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
*/
ACTIV_FRAMEWORK_API StatusCode GetEndPointIdSet(const Component &component, const Address &serverAddress,
EndPointIdSet &endPointIdSet);
// ---------------------------------------------------------------------------------------------------------------------------------
// CLIENT AND SERVER SIDE
/**
* @brief Break a connection.
*
* @param component component to initiate the break from.
* @param connectionAddress the address of a circuit to break. If the connection is shared,
* all circuits over that connection will break.
*
* @retval STATUS_CODE_SUCCESS the connection has been broken.
* @retval STATUS_CODE_FAILURE
*/
ACTIV_FRAMEWORK_API StatusCode Break(const Component &component, const Address &connectionAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Disconnect a circuit.
*
* @param component component to initiate the disconnect from.
* @param circuitAddress the address of the circuit to initiate a disconnect on.
* @param timeout if 0, initiate an asynchronous disconnect. Otherwise, how long to wait for the circuit to
* close, in ms.
*
* @retval STATUS_CODE_SUCCESS for an asynchronous disconnect, OnDisconnect() will be invoked when the circuit is down.
* @retval STATUS_CODE_SUCCESS for a synchronous disconnect, circuit is down.
* Note data from this circuit may still be queued up on the destination endpoint, it is up to the
* application to discard this data if required.
* @retval STATUS_CODE_TIMEOUT for a synchronous disconnect - circuit did not close in the timeout period.
* @retval STATUS_CODE_FAILURE ...
*/
ACTIV_FRAMEWORK_API StatusCode Disconnect(const Component &component, const Address &circuitAddress,
const TimeoutPeriod timeout = 0);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get the local ip address of a connection or server.
*
* Currently the local address is not passed in an accept (server-side) or connect (client-side) notification. This
* method can be used to retrieve it.
*
* @param component component to send the message from.
* @param address the address of the circuit or server to get the local ip address of.
* @param ipAddress to receive the ip address.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode GetLocalIpAddress(const Component &component, const Address &address, IpAddress &ipAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set heap for a connection.
*
* @param component component to send the message from.
* @param address the address of a circuit.
* @param pHeap heap to use for received data on this connection.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetHeap(const Component &component, const Address &address, const IHeap * const pHeap);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get maximum transmit queue size for a connection.
*
* @param component component to send the message from.
* @param address the address of a circuit.
* @param numberOfBytes to receive the max bytes allowed on tx queue before breaking connection (0 is no limit).
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode GetMaxTxQueueSize(const Component &component, const Address &address, size_t &numberOfBytes);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set maximum transmit queue size for a connection.
*
* @param component component to send the message from.
* @param address the address of a circuit.
* @param numberOfBytes max bytes to allow on tx queue before breaking connection (0 is no limit).
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetMaxTxQueueSize(const Component &component, const Address &address, const size_t numberOfBytes);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Enable receipt of socket stats for a circuit.
*
* The component will receive a message of type RouterServiceApi::Tcp::SocketStats::MESSAGE_TYPE on a lazy basis.
* Use DeserializeSocketStats() to retrieve the socket stats for the connection.
*
* @param component component to send request from.
* @param circuitAddress the address of the circuit to get the underlying socket stats for.
*
* @return STATUS_CODE_SUCCESS or an error status code.
*/
ACTIV_FRAMEWORK_API StatusCode EnableSocketStats(const Component &component, const Address &circuitAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Deserialize a socket stats message.
*
* @param heapMessage received message of type RouterServiceApi::Tcp::SocketStats::MESSAGE_TYPE
* @param socketStats reference to a SocketStats to receive the stats.
*
* @return STATUS_CODE_SUCCESS or an error status code.
*/
ACTIV_FRAMEWORK_API StatusCode DeserializeSocketStats(const HeapMessage &heapMessage, SocketStats &socketStats);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Clear high counts for a socket.
*
* @param component component to send request from.
* @param circuitAddress the address of the circuit to get the underlying socket stats for.
*/
ACTIV_FRAMEWORK_API StatusCode ClearSocketStatsHighCounts(const Component &component, const Address &circuitAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Convert tunnelling type to a string.
*
* @param tunnelType
*
* @return String representation of @a tunnelType.
*/
ACTIV_FRAMEWORK_API String TunnelTypeToString(const TunnelType tunnelType);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Convert string to tunnelling type.
*
* @param str string representation of a tunnelling type (e.g. from TunnelTypeToString()).
*
* @return TUNNEL_TYPE_UNKNOWN if unable to convert the string.
*/
ACTIV_FRAMEWORK_API TunnelType StringToTunnelType(const String &str);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Convert protocol to a string.
*
* @param protocol
*
* @return String representation of @a protocol.
*/
ACTIV_FRAMEWORK_API const char *ProtocolToString(const Protocol protocol);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Convert string to protocol.
*
* @param str string representation of a protocol (e.g. from ProtocolToString()).
*
* @return TUNNEL_TYPE_UNKNOWN if unable to convert the string.
*/
ACTIV_FRAMEWORK_API Protocol StringToProtocol(const String &str);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Enable buffer tokens on a connection.
*
* The connection component will receive periodic messages about buffering on the connection:
* - ROUTER_MESSAGE_CONNECTION_TX_BYTES
* - ROUTER_MESSAGE_BUFFER_TOKEN
*
* See ActivFramework/RouterService/RouterCircuitMessages.h for further details.
*
* This option should only be enabled:
* - When the remote application also supports buffer tokens.
* - When the connection is not sharable, either by protocol used or by specifying 'unique' on the client url.
*
* @param component component to send request from.
* @param circuitAddress the address of the circuit to enable buffer tokens on.
*
* @return STATUS_CODE_SUCCESS or an error status code.
*/
ACTIV_FRAMEWORK_API StatusCode EnableBufferTokens(const Component &component, const Address &circuitAddress);
} // namespace Tcp
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Udp related apis.
namespace Udp
{
/**
* @brief Create a socket and bind it to a local address.
*
* @param component component to send the message from.
* @param localAddress local address to bind to.
* @param localPort local port to bind to.
* @param maxRxSize maximum size of a datagram that can be received.
* @param socketAddress reference to an Address object to receive the address of the socket.
* @param pHeap the heap to use for received messages. Default is this component's heap.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_TIMEOUT
* @retval STATUS_CODE_FAILURE ...
*/
ACTIV_FRAMEWORK_API StatusCode Create(const Component &component, const String &localAddress, const uint16_t localPort,
const uint16_t maxRxSize, Address &socketAddress, IHeap * const pHeap = ACTIV_NULLPTR);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Initiate a read on a udp socket.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to connect.
* @param shouldPurgeRxBuffer purge the socket's rx buffer before initiating the async read?
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode Read(const Component &component, const Address &socketAddress,
const bool shouldPurgeRxBuffer = false);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Connect a udp socket to a remote address (filter all traffic from other addresses).
*
* @param component component to send the message from.
* @param socketAddress address of the socket to connect.
* @param remoteAddressString the remote address to connect to in string form.
* @param remotePort the remote port to connect to (local endian).
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode Connect(const Component &component, const Address &socketAddress, const String &remoteAddressString,
const uint16_t remotePort);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Disconnect a udp socket from a remote address (allow all traffic).
*
* @param component component to send the message from.
* @param socketAddress address of the socket to disconnect.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode Disconnect(const Component &component, const Address &socketAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get the local ip address of the udp socket.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to get the local ip address for.
* @param ipAddress to receive the ip address.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode GetLocalIpAddress(const Component &component, const Address &socketAddress, IpAddress &ipAddress);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Close a udp socket.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to shutdown.
* @param gracefully true to only close the socket once any outstanding tx has completed,
* false to force the socket closed immediately.
*
* @retval STATUS_CODE_SUCCESS the socket is fully closed.
* @retval STATUS_CODE_PENDING the socket is closing and OnSocketClose() will be called.
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode Close(const Component &component, const Address &socketAddress, const bool gracefully = false);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Join a multicast group.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to join the multicast group on.
* @param multicastGroupString an ipv4 or ipv6 multicast address string.
* @param interfaceAddressString an ipv4 or ipv6 interface address string.
* @param sourceAddressString an ipv4 or ipv6 source address string. If non-empty, a source specific multicast join is
* attempted.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode JoinMulticastGroup(const Component &component, const Address &socketAddress,
const String &multicastGroupString, const String &interfaceAddressString, const String &sourceAddressString = String(""));
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Leave a multicast group.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to leave the multicast group.
* @param multicastGroupString an ipv4 or ipv6 multicast address string.
* @param interfaceAddressString an ipv4 or ipv6 interface address string.
* @param sourceAddressString an ipv4 or ipv6 source address string. If non-empty, a source specific multicast leave is
* attempted.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode LeaveMulticastGroup(const Component &component, const Address &socketAddress,
const String &multicastGroupString, const String &interfaceAddressString, const String &sourceAddressString = String(""));
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set multicast interface for transmission.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to set multicast interface on.
* @param interfaceAddressString an ipv4 or ipv6 address string.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetMulticastTxInterface(const Component &component, const Address &socketAddress,
const String &interfaceAddressString);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set TTL to be used for multicasting.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to set the ttl on.
* @param ttl the TTL.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetMulticastTtl(const Component &component, const Address &socketAddress, const uint32_t ttl);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set TTL to be used for unicasting.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to set unicast ttl on.
* @param ttl the TTL.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetUnicastTtl(const Component &component, const Address &socketAddress, const uint32_t ttl);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get the internal rx buffer size of a socket.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to get buffer size of.
* @param size to receive the buffer size.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode GetRxBufferSize(const Component &component, const Address &socketAddress, uint32_t &size);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set the internal rx buffer size of a socket.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to set buffer size on.
* @param size the buffer size.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetRxBufferSize(const Component &component, const Address &socketAddress, const uint32_t size);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get the internal tx buffer size of a socket.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to get buffer size of.
* @param size to receive the buffer size.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode GetTxBufferSize(const Component &component, const Address &socketAddress, uint32_t &size);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set the internal tx buffer size of a socket.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to set buffer size on.
* @param size the buffer size.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetTxBufferSize(const Component &component, const Address &socketAddress, const uint32_t size);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set the receive multicast loopback option of a socket.
*
* @param component component to send the message from.
* @param socketAddress address of the socket to set transmit buffer size on.
* @param enable true to enable receipt of multicast loopback data, else false.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetMulticastLoopback(const Component &component, const Address &socketAddress, const bool enable);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Set the type of service of a socket (IP_TOS socket option).
*
* @param component component to send the message from.
* @param socketAddress address of the socket.
* @param typeOfService IP_TOS value.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetTypeOfService(const Component &component, const Address &socketAddress,
const byte_t typeOfService);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Get the underying socket handle.
*
* Currently only supports udp sockets created by the router.
*
* @param component component to send the message from.
* @param socketAddress the socket to get the handle of.
* @param socket reference to a SOCKET variable to receive the handle.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode GetSocketHandle(const Component &component, const Address &socketAddress, SOCKET &socket);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Do a blocking send of some data to a specified ip address.
*
* @param socket socket handle obtained with GetSocketHandle().
* @param pData pointer to data to send.
* @param dataLength length of data to send.
* @param toAddress destination ip address.
* @param timeoutPeriod how long to wait for the event, in ms.
*
* @return STATUS_CODE_SUCCESS
* @return STATUS_CODE_TIMEOUT
* @return ...
*/
ACTIV_FRAMEWORK_API StatusCode SendTo(const SOCKET socket, const void *pData, size_t dataLength, const IpAddress &toAddress,
const TimeoutPeriod timeoutPeriod = ACTIV_WAIT_INFINITE);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Do a blocking send of some data.
*
* @param socket socket handle obtained with GetSocketHandle().
* @param pData pointer to data to send.
* @param dataLength length of data to send.
* @param timeoutPeriod how long to wait for the event, in ms.
*
* @return STATUS_CODE_SUCCESS
* @return STATUS_CODE_TIMEOUT
* @return ...
*/
ACTIV_FRAMEWORK_API StatusCode Send(const SOCKET socket, const void *pData, size_t dataLength,
const TimeoutPeriod timeoutPeriod = ACTIV_WAIT_INFINITE);
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Post some data. This call does not block, the transmission is handled by the router service.
*
* @param component component to send the message from.
* @param socketAddress the socket to send the data on.
* @param heapMessage the message to send.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode PostData(const Component &component, const Address &socketAddress, HeapMessage &heapMessage);
} // namespace Udp
} // namespace RouterServiceApi
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_ROUTER_SERVICE_API_H)
@@ -1,243 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ScopedAddress.h
*
* @brief ScopedAddress header file.
*/
#if (!defined ACTIV_FRAMEWORK_SCOPED_ADDRESS_H)
#define ACTIV_FRAMEWORK_SCOPED_ADDRESS_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/Exception.h"
#include "ActivMiddleware/ActivFramework/Address.h"
#include "ActivMiddleware/ActivFramework/Timer.h"
#include ACTIV_BOOST_INCLUDE(move/move.hpp)
//! Activ namespace.
namespace Activ
{
class Component;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Scoped address.
*
* When a ScopedAddress goes out of scope, or is assigned a new value, a SYSTEM_MESSAGE_CLOSE_ADDRESS message is sent to the
* current address (if valid).
*/
class ScopedAddress
{
public:
/**
* @brief Constructor.
*
* @param component reference to the Component used to post a SYSTEM_MESSAGE_CLOSE_ADDRESS when this object goes out of scope.
*/
ScopedAddress(const Component &component);
/**
* @brief Constructor.
*
* @param component reference to the Component used to post a SYSTEM_MESSAGE_CLOSE_ADDRESS when this object goes out of scope.
* @param address initial Address value to assign.
*/
ScopedAddress(const Component &component, const Address &address);
/**
* @brief Move constructor.
*
* @param rhs ScopedAddress to move into this.
*/
ScopedAddress(ACTIV_BOOST_RV_REF(ScopedAddress) rhs) :
m_component(rhs.m_component),
m_address(rhs.m_address),
m_timer(CxxYZ::move(rhs.m_timer)),
m_pTimerComponent(CxxYZ::move(rhs.m_pTimerComponent))
{
// Inline here for G++.
rhs.m_address.Clear();
}
/**
* @brief Destructor.
*
* If the underlying address is valid, a SYSTEM_MESSAGE_CLOSE_ADDRESS is posted to it.
*/
~ScopedAddress();
/**
* @brief Clear the current address.
*
* If the current address is valid, a SYSTEM_MESSAGE_CLOSE_ADDRESS is posted to it.
*/
ACTIV_FRAMEWORK_API
void Clear();
/**
* @brief Convert the address to a string.
*
* @return String representation of the address, in the form "endPointId:portId".
*/
String ToString() const;
/**
* @brief Is this a valid address?
*
* A valid address is one where endPointId is not INVALID_ENDPOINT_ID and portId is not INVALID_PORT_ID.
*
* @return Boolean.
*/
bool IsValid() const;
/**
* @brief Equality test operator.
*
* @param rhs Address object to compare with.
*
* @return Boolean.
*/
bool operator==(const Address &rhs) const;
/**
* @brief Inequality test operator.
*
* @param rhs Address object to compare with.
*
* @return Boolean.
*/
bool operator!=(const Address &rhs) const;
/**
* @brief Assignment from Address operator.
*
* If the current address is valid, a SYSTEM_MESSAGE_CLOSE_ADDRESS is posted to it before assigning the new value.
*
* @param rhs the Address to assign from.
*
* @return *this.
*/
ScopedAddress &operator=(const Address &rhs);
/**
* @brief Move assignment from ScopedAddress operator.
*
* If the current address is valid, a SYSTEM_MESSAGE_CLOSE_ADDRESS is posted to it before assigning the new value.
* The Address stored in rhs is released.
*
* @param rhs the Address to assign from.
*
* @return *this.
*/
ScopedAddress &operator=(ACTIV_BOOST_RV_REF(ScopedAddress) rhs)
{
if (this != &rhs)
{
// Inline here for G++.
Clear();
m_address = rhs.m_address;
rhs.m_address.Clear();
m_timer = CxxYZ::move(rhs.m_timer);
m_pTimerComponent = CxxYZ::move(rhs.m_pTimerComponent);
}
return *this;
}
/**
* @brief Const Address reference cast operator.
*
* @return Const reference to the underlying Address operator.
*/
operator const Address &() const;
private:
ACTIV_BOOST_MOVABLE_BUT_NOT_COPYABLE(ScopedAddress)
const Component & m_component;
Address m_address;
Timer m_timer;
// Using shared_ptr as unique_ptr creates dependency issues.
CxxYZ::shared_ptr<Component>
m_pTimerComponent;
friend class TimerServiceApiImpl;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline ScopedAddress::ScopedAddress(const Component &component) :
m_component(component)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ScopedAddress::ScopedAddress(const Component &component, const Address &address) :
m_component(component),
m_address(address)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ScopedAddress::~ScopedAddress()
{
Clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline String ScopedAddress::ToString() const
{
return m_address.ToString();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool ScopedAddress::IsValid() const
{
return m_address.IsValid();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool ScopedAddress::operator==(const Address &rhs) const
{
return (m_address == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool ScopedAddress::operator!=(const Address &rhs) const
{
return (m_address != rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ScopedAddress &ScopedAddress::operator=(const Address &rhs)
{
if (rhs != m_address)
{
Clear();
m_address = rhs;
}
return *this;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ScopedAddress::operator const Address &() const
{
return m_address;
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_SCOPED_ADDRESS_H)
@@ -1,341 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/Service.h
*
* @brief Header file for service class.
*/
#if (!defined ACTIV_FRAMEWORK_SERVICE_H)
#define ACTIV_FRAMEWORK_SERVICE_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/Component.h"
#include "ActivMiddleware/ActivFramework/Messages.h"
#include "ActivMiddleware/ActivFramework/ServiceTypes.h"
#include "ActivMiddleware/CxxYZ/list.h"
//! Activ namespace.
namespace Activ
{
namespace ServiceSettingsKeywords
{
using namespace Activ::ComponentSettingsKeywords;
namespace tag
{
using namespace Activ::ComponentSettingsKeywords::tag;
} // namespace tag
// Service::Settings fields.
ACTIV_BOOST_PARAMETER_NAME(serviceId)
ACTIV_BOOST_PARAMETER_NAME(serviceAccessPointList)
ACTIV_BOOST_PARAMETER_NAME(serviceAttributes)
} // namespace ServiceSettingsKeywords
template<typename T>
class ChildService;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Service class.
*/
class Service : public Component
{
public:
class SettingsImpl : public Component::SettingsImpl
{
public:
//! Copy constructor.
SettingsImpl(const SettingsImpl &settings);
//! Boost parameter constructor.
template<typename ARGS>
SettingsImpl(const ARGS &args);
ServiceInfo m_serviceInfo;
ACTIV_DECLARE_PARAMETER_ACCESSOR(ServiceSettingsKeywords, serviceId)
ACTIV_DECLARE_PARAMETER_ACCESSOR(ServiceSettingsKeywords, serviceAccessPointList)
ACTIV_DECLARE_PARAMETER_ACCESSOR(ServiceSettingsKeywords, serviceAttributes)
};
/**
* @brief Optional settings for a Service.
*
* name name of the service.
* pHeap heap to use for messaging, or 0 (the default) for the calling application's heap.
* licenseId the service's license id.
*
* This uses Boost's parameter library and can be used as follows:
*
* Service::Settings settings(Service::Settings::name() = "Test", Service::Settings::serviceId() = "My.Service");
*/
class Settings : public SettingsImpl
{
public:
//! Copy constructor.
Settings(const Settings &settings);
// Boost parameter constructor.
ACTIV_BOOST_PARAMETER_CONSTRUCTOR(
Settings, (SettingsImpl), ServiceSettingsKeywords::tag,
(required
(name, *)
(serviceId, *)
(serviceAccessPointList, *)
)
(optional
(serviceAttributes, *)
(portId, *)
(heap, *)
(licenseId, *)
(callbackInfoList, *)
)
)
};
//! An empty access point list for a service.
ACTIV_FRAMEWORK_API static const ServiceAccessPointList emptyServiceAccessPointList;
/**
* @brief Constructor.
*
* Attaches this object to a managed endpoint.
*
* @param managedEndPoint reference to a ManagedEndPoint object to which this component is to be attached.
* @param settings
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API Service(ManagedEndPoint &managedEndPoint, const SettingsImpl &settings);
/**
* @brief Constructor.
*
* Attaches this service to a managed endpoint at the next available slot. The service will get allocated
* a uuid.
*
* @param managedEndPoint reference to a ManagedEndPoint object to which this component is to be attached.
* @param name name of the service.
* @param serviceInfo service id and access points for this service.
* @param pHeap heap to use for messaging, or 0 for the system heap.
* @param componentId the component id.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API Service(ManagedEndPoint &managedEndPoint, const String &name, const ServiceInfo &serviceInfo,
IHeap * const pHeap = 0, const String &componentId = defaultComponentId);
//! Destructor.
ACTIV_FRAMEWORK_API ~Service();
//! Get the service id.
ACTIV_FRAMEWORK_API const ServiceId &GetServiceId() const;
//! Get the service access point list.
ACTIV_FRAMEWORK_API const ServiceAccessPointList &GetServiceAccessPointList() const;
//! Get the ServiceInstance.
ACTIV_FRAMEWORK_API const ServiceInstance &GetServiceInstance() const;
/**
* @brief Register the service with any configured directory services.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ...
*/
ACTIV_FRAMEWORK_API virtual StatusCode Register();
/**
* @brief Deregister the service from any directory services.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ...
*/
ACTIV_FRAMEWORK_API virtual StatusCode Deregister();
/**
* @brief Update the service's attributes.
*
* Note as with all other Service methods, this function is not thread-aware. It is up to the user to ensure that
* concurrent calls to this method are not made.
*
* @param serviceAttributes
*
* @return STATUS_CODE_SUCCESS or an error status if unable to notify the DirectoryService of the change.
*/
ACTIV_FRAMEWORK_API StatusCode UpdateAttributes(const ServiceAttributes &serviceAttributes);
//! Close all access points and accepted connections.
ACTIV_FRAMEWORK_API void Close();
//! Break accepted connections across all servers.
ACTIV_FRAMEWORK_API void BreakAll();
//! Get the set of RouterService endpoint ids that will be handling all of this service's access points.
ACTIV_FRAMEWORK_API void GetRouterServiceEndPointIdSet(EndPointIdSet &endPointIdSet) const;
protected:
/**
* @brief A client is attempting to connect.
*
* The default behaviour is to call ProcessOpenServiceRequest(). See Component::OnAccept() for more information.
*
* @param acceptMessage
*
* @return Unused by the framework.
*/
ACTIV_FRAMEWORK_API virtual StatusCode OnAccept(HeapMessage &acceptMessage) ACTIV_OVERRIDE;
/**
* @brief Process an open service request.
*
* This method is protected to allow processing of extended open service requests. By default it validates
* again the default open service request and builds a default open service response.
*
* @param acceptMessage as passed to OnAccept().
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API virtual StatusCode ProcessOpenServiceRequest(HeapMessage &acceptMessage);
/**
* @brief Validate a received open service message.
*
* An open service message is contained in the body of the message passed to OnAccept().
*
* @param acceptMessage as passed to OnAccept().
* @param openServiceRequest message to deserialize into.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode ValidateOpenServiceRequest(const HeapMessage &acceptMessage,
OpenServiceRequest &openServiceRequest) const;
/**
* @brief Build a response to an open service request.
*
* @param acceptMessage as passed to OnAccept() and validated by ValidateOpenServiceRequest().
* @param openServiceResponse message to serialize as the response.
* @param openServiceVersion version of the open service message.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode BuildOpenServiceResponse(HeapMessage &acceptMessage, OpenServiceResponse &openServiceResponse,
const byte_t openServiceVersion) const;
private:
//! List of servers.
class AccessList
{
public:
/**
* @brief Constructor.
*
* @param service
*/
AccessList(Service &service);
//! Destructor.
~AccessList();
/**
* @brief Add a server address to the list.
*
* @param serverAddress address of server to add.
*/
void Add(const Address &serverAddress);
//! Clear access list. Stop listening and break accepted connections.
void Clear();
//! Break accepted connections across all servers.
void BreakAll();
//! Get the set of RouterService endpoint ids that will be handling all of this service's access points.
void GetRouterServiceEndPointIdSet(EndPointIdSet &endPointIdSet) const;
private:
typedef CxxYZ::list<Address> ServerList;
Service & m_service;
ServerList m_serverList;
};
/**
* @brief Constructor for ChildService.
*
* @param parentService reference to the parent service.
* @param managedEndPoint reference to a ManagedEndPoint object to which this port is to be attached.
* @param pHeap heap to use for messaging, or 0 for the parent service heap.
* @param name name of the Port, local to the endpoint.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API Service(Service &service, ManagedEndPoint &managedEndPoint, IHeap * const pHeap, const String &name);
/**
* @brief Make ServiceInstance object with normalized access points.
*
* @param serviceInfo
* @param uuid
* @param address
*
* @return Normalized ServiceInstance.
*/
const ServiceInstance MakeServiceInstance(const ServiceInfo &serviceInfo, const Uuid &uuid, const Address &address);
/**
* @brief Make ServiceInstance object with no access points or attributes for a ChildService.
*
* @param parentServiceInstance
*
* @return ServiceInstance.
*/
static const ServiceInstance MakeChildServiceInstance(const ServiceInstance &parentServiceInstance);
AccessList m_accessList; ///< List of servers this service is available on.
ServiceInstance m_serviceInstance; ///< Service id, access points.
template<typename T>
friend class ChildService;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline Service::SettingsImpl::SettingsImpl(const SettingsImpl &settings) :
Component::SettingsImpl(static_cast<const Component::SettingsImpl &>(settings)),
m_serviceInfo(settings.m_serviceInfo)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename ARGS>
inline Service::SettingsImpl::SettingsImpl(const ARGS &args) :
Component::SettingsImpl(args),
m_serviceInfo(args[ServiceSettingsKeywords::_serviceId], args[ServiceSettingsKeywords::_serviceAccessPointList],
args[ServiceSettingsKeywords::_serviceAttributes || Boost::value_factory<ServiceAttributes>()])
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline Service::Settings::Settings(const Settings &settings) :
Service::SettingsImpl(static_cast<const SettingsImpl &>(settings))
{
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_SERVICE_H)
@@ -1,213 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ServiceApi.h
*
* @brief Header file for service access api.
*/
#if (!defined ACTIV_FRAMEWORK_SERVICE_API_H)
#define ACTIV_FRAMEWORK_SERVICE_API_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/Messages.h"
#include "ActivMiddleware/ActivFramework/ServiceTypes.h"
//! Activ namespace.
namespace Activ
{
class Component;
class HeapMessage;
class ScopedAddress;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Api to the access services.
*/
class ServiceApi
{
public:
/**
* @brief Add an attribute to the local DirectoryService.
*
* @param component
* @param key the key to add/update.
* @param value the (single) value to add to key @a key.
*
* @return STATUS_CODE_SUCCESS or an error status.
*/
ACTIV_FRAMEWORK_API static StatusCode AddDirectoryServiceAttribute(const Component &component, const String &key,
const String &value);
/**
* @brief Add an attribute query to the set of attributes we are matching against remote directory services.
*
* @param component
* @param attributeQuery
*
* @return STATUS_CODE_SUCCESS or an error status.
*/
ACTIV_FRAMEWORK_API static StatusCode AddRemoteDirectoryServiceAttributeQuery(const Component &component,
const String &attributeQuery);
/**
* @brief Find all instances of a service by service id and return all access points.
*
* @param component the component doing the find.
* @param serviceId id of the service to find.
* @param agentScope scope of the services to find (within this agent space or globally).
* @param attributeQuery an LDAP style attribute query. Pass empty string to not filter by attributes.
* @param serviceInstanceList to receive the results of the find.
* @param timeout how long to wait for the response, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode FindServices(const Component &component, const ServiceId &serviceId,
const AgentScope agentScope, const String &attributeQuery, ServiceInstanceList &serviceInstanceList,
const TimeoutPeriod timeout = 5000);
/**
* @brief Find all instances of a service by service id and return all access points.
*
* @param component the component doing the find.
* @param serviceId id of the service to find.
* @param agentScope scope of the services to find (within this agent space or globally).
* @param attributeQuery an LDAP style attribute query. Pass empty string to not filter by attributes.
* @param serviceOrdering how to order the results.
* @param serviceInstanceList to receive the results of the find.
* @param timeout how long to wait for the response, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode FindServices(const Component &component, const ServiceId &serviceId,
const AgentScope agentScope, const String &attributeQuery, const ServiceOrdering serviceOrdering,
ServiceInstanceList &serviceInstanceList, const TimeoutPeriod timeout = 5000);
/**
* @brief Deserialize a notification of a service being registered.
*
* A service register message has type SERVICE_MESSAGE_REGISTER.
*
* @param heapMessage
* @param serviceInstance to receive details of the service.
*
* @return STATUS_CODE_SUCCESS or an error status if @a heapMessage couldn't be deserialized.
*/
ACTIV_FRAMEWORK_API static StatusCode DeserializeServiceRegisterMessage(const HeapMessage &heapMessage,
ServiceInstance &serviceInstance);
/**
* @brief Deserialize a notification of a service being deregistered.
*
* A service deregister message has type SERVICE_MESSAGE_DEREGISTER.
*
* @param heapMessage
* @param uuid to receive the uuid of the service that is no longer available.
*
* @return STATUS_CODE_SUCCESS or an error status if @a heapMessage couldn't be deserialized.
*/
ACTIV_FRAMEWORK_API static StatusCode DeserializeServiceDeregisterMessage(const HeapMessage &heapMessage, Uuid &uuid);
/**
* @brief Deserialize a notification of a service's attributes being updated.
*
* A service attribute update message has type SERVICE_MESSAGE_UPDATE_ATTRIBUTES.
*
* @param heapMessage
* @param uuid to receive the uuid of the service.
* @param serviceAttributes to receive the new attributes.
*
* @return STATUS_CODE_SUCCESS or an error status if @a heapMessage couldn't be deserialized.
*/
ACTIV_FRAMEWORK_API static StatusCode DeserializeServiceAttributesUpdateMessage(const HeapMessage &heapMessage,
Uuid &uuid, ServiceAttributes &serviceAttributes);
/**
* @brief Open a service.
*
* The m_serviceId member must contain the id of the service you wish to open and the m_url member must
* contain the access point of the service you wish to use.
*
* On a successful return, the m_serviceAddress member will contain the proxied address for communction with the
* service.
*
* If doing an asynchronous open (with timeout == 0), when the connection is established (OnConnect() invoked
* with circuitAddress == m_serviceAddress of \a serviceHandle), ValidateOpenServiceResponse() should be called.
* This verifies the service connected to is of the right type.
*
* @param component reference to Component wishing to open service.
* @param serviceHandle reference to a ServiceHandle object.
* @param timeout how long to wait for the connection to be established, in ms.
* @param pOpenServiceRequest optional user data to send in the open service message.
* @param pOpenServiceResponse optional data to receive from a sync response.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode OpenService(Component &component, ServiceHandle &serviceHandle,
const TimeoutPeriod timeout = COMPONENT_DEFAULT_TIMEOUT, OpenServiceRequest * const pOpenServiceRequest = 0,
OpenServiceResponse * const pOpenServiceResponse = 0);
/**
* @brief Close a service.
*
* The close is handled asynchronously, as there may be data queued up on the endpoint from the service.
* At some point an OnDisconnect() callback will be invoked with circuitAddress == serviceHandle.m_serviceAddress.
*
* @param component reference to Component that opened the service.
* @param serviceHandle reference to a ServiceHandle object as filled in by a successful OpenService().
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_CONNECTED
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode CloseService(Component &component, const ServiceHandle &serviceHandle);
/**
* @brief Validate an open service response.
*
* @param connectMessage as passed to Component::OnConnect().
* @param openServiceResponse to deserialize into.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode ValidateOpenServiceResponse(const HeapMessage &connectMessage,
OpenServiceResponse &openServiceResponse);
private:
/**
* @brief Initiate an asynchronous open service.
*
* @param component reference to Component wishing to open service.
* @param serviceHandle the service to open.
* @param pOpenServiceRequest open service request data.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
static StatusCode OpenServiceAsync(Component &component, ServiceHandle &serviceHandle,
const OpenServiceRequest * const pOpenServiceRequest);
/**
* @brief Synchronously open a service.
*
* @param component reference to Component wishing to open service.
* @param serviceHandle the service to open.
* @param pOpenServiceRequest open service request data.
* @param pOpenServiceResponse to receive open response data.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
static StatusCode OpenServiceSync(Component &component, ServiceHandle &serviceHandle, const TimeoutPeriod timeout,
const OpenServiceRequest * const pOpenServiceRequest, OpenServiceResponse * const pOpenServiceResponse);
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_SERVICE_API_H)
@@ -1,193 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ServiceId.h
*
* @brief Header file for ServiceId.
*/
#if (!defined ACTIV_FRAMEWORK_SERVICE_ID_H)
#define ACTIV_FRAMEWORK_SERVICE_ID_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include "ActivMiddleware/ActivBase/MessageValidator.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Service id class.
*
* ServiceId uniquely identifies a particular type of service.
*/
class ServiceId
{
public:
class Serializer;
//! Default constructor.
ServiceId();
/**
* @brief Constructor.
*
* @param id service id in c-string form.
*/
ServiceId(const char * const id);
/**
* @brief Constructor.
*
* @param id service id in string form.
*/
ServiceId(const String &id);
/**
* @brief Set the service id.
*
* @param id service id in string form.
*/
void Set(const String &id);
//! Get service id in string form.
const String &ToString() const;
//! Clear down.
void Clear();
/**
* @brief Equality operator.
*
* @param rhs to compare with.
*
* @return Boolean.
*/
bool operator==(const ServiceId &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs to compare with.
*
* @return Boolean.
*/
bool operator!=(const ServiceId &rhs) const;
/**
* @brief Less than operator.
*
* @param rhs to compare with.
*
* @return Boolean.
*/
bool operator<(const ServiceId &rhs) const;
/**
* @brief Serialize.
*
* @param messageBuilder
*
* @return STATUS_CODE_SUCCESS or an error status.
*/
StatusCode Serialize(MessageBuilder &messageBuilder) const;
/**
* @brief Deserialize.
*
* @param messageValidator
*
* @return STATUS_CODE_SUCCESS or an error status.
*/
StatusCode Deserialize(MessageValidator &messageValidator);
private:
String m_id;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline ServiceId::ServiceId()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ServiceId::ServiceId(const char * const id) :
m_id(id)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ServiceId::ServiceId(const String &id) :
m_id(id)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void ServiceId::Set(const String &id)
{
m_id = id;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const String &ServiceId::ToString() const
{
return m_id;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void ServiceId::Clear()
{
m_id.clear();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool ServiceId::operator==(const ServiceId &rhs) const
{
return m_id == rhs.m_id;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool ServiceId::operator!=(const ServiceId &rhs) const
{
return m_id != rhs.m_id;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool ServiceId::operator<(const ServiceId &rhs) const
{
return m_id < rhs.m_id;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode ServiceId::Serialize(MessageBuilder &messageBuilder) const
{
// NB! We can't convert to GenericMessages as it is already remoted in this format.
// Unlikely it's ever going to change from just being a string so no worries.
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageBuilder.Append(m_id));
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode ServiceId::Deserialize(MessageValidator &messageValidator)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageValidator.ValidateString(m_id));
return STATUS_CODE_SUCCESS;
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_SERVICE_ID_H)
@@ -1,757 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ServiceTypes.h
*
* @brief Header file for various service related classes.
*/
#if (!defined ACTIV_FRAMEWORK_SERVICE_TYPES_H)
#define ACTIV_FRAMEWORK_SERVICE_TYPES_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/Address.h"
#include "ActivMiddleware/ActivFramework/Component.h"
#include "ActivMiddleware/ActivFramework/PubSubServiceApi.h"
#include "ActivMiddleware/ActivFramework/ServiceId.h"
#include "ActivMiddleware/ActivFramework/Subject.h"
#include "ActivMiddleware/ActivFramework/Timer.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include "ActivMiddleware/ActivBase/IniFileParser.h"
#include "ActivMiddleware/ActivBase/StringException.h"
#include "ActivMiddleware/ActivBase/Uuid.h"
//! Activ namespace.
namespace Activ
{
class Service;
//! FindServices() ordering enumeration.
enum ServiceOrdering
{
SERVICE_ORDERING_DEFAULT, ///< For a given ServiceId, ServiceLocation.ini instances appear first in a ServiceInstanceList.
SERVICE_ORDERING_PREFER_LOCAL, ///< For a given ServiceId, order local instances first in a ServiceInstanceList.
SERVICE_ORDERING_LOAD ///< For a given ServiceId, order local instances by load attribute (lowest first; no load attribute is assumed high).
};
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Service access point class.
*/
class ServiceAccessPoint
{
public:
/**
* @brief Default constructor.
*/
ACTIV_FRAMEWORK_API ServiceAccessPoint();
/**
* @brief Constructor.
*
* @param url url string.
* @param agentScope
*/
ACTIV_FRAMEWORK_API ServiceAccessPoint(const String &url, const AgentScope agentScope);
/**
* @brief Read service access point from an ini file key.
*
* Key is of the form url = scope:url
* or url = url
*
* E.g. url = local:ams://:9005
* url = global:ams://:9006
* url = ams://:9007 (default to AGENT_SCOPE_GLOBAL)
*
* @param keyIterator iterator to ini file key.
*
* @throw std::exception
*/
ACTIV_FRAMEWORK_API void Read(const IniFileParser::ConstKeyIterator &keyIterator);
/**
* @brief Clear members in access point.
*/
ACTIV_FRAMEWORK_API void Clear();
/**
* @brief Is the URL referring to a resource that is likely to be on the local machine?
*
* The current implementation of this function is not optimized and should be used sparingly. Note this differs from the
* AgentScope of the access point, which refers to whether an access point is local to the ACTIV system or resides in a
* different system.
*
* @return Whether this is a local access point.
*/
ACTIV_FRAMEWORK_API bool IsLocal() const;
/**
* @brief Is the URL referring to a resource that is likely to be on the provided network?
*
* @param network a string referring to an address on a local interface (ip address or a hostname).
*
* @return Boolean
*/
ACTIV_FRAMEWORK_API bool IsOnNetwork(const String &network) const;
/**
* @brief Is the URL referring to a resource that is likely to be on the provided network?
*
* @param network an IpAddress of an address on a local interface.
*
* @return Boolean
*/
ACTIV_FRAMEWORK_API bool IsOnNetwork(const IpAddress &network) const;
/**
* @brief Is the URL referring to a resource that is likely to be on the provided network?
*
* @param network an IpAddressMask of an address on a local interface.
*
* @return Boolean
*/
ACTIV_FRAMEWORK_API bool IsOnNetwork(const IpAddressMask &network) const;
/**
* @brief Get the address of the local interface that this access point will use.
*
* @return IpAddress reference.
*
* @throw std::exception
*/
ACTIV_FRAMEWORK_API const IpAddress GetLocalInterface() const;
/**
* @brief Convert to a string for display purposes.
*
* @return String.
*/
ACTIV_FRAMEWORK_API const String ToString() const;
String m_url;
AgentScope m_agentScope;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief List of service access points.
*/
typedef std::vector<ServiceAccessPoint> ServiceAccessPointList;
/**
* @brief Read service access point list from an ini file section.
*
* Note the ServiceAccessPointList is NOT cleared initially, and ServiceAccessPoints are only append to this
* object if the whole section is parsed successfully.
*
* @param sectionIterator iterator to an ini file section.
* @param serviceAccessPointList list to populate.
*
* @throw std::exception
*/
ACTIV_FRAMEWORK_API void ReadServiceAccessPointList(const IniFileParser::ConstSectionIterator &sectionIterator,
ServiceAccessPointList &serviceAccessPointList);
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Service attributes.
*
* The string form of attributes is a comma separated list of keys and/or (key=value[,value]) pairs.
* E.g. "key1,(key2=value1,value2)".
*/
class ServiceAttributes
{
public:
typedef std::vector<String> ServiceAttributeValueList;
typedef std::map<String, ServiceAttributeValueList> Map;
typedef Map::iterator Iterator;
typedef Map::const_iterator ConstIterator;
class Serializer;
//! Default constructor.
ACTIV_FRAMEWORK_API ServiceAttributes();
/**
* @brief Copy constructor.
*
* @param serviceAttributes
*/
ACTIV_FRAMEWORK_API ServiceAttributes(const ServiceAttributes &serviceAttributes);
/**
* @brief Constructor.
*
* @param attributeString String containing list of attributes.
*
* @throw std::exception if @a attributeString is invalid.
*/
ACTIV_FRAMEWORK_API ServiceAttributes(const String &attributeString);
//! Copy assignment operator.
ACTIV_FRAMEWORK_API ServiceAttributes &operator=(const ServiceAttributes &rhs);
/**
* @brief Read setting from an ini-file.
*
* @param sectionIterator
* @param keyName
* @param shouldReplaceValue
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API void Read(const IniFileParser::ConstSectionIterator &sectionIterator, const String keyName,
const bool shouldReplaceValue = true);
/**
* @brief Update an existing key, or add it if not present.
*
* @param key the key to update/add.
* @param value the (optionally comma-delimited list of) value(s) to use.
* @param shouldReplaceValue should the entire list of values for @a key be replaced,
* or the new values added to the existing list of values for @a key.
*/
ACTIV_FRAMEWORK_API void UpdateKey(const String &key, const String &value, const bool shouldReplaceValue = false);
/**
* @brief Update an existing key, or add it if not present.
*
* @param key the key to update/add.
* @param valueList the list of values to use.
* @param shouldReplaceValue should the entire list of values for @a key be replaced,
* or the new values added to the existing list of values for @a key.
*/
ACTIV_FRAMEWORK_API void UpdateKey(const String &key, const ServiceAttributeValueList &valueList,
const bool shouldReplaceValue = false);
/**
* @brief Remove an existing key.
*
* @param key the key to remove.
*
* @return True if the key was present and has been removed.
*/
ACTIV_FRAMEWORK_API bool RemoveKey(const String &key);
/**
* @brief Is there a key with a particular value?
*
* @param key the key to check, or if empty, a match is assumed (true returned).
* @param value the value to check, or if empty, a match is assumed (true returned).
*
* @return true if there is a key with name @a key that has a value @a value in its list of values.
*/
ACTIV_FRAMEWORK_API bool HasValue(const String &key, const String &value = String()) const;
/**
* @brief Get mandatory value.
*
* @tparam attribute type.
*
* @param attribute
*
* @return The value.
*
* @throw StringException
*/
template<typename T>
typename Boost::disable_if_c<Boost::is_same<T, String>::value, T>::type GetMandatoryValue(const String &attribute) const;
/**
* @brief Get mandatory value.
*
* @tparam attribute type.
*
* @param attribute
*
* @return The value.
*
* @throw StringException
*/
template<typename T>
typename Boost::enable_if_c<Boost::is_same<T, String>::value, const String &>::type
GetMandatoryValue(const String &attribute) const;
/**
* @brief Get optional value.
*
* @tparam attribute type.
*
* @param attribute
*
* @return The optional value.
*/
template<typename T>
typename Boost::disable_if_c<Boost::is_same<T, String>::value, Boost::optional<T> >::type
GetOptionalValue(const String &attribute) const;
/**
* @brief Get optional value.
*
* @tparam attribute type.
*
* @param attribute
*
* @return The optional value.
*/
template<typename T>
typename Boost::enable_if_c<Boost::is_same<T, String>::value, Boost::optional<String> >::type
GetOptionalValue(const String &attribute) const;
//! Clear all attributes.
ACTIV_FRAMEWORK_API void Clear();
//! Get string representation of the map.
ACTIV_FRAMEWORK_API const String ToString() const;
/**
* @brief Find key in the map.
*
* @param key the key to find.
*
* @return ConstIterator pointing to the found pair in the map.
*/
ACTIV_FRAMEWORK_API const ConstIterator Find(const String &key) const;
/**
* @brief Find where the map begins.
*
* @return ConstIterator to the beginning of the map.
*/
ACTIV_FRAMEWORK_API const ConstIterator Begin() const;
/**
* @brief Find where the map ends.
*
* @return ConstIterator to the end of the map.
*/
ACTIV_FRAMEWORK_API const ConstIterator End() const;
//! Any attributes?
ACTIV_FRAMEWORK_API bool IsEmpty() const;
//! Do these attributes match the provided query?
ACTIV_FRAMEWORK_API bool DoesQueryMatch(const String &attributeQuery) const;
//! Do these attributes match the provided query?
ACTIV_FRAMEWORK_API bool DoesQueryMatch(const ServiceAttributes &attributeQuery) const;
/**
* @brief Equality operator.
*
* @param rhs
*
* @return Boolean.
*/
ACTIV_FRAMEWORK_API bool operator==(const ServiceAttributes &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs
*
* @return Boolean.
*/
ACTIV_FRAMEWORK_API bool operator!=(const ServiceAttributes &rhs) const;
//! Key name for load attribute.
ACTIV_FRAMEWORK_API static const String m_loadKey;
//! Key name for type attribute.
ACTIV_FRAMEWORK_API static const String m_typeKey;
private:
/**
* @brief Parse comma-delimited list of values.
*
* @param key the key to add the values to.
* @param pValues pointer to the start of the value list.
* @param length length of the values pointed to by @a pValues.
* @param shouldReplaceValue should the entire list of values for @a key be replaced,
* or the new values added to the existing list of values for @a key.
*/
void ParseValueList(const String &key, const char * const pValues, const size_t length,
const bool shouldReplaceValue);
Map m_map;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
typename Boost::disable_if_c<Boost::is_same<T, String>::value, T>::type
ServiceAttributes::GetMandatoryValue(const String &attribute) const
{
const ConstIterator iterator = Find(attribute);
if (End() == iterator)
ACTIV_BOOST_THROW_EXCEPTION(StringException("mandatory attribute \"" + attribute + "\" - not found"));
const ServiceAttributeValueList &serviceAttributeValueList = iterator->second;
if (serviceAttributeValueList.size() > 1)
ACTIV_BOOST_THROW_EXCEPTION(StringException("mandatory attribute \"" + attribute + "\" - has too many values"));
if (serviceAttributeValueList.empty())
ACTIV_BOOST_THROW_EXCEPTION(StringException("mandatory attribute \"" + attribute + "\" - has no value"));
T value;
if (!StringToType(serviceAttributeValueList[0], value))
ACTIV_BOOST_THROW_EXCEPTION(StringException("mandatory attribute \"" + attribute + "\" - could not convert to type"));
return value;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
typename Boost::enable_if_c<Boost::is_same<T, String>::value, const String &>::type
ServiceAttributes::GetMandatoryValue(const String &attribute) const
{
const ConstIterator iterator = Find(attribute);
if (End() == iterator)
ACTIV_BOOST_THROW_EXCEPTION(StringException("mandatory attribute \"" + attribute + "\" - not found"));
const ServiceAttributeValueList &serviceAttributeValueList = iterator->second;
if (serviceAttributeValueList.size() > 1)
ACTIV_BOOST_THROW_EXCEPTION(StringException("mandatory attribute \"" + attribute + "\" - has too many values"));
if (serviceAttributeValueList.empty() || serviceAttributeValueList[0].empty())
ACTIV_BOOST_THROW_EXCEPTION(StringException("mandatory attribute \"" + attribute + "\" - has no value"));
return serviceAttributeValueList[0];
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
typename Boost::disable_if_c<Boost::is_same<T, String>::value, Boost::optional<T> >::type
ServiceAttributes::GetOptionalValue(const String &attribute) const
{
const ConstIterator iterator = Find(attribute);
if (End() == iterator)
return Boost::none;
if (1 != iterator->second.size())
return Boost::none;
T value;
if (!StringToType(iterator->second[0], value))
return Boost::none;
return value;
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
typename Boost::enable_if_c<Boost::is_same<T, String>::value, Boost::optional<String> >::type
ServiceAttributes::GetOptionalValue(const String &attribute) const
{
Boost::optional<T> value;
const ConstIterator iterator = Find(attribute);
if (End() == iterator)
return Boost::none;
if (1 != iterator->second.size())
return Boost::none;
if (iterator->second[0].empty())
return Boost::none;
return iterator->second[0];
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Information required to construct a Service.
*/
class ServiceInfo
{
public:
/**
* @brief Default constructor.
*/
ACTIV_FRAMEWORK_API ServiceInfo();
/**
* @brief Constructor.
*
* @param serviceId
* @param serviceAccessPointList
* @param serviceAttributes
*/
ACTIV_FRAMEWORK_API ServiceInfo(const ServiceId &serviceId, const ServiceAccessPointList &serviceAccessPointList,
const ServiceAttributes &serviceAttributes);
ServiceId m_serviceId; ///< Id of the service.
ServiceAccessPointList m_serviceAccessPointList; ///< All access points for this service.
ServiceAttributes m_serviceAttributes;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Class representing an instance of a service and its locations.
*/
class ServiceInstance
{
public:
//! Default constructor.
ACTIV_FRAMEWORK_API ServiceInstance();
//! Copy constructor.
ACTIV_FRAMEWORK_API ServiceInstance(const ServiceInstance &rhs);
//! Copy assignment operator.
ACTIV_FRAMEWORK_API ServiceInstance &operator=(const ServiceInstance &rhs);
/**
* @brief Get the first access point that appears to be on the provided network.
*
* @param network a string referring to an address on a local interface (ip address or a hostname).
*
* @return Reference to the ServiceAccessPoint.
*
* @throw std::exception if a match cannot be found.
*/
ACTIV_FRAMEWORK_API const ServiceAccessPoint &GetAccessPointOnNetwork(const String &network) const;
/**
* @brief Get the first access point that appears to be on the provided network.
*
* @param network an IpAddress of an address on a local interface.
*
* @return Reference to the ServiceAccessPoint.
*
* @throw std::exception if a match cannot be found.
*/
ACTIV_FRAMEWORK_API const ServiceAccessPoint &GetAccessPointOnNetwork(const IpAddress &network) const;
/**
* @brief Get the first access point that appears to be on the provided network.
*
* @param network an IpAddressMask of an address on a local interface.
*
* @return Reference to the ServiceAccessPoint.
*
* @throw std::exception if a match cannot be found.
*/
ACTIV_FRAMEWORK_API const ServiceAccessPoint &GetAccessPointOnNetwork(const IpAddressMask &network) const;
/**
* @brief Get the first access point that uses the provided remote address.
*
* @param remoteAddress a string referring to the address of a remote machine (ip address or a hostname).
*
* @return Reference to the ServiceAccessPoint.
*
* @throw std::exception if a match cannot be found.
*/
ACTIV_FRAMEWORK_API const ServiceAccessPoint &GetAccessPointFromRemoteAddress(const String &remoteAddress) const;
/**
* @brief Get the first access point that uses the provided remote address.
*
* @param remoteAddress IpAddress referring to the address of a remote machine.
*
* @return Reference to the ServiceAccessPoint.
*
* @throw std::exception if a match cannot be found.
*/
ACTIV_FRAMEWORK_API const ServiceAccessPoint &GetAccessPointFromRemoteAddress(const IpAddress &remoteAddress) const;
/**
* @brief Serialize.
*
* @param messageBuilder
*
* @return STATUS_CODE_SUCCESS or an error status.
*/
ACTIV_FRAMEWORK_API
StatusCode Serialize(MessageBuilder &messageBuilder) const;
/**
* @brief Deserialize.
*
* @param messageValidator
*
* @return STATUS_CODE_SUCCESS or an error status.
*/
ACTIV_FRAMEWORK_API
StatusCode Deserialize(MessageValidator &messageValidator);
ServiceId m_serviceId; ///< Id of the service.
String m_hostName; ///< Of the machine providing the service.
ServiceAccessPointList m_serviceAccessPointList; ///< All access points for this service.
ServiceAttributes m_serviceAttributes;
Uuid m_uuid; ///< Uuid of this service.
Address m_localAddress; ///< Only valid for service local to the system.
private:
/**
* @brief Constructor.
*
* @param serviceInfo
* @param uuid
* @param localAddress
*/
ACTIV_FRAMEWORK_API ServiceInstance(const ServiceInfo &serviceInfo, const Uuid &uuid, const Address &localAddress);
friend class Service;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! List of ServiceInstances.
typedef std::vector<ServiceInstance> ServiceInstanceList;
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Parameters to OpenService() apis.
*/
class ServiceHandle
{
public:
/**
* @brief Default constructor.
*/
ACTIV_FRAMEWORK_API ServiceHandle();
/**
* @brief Constructor.
*
* @param serviceId id for the service.
* @param url
*/
ACTIV_FRAMEWORK_API ServiceHandle(const ServiceId &serviceId, const String &url);
/**
* @brief Clear down.
*/
ACTIV_FRAMEWORK_API void Clear();
ServiceId m_serviceId; ///< Id of the service.
String m_url; ///< Url to the service.
Address m_serviceAddress; ///< Local proxied address of the service.
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Service subject type. By subscribing to this subject, a component can receive
* notifications of service registration / deregistration.
*/
class ServiceSubject : public Subject
{
public:
/**
* @brief Constructor.
*/
ACTIV_FRAMEWORK_API ServiceSubject();
/**
* @brief Constructor to receive notifications about a particular instance of a service.
*
* @param uuid Uuid of a service.
*/
ACTIV_FRAMEWORK_API ServiceSubject(const Uuid &uuid);
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Service instance watch.
class ServiceInstanceWatch : private Component
{
public:
typedef Component ImmediateBase;
typedef CxxYZ::function<void (const ServiceInstance &)> CallbackFunction; ///< Callback function type definition.
/**
* @brief Constructor.
*
* @param managedEndPoint
*/
ACTIV_FRAMEWORK_API ServiceInstanceWatch(ManagedEndPoint &managedEndPoint);
/**
* @brief Constructor.
*
* @param managedEndPoint
* @param callback
*/
ACTIV_FRAMEWORK_API ServiceInstanceWatch(ManagedEndPoint &managedEndPoint, CallbackFunction callback);
/**
* @brief Set.
*
* @param serviceInstance
* @param attributeQuery
*/
ACTIV_FRAMEWORK_API void Set(const ServiceInstance &serviceInstance, const String &attributeQuery);
//! Clear.
ACTIV_FRAMEWORK_API void Clear();
/**
* @brief Add watcher.
*
* @param callback
*/
ACTIV_FRAMEWORK_API void AddWatcher(CallbackFunction callback);
private:
// Component overrides.
virtual StatusCode OnMessage(HeapMessage &message) ACTIV_OVERRIDE;
//! Process service instance change timer.
void ProcessServiceInstanceChangeTimer();
/**
* @brief Process a service deregister message.
*
* @param heapMessage a received message.
*/
void ProcessServiceDeregisterMessage(HeapMessage &message);
/**
* @brief Process a service update attributes message.
*
* @param heapMessage a received message.
*/
void ProcessServiceUpdateAttributesMessage(HeapMessage &message);
//! Start service instance change timer.
void StartTimer();
ScopedSubscription m_scopedSubscription;
ServiceInstance m_serviceInstance;
String m_attributeQuery;
std::vector<CallbackFunction> m_callbackList;
Timer m_serviceInstanceChangeTimer;
// Last member.
Component::Enabler m_componentEnabler;
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_SERVICE_TYPES_H)
@@ -1,139 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/SocketEventManagee.h
*
* @brief Header file for SocketEventManagee class.
*/
#if (!defined ACTIV_FRAMEWORK_SOCKET_EVENT_MANAGEE_H)
#define ACTIV_FRAMEWORK_SOCKET_EVENT_MANAGEE_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/EventManagee.h"
#if (defined ACTIV_PLATFORM_WINDOWS)
#include "ActivMiddleware/ActivBase/Windows/Ip/WsaBufHelper.h"
#include "ActivMiddleware/Misc/ScopedHelper.h"
#else
#include "ActivMiddleware/ActivBase/Posix/Ip/IoVecHelper.h"
#endif
#include "ActivMiddleware/ActivFramework/Component.h"
#include "ActivMiddleware/ActivFramework/HeapMessage.h"
#include ACTIV_BOOST_INCLUDE(scoped_array.hpp)
#include ACTIV_BOOST_INCLUDE(smart_ptr/intrusive_ptr.hpp)
#include ACTIV_BOOST_INCLUDE(smart_ptr/intrusive_ref_counter.hpp)
//! Activ namespace.
namespace Activ
{
/**
* @brief Class to hook a local socket in to an endpoint's EventManager.
*
* If there is intention to destroy a SocketEventManagee inside the context of the OnEvents() callback, then it should be
* referenced counted with SocketEventManageePtr.
*/
class SocketEventManagee : public EventManagee,
public Boost::intrusive_ref_counter<SocketEventManagee, Boost::thread_unsafe_counter>
{
public:
/**
* @brief Constructor, used for RouterService based sockets.
*
* No read is initiated on the socket; you must call InitiateRead(). Datagrams will be passed to component.OnData().
*
* @param component the Component to invoke OnData() on with a received datagram.
* @param socketAddress the Address of a socket created by the RouterServiceApi.
* @param maxReadBytes the maximum number of bytes to read from the socket in one event. 0 for no limit.
* @param maximumTransmissionUnitSize the maximum datagram size that can be received.
* @param idealTransmissionUnitSize the expected normal datagram size.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API SocketEventManagee(Component &component, const Address &socketAddress, const size_t maxReadBytes,
const size_t maximumTransmissionUnitSize, const size_t idealTransmissionUnitSize);
/**
* @brief Constructor, used for sockets created in this thread. The life time of the socket handle is managed externally.
*
* No read is initiated on the socket; you must call InitiateRead(). Datagrams will be passed to component.OnData().
*
* @param component the Component to invoke OnData() on with a received datagram.
* @param socketHandle the socket handle.
* @param maxReadBytes the maximum number of bytes to read from the socket in one event. 0 for no limit.
* @param maximumTransmissionUnitSize the maximum datagram size that can be received.
* @param idealTransmissionUnitSize the expected normal datagram size.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API SocketEventManagee(Component &component, const HANDLE socketHandle, const size_t maxReadBytes,
const size_t maximumTransmissionUnitSize, const size_t idealTransmissionUnitSize);
//! Destructor.
ACTIV_FRAMEWORK_API ~SocketEventManagee();
/**
* @brief Initiate a read on the socket.
*
* The socket receive buffer is emptied first (without invoking OnData()). This is to avoid issues with receive buffer
* overflows between socket creation and calling this function (which might cause retransmissions, for example).
*
* @return STATUS_CODE_SUCCESS or an error value.
*/
ACTIV_FRAMEWORK_API StatusCode InitiateRead();
/**
* @brief Do a blocking send of some data to a specified ip address.
*
* @param ipAddress destination ip address.
* @param pData pointer to data to send.
* @param dataLength length of data to send.
*
* @return STATUS_CODE_SUCCESS or an error value.
*/
ACTIV_FRAMEWORK_API StatusCode PostData(const IpAddress &ipAddress, const void * const pData, const size_t dataLength);
//! Get the socket address.
const Address &GetSocketAddress() const;
protected:
ACTIV_FRAMEWORK_API virtual void OnEvents(const Events events) ACTIV_OVERRIDE;
private:
void ProcessReadEvent();
void InvokeCallback(HeapMessage &heapMessage) const;
void EmptySocketReceiveBuffer();
SOCKET GetSocket() const;
Component & m_component;
Boost::scoped_ptr<Component> m_pDummyComponent;
const Address m_socketAddress;
const size_t m_maxReadBytes;
const size_t m_maximumTransmissionUnitSize;
const size_t m_idealTransmissionUnitSize;
Boost::scoped_array<char> m_pMaximumTransmissionUnitBuffer;
IpBufferHelper m_ipBufferHelper;
HeapMessage m_rxHeapMessage;
#if (defined ACTIV_PLATFORM_WINDOWS)
ScopedSocket m_socket;
#endif
};
// ---------------------------------------------------------------------------------------------------------------------------------
typedef Boost::intrusive_ptr<SocketEventManagee> SocketEventManageePtr;
// ---------------------------------------------------------------------------------------------------------------------------------
inline const Address &SocketEventManagee::GetSocketAddress() const
{
return m_socketAddress;
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_SOCKET_EVENT_MANAGEE_H)
@@ -1,422 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/Subject.h
*
* @brief Subject type header file.
*/
#if (!defined ACTIV_FRAMEWORK_SUBJECT_H)
#define ACTIV_FRAMEWORK_SUBJECT_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/MessageBuilder.h"
#include "ActivMiddleware/ActivBase/MessageValidator.h"
#include "ActivMiddleware/Misc/MemoryHelper.h"
//! Activ namespace.
namespace Activ
{
class MessageBuilder;
class MessageValidator;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Subject class.
*/
class Subject
{
public:
typedef byte_t SubjectLength; ///< Type of the length.
static const SubjectLength MAX_LENGTH = 48; ///< Maximum subject length.
static const char SEPARATOR_CHAR = '/'; ///< Subject section separator character.
//! Default constructor.
Subject();
/**
* @brief Constructor for binary subject.
*
* @param pSubjectData subject data.
* @param subjectDataLength subject data length.
*
* @throw StatusCodeException
*/
Subject(const void *pSubjectData, const size_t subjectDataLength);
/**
* @brief Constructor for c-string subject.
*
* @param pSubject textual subject.
*
* @throw StatusCodeException
*/
Subject(const char *pSubject);
/**
* @brief Constructor for stl string subject.
*
* @param subject subject string.
*
* @throw StatusCodeException
*/
Subject(const String &subject);
//! Clear the subject down.
void Clear();
/**
* @brief Serialize a subject.
*
* @param messageBuilder
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode Serialize(MessageBuilder &messageBuilder) const;
/**
* @brief Deserialize a subject.
*
* @param messageValidator
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode Deserialize(MessageValidator &messageValidator);
//! Get the length of the subject.
size_t GetLength() const;
//! Get the length of the subject when serialized.
size_t GetSerializedLength() const;
/**
* @brief Set subject.
*
* @param pSubject textual subject.
*
* @throw StatusCodeException
*/
void Set(const char *pSubject);
/**
* @brief Set subject.
*
* @param pSubjectData subject data.
* @param subjectDataLength subject data length.
*
* @throw StatusCodeException
*/
void Set(const void *pSubjectData, const size_t subjectDataLength);
/**
* @brief Set subject from a string.
*
* @param subject subject string.
*
* @throw StatusCodeException
*/
void Set(const String &subject);
/**
* @brief Set subject from another Subject object.
*
* @param subject Subject to assign from.
*/
void Set(const Subject &subject);
//! Get pointer to raw subject data.
const void *Get() const;
/**
* @brief Convert the subject to a string.
*
* @return A string containing the subject. Note if the subject is not printable, nor will the returned string be!
*/
String ToString() const;
/**
* @brief Equality operator.
*
* @param subject subject to compare.
*
* @return boolean.
*/
bool operator==(const Subject &subject) const;
/**
* @brief Inequality operator.
*
* @param subject subject to compare.
*
* @return boolean.
*/
bool operator!=(const Subject &subject) const;
/**
* @brief Less than operator.
*
* @param subject subject to compare.
*
* @return boolean.
*/
bool operator<(const Subject &subject) const;
/**
* @brief Greater than operator.
*
* @param subject subject to compare.
*
* @return boolean.
*/
bool operator>(const Subject &subject) const;
/**
* @brief Less than or equal operator.
*
* @param subject subject to compare.
*
* @return boolean.
*/
bool operator<=(const Subject &subject) const;
/**
* @brief Greater than or equal operator.
*
* @param subject subject to compare.
*
* @return boolean.
*/
bool operator>=(const Subject &subject) const;
private:
/**
* @brief Initialize method.
*
* @param pSubjectData subject data.
* @param subjectDataLength subject data length.
*
* @throw StatusCodeException
*/
void Initialize(const void *pSubjectData, const size_t subjectDataLength);
/**
* @brief Compare two subjects.
*
* @param subject Subject to compare.
*
* @retval 0 if the subjects are identical.
* @retval +ve if this is lexicographically greater than \a subject.
* @retval -ve if this is lexicographically less than \a subject.
*/
int Compare(const Subject &subject) const;
#pragma pack(1)
byte_t m_subject[MAX_LENGTH]; ///< Subject.
SubjectLength m_length; ///< Length of the subject.
#pragma pack()
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline Subject::Subject()
{
Clear();
::memset(m_subject, 0, sizeof(m_subject));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Subject::Subject(const void *pSubjectData, const size_t subjectDataLength)
{
Initialize(pSubjectData, subjectDataLength);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Subject::Subject(const char *pSubject)
{
Initialize(pSubject, ::strlen(pSubject));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Subject::Subject(const String &subject)
{
Initialize(subject.c_str(), subject.size());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Subject::Clear()
{
m_length = 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Subject::Serialize(MessageBuilder &messageBuilder) const
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageBuilder.Append<MessageBuilder::ENDIAN_LITTLE>(m_length));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageBuilder.AppendBuffer(m_subject, m_length));
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Subject::Deserialize(MessageValidator &messageValidator)
{
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, (messageValidator.ValidateBinaryIntegralRange<sizeof(byte_t),
MessageValidator::ENDIAN_LITTLE, byte_t, 0, MAX_LENGTH>(m_length)));
ACTIV_RETURN_RESULT_IF_UNLIKELY(STATUS_CODE_SUCCESS, !=, messageValidator.ValidateBytesCopy(m_length, &m_subject));
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Subject::GetLength() const
{
return m_length;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Subject::GetSerializedLength() const
{
return sizeof(m_length) + m_length;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Subject::Set(const char *pSubject)
{
Initialize(pSubject, ::strlen(pSubject));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Subject::Set(const void *pSubjectData, const size_t subjectDataLength)
{
Initialize(pSubjectData, subjectDataLength);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Subject::Set(const String &subject)
{
Initialize(subject.c_str(), subject.size());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Subject::Set(const Subject &subject)
{
m_length = subject.m_length;
MemoryCopy(m_subject, subject.m_subject, m_length);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const void *Subject::Get() const
{
return m_subject;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline String Subject::ToString() const
{
return String(reinterpret_cast<const char *>(m_subject), m_length);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Subject::operator==(const Subject &subject) const
{
return 0 == Compare(subject);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Subject::operator!=(const Subject &subject) const
{
return 0 != Compare(subject);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Subject::operator<(const Subject &subject) const
{
return Compare(subject) < 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Subject::operator>(const Subject &subject) const
{
return Compare(subject) > 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Subject::operator<=(const Subject &subject) const
{
return Compare(subject) <= 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Subject::operator>=(const Subject &subject) const
{
return Compare(subject) >= 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Subject::Initialize(const void *pSubjectData, const size_t subjectDataLength)
{
if (0 == pSubjectData)
{
m_length = 0;
}
else
{
if (subjectDataLength > MAX_LENGTH)
ACTIV_THROW(StatusCodeException, STATUS_CODE_INVALID_LENGTH);
m_length = static_cast<SubjectLength>(subjectDataLength);
MemoryCopy(m_subject, pSubjectData, m_length);
}
::memset(m_subject + m_length, 0, sizeof(m_subject) - m_length);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline int Subject::Compare(const Subject &subject) const
{
if (m_length != subject.m_length)
{
const size_t compareLength = std::min(m_length, subject.m_length);
const int compareValue = ::memcmp(m_subject, subject.m_subject, compareLength);
if (0 == compareValue)
return (m_length == compareLength) ? -1 : 1;
else
return compareValue;
}
else
{
return ::memcmp(m_subject, subject.m_subject, m_length);
}
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_SUBJECT_H)
@@ -1,95 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/Subjects.h
*
* @brief Header file for framework subject classes.
*/
#if (!defined ACTIV_FRAMEWORK_SUBJECTS_H)
#define ACTIV_FRAMEWORK_SUBJECTS_H
#include "ActivMiddleware/ActivFramework/Subject.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Endpoint subject.
*/
class EndPointSubject : public Subject
{
public:
/**
* @brief Constructor.
*/
EndPointSubject();
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline EndPointSubject::EndPointSubject() :
Subject("/system/endpoint")
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Shutdown subject.
*/
class ShutdownSubject : public Subject
{
public:
/**
* @brief Constructor.
*/
ShutdownSubject();
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline ShutdownSubject::ShutdownSubject() :
Subject("/system/shutdown")
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Process subject.
*/
class ProcessSubject : public Subject
{
public:
/**
* @brief Default constructor.
*/
ProcessSubject();
/**
* @brief Constructor.
*
* @param processId
*/
ProcessSubject(const ProcessId processId);
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline ProcessSubject::ProcessSubject() :
Subject("/system/process")
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline ProcessSubject::ProcessSubject(const ProcessId processId) :
Subject("/system/process/" + TypeToString(processId))
{
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_SUBJECTS_H)
@@ -1,110 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/SyncRequestId.h
*
* @brief Header file for synchronous request id class.
*/
#if (!defined ACTIV_FRAMEWORK_SYNC_REQUEST_ID_H)
#define ACTIV_FRAMEWORK_SYNC_REQUEST_ID_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/RequestId.h"
//! Activ namespace.
namespace Activ
{
class HeapMessage;
class SystemImpl;
class IAddressableEndPoint;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Synchronous request id class.
*/
class SyncRequestId
{
public:
/**
* @brief Default constructor.
*/
ACTIV_FRAMEWORK_API
SyncRequestId();
/**
* @brief Copy constructor.
*
* Ownership of an attached endpoint is transferred to the new object.
*
* @param syncRequestId the SyncRequestId to copy from.
*/
ACTIV_FRAMEWORK_API
SyncRequestId(SyncRequestId &syncRequestId);
/**
* @brief Destructor. An attached endpoint is returned to the system pool.
*/
ACTIV_FRAMEWORK_API
~SyncRequestId();
/**
* @brief Explicitly return an attached sync endpoint to the system pool.
*/
ACTIV_FRAMEWORK_API
void Return();
/**
* @brief Wait for the response to a sync call.
*
* @param heapMessage reference to a HeapMessage object to receive the response.
* If the call times out, heapMessage will be left unchanged.
* @param timeout how long to wait for the response, in ms.
*
* @retval STATUS_CODE_SUCCESS got the response in \a heapMessage.
* @retval STATUS_CODE_TIMEOUT no response received in timeout period, \a heapMessage is empty.
* @retval STATUS_CODE_INVALID_ENDPOINT.
*/
ACTIV_FRAMEWORK_API
StatusCode GetResponse(HeapMessage &heapMessage, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE);
/**
* @brief Get the underlying RequestId object.
*
* @return Reference to the underlying RequestId.
*/
const RequestId &GetRequestId() const;
/**
* @brief Assignment operator.
*
* @param rhs SyncRequestId object to copy from.
*
* @return *this.
*/
ACTIV_FRAMEWORK_API
SyncRequestId &operator=(SyncRequestId &rhs);
private:
/**
* @brief Allocate an endpoint and send id from the system.
*/
void Set(SystemImpl * const pSystem, const RequestId::SendId sendId, IAddressableEndPoint * const pEndPoint);
SystemImpl * m_pSystem;
IAddressableEndPoint * m_pEndPoint;
RequestId m_requestId;
friend class SystemImpl;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline const RequestId &SyncRequestId::GetRequestId() const
{
return m_requestId;
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_SYNC_REQUEST_ID_H)
@@ -1,12 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/TableUiOptions.h
*
* @brief Forwarding header for TableUiOptions.h.
*/
#if (!defined ACTIV_FRAMEWORK_TABLE_UI_OPTIONS_H)
#define ACTIV_FRAMEWORK_TABLE_UI_OPTIONS_H
#include "ActivMiddleware/ActivDatabase/TableUiOptions.h"
#endif // (!defined ACTIV_FRAMEWORK_TABLE_UI_OPTIONS_H)
@@ -1,82 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ThinApplication.h
*
* @brief Header file for thin application class.
*/
#if (!defined ACTIV_FRAMEWORK_THIN_APPLICATION_H)
#define ACTIV_FRAMEWORK_THIN_APPLICATION_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/Application.h"
#include "ActivMiddleware/ActivFramework/RouterService.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Thin application class.
*
* The ThinApplication class should be used when linking to an existing shared memory system. It provides
* access to always on agent services.
*/
class ThinApplication : public Application
{
public:
//! Settings.
class Settings : public Application::Settings
{
public:
//! Default constructor.
ACTIV_FRAMEWORK_API Settings();
/**
* @brief Read settings from an ini file section.
*
* @param iniFileParser ini file.
*
* @throw Exception
*/
ACTIV_FRAMEWORK_API void Read(const IniFileParser &iniFileParser);
IHeap::Settings m_applicationHeapSettings; ///< Settings for application heap. Default: use system heap.
Boost::optional<RouterService::Settings> m_routerServiceSettings; ///< Settings for optional local RouterService.
};
/**
* @brief Constructor.
*
* @param settings the Settings object to use.
* @param timeout how long to wait for the system to exist, in ms.
* @param componentId the component id.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API ThinApplication(const Settings &settings, Timeout &timeout = Timeout::GetInfinite(),
const String &componentId = defaultComponentId);
//! Destructor.
ACTIV_FRAMEWORK_API virtual ~ThinApplication() ACTIV_OVERRIDE;
/**
* @brief Make UiComponent for the process-local RouterService.
*
* @param parentUiComponent UiComponent that will allow switching to the RouterService's ui.
*
* @return shared_ptr to the UiComponent, or null if there is no process-local RouterService.
*/
ACTIV_FRAMEWORK_API CxxYZ::shared_ptr<UiComponent> MakeRouterServiceUiComponent(const UiComponent &parentUiComponent);
protected:
ACTIV_FRAMEWORK_API virtual StatusCode OnMessage(HeapMessage &message) ACTIV_OVERRIDE;
private:
class Private;
Boost::scoped_ptr<Private> m_pPrivate; ///< Hidden implementation details.
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_THIN_APPLICATION_H)
@@ -1,105 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/ThreadTimer.h
*
* @brief ThreadTimer header file.
*/
#if (!defined ACTIV_FRAMEWORK_THREAD_TIMER_H)
#define ACTIV_FRAMEWORK_THREAD_TIMER_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Time.h"
#include "ActivMiddleware/ActivFramework/Timer.h"
#include "ActivMiddleware/CxxYZ/functional.h"
//! Activ namespace.
namespace Activ
{
// Forward declaration.
class ManagedEndPoint;
//! ThreadTimer namespace.
namespace ThreadTimer
{
typedef Timer::TickChimeCallbackFunction CallbackFunction;
typedef Timer::Microseconds Microseconds;
typedef Timer::Milliseconds Milliseconds;
typedef Timer::Seconds Seconds;
typedef Timer::Minutes Minutes;
typedef Timer::Hours Hours;
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
//! Countdown timer.
class CountdownTimer
{
public:
/**
* @brief Constructor.
*
* @param managedEndPoint the ManagedEndPoint to add a timer to.
* @param name the name of the timer (for logging).
* @param interval the interval of the timer in milliseconds.
* @param callbackFunction the function to call when timer expires.
*
* @throw std::exception
* @throw StatusCodeException
*/
CountdownTimer(ManagedEndPoint &managedEndPoint, const String &name, const Timer::Interval interval,
const CallbackFunction &callbackFunction) :
m_timer(Timer::CreateCountdown(managedEndPoint, name, interval, callbackFunction))
{
}
//! Cancel.
void Cancel()
{
m_timer.Cancel();
}
private:
Timer m_timer;
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Repeating timer.
class ChimeTimer
{
public:
/**
* @brief Constructor.
*
* @param managedEndPoint the ManagedEndPoint to add a timer to.
* @param name the name of the timer (for logging).
* @param interval the interval of the timer in milliseconds.
* @param callbackFunction the function to call when timer expires.
*
* @throw std::exception
* @throw StatusCodeException
*/
ChimeTimer(ManagedEndPoint &managedEndPoint, const String &name, const Timer::Interval interval,
const CallbackFunction &callbackFunction) :
m_timer(Timer::CreateTickChime(managedEndPoint, name, interval, callbackFunction))
{
}
//! Cancel.
void Cancel()
{
m_timer.Cancel();
}
private:
Timer m_timer;
};
} // namespace ThreadTimer
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_THREAD_TIMER_H)
@@ -1,12 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/Timeband.h
*
* @brief Forwarding header for Timeband.h.
*/
#if (!defined ACTIV_FRAMEWORK_TIMEBAND_H)
#define ACTIV_FRAMEWORK_TIMEBAND_H
#include "ActivMiddleware/ActivBase/Timeband.h"
#endif // (!defined ACTIV_FRAMEWORK_TIMEBAND_H)
@@ -1,245 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/Timer.h
*
* @brief Timer header file.
*/
#if (!defined ACTIV_FRAMEWORK_TIMER_H)
#define ACTIV_FRAMEWORK_TIMER_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/TimeCommon.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#include ACTIV_BOOST_INCLUDE(optional/optional.hpp)
//! Activ namespace.
namespace Activ
{
// Forward declarations.
class DateTime;
class ManagedEndPoint;
class ManagedEndPointTimerService;
class Time;
//! Timer class.
class Timer
{
public:
//! Tick and countdown timer callback function definition.
typedef CxxYZ::function<void (uint64_t microsecondTimeStamp)> TickChimeCallbackFunction;
//! Local and utc timer and alarm callback function definition.
typedef CxxYZ::function<void (const DateTime &dateTime)> ClockChimeCallbackFunction;
//! Timer id definition.
typedef size_t Id;
//! Timer type definition.
typedef uint8_t Type;
//! Timer interval base class.
class Interval
{
protected:
Interval(const uint64_t intervalInMicroseconds) :
m_intervalInMicroseconds(intervalInMicroseconds) { }
public:
const uint64_t m_intervalInMicroseconds;
};
//! Timer interval helper.
template <typename T>
class IntervalHelper : public Interval
{
public:
explicit IntervalHelper(const uint64_t interval) :
Interval(T::MICROSECONDS_PER_UNIT * interval) {}
};
//! Supported timer intervals.
typedef IntervalHelper<TimeCommon::Microseconds> Microseconds;
typedef IntervalHelper<TimeCommon::Milliseconds> Milliseconds;
typedef IntervalHelper<TimeCommon::Seconds> Seconds;
typedef IntervalHelper<TimeCommon::Minutes> Minutes;
typedef IntervalHelper<TimeCommon::Hours> Hours;
typedef IntervalHelper<TimeCommon::Days> Days;
//! Default constructor.
ACTIV_FRAMEWORK_API
Timer();
//! Move constructor.
Timer(ACTIV_BOOST_RV_REF(Timer) rhs) :
m_pManagedEndPoint(rhs.m_pManagedEndPoint),
m_type(rhs.m_type),
m_interval(rhs.m_interval),
m_id(rhs.m_id)
{
rhs.m_id = Boost::none;
}
//! Move assignment.
Timer &operator=(ACTIV_BOOST_RV_REF(Timer) rhs)
{
if (this != CxxYZ::addressof(rhs))
{
Cancel();
m_pManagedEndPoint = rhs.m_pManagedEndPoint;
m_type = rhs.m_type;
m_interval = rhs.m_interval;
m_id = rhs.m_id;
rhs.m_id = Boost::none;
}
return *this;
}
//! Destructor.
ACTIV_FRAMEWORK_API
~Timer();
//! Is set.
bool IsSet() const;
//! Cancel.
ACTIV_FRAMEWORK_API
void Cancel();
/**
* @brief Create tick chime (repeating).
*
* @param managedEndPoint
* @param name (optional)
* @param interval, one of Microseconds, Milliseconds, Seconds, Minutes, Hours or Days.
* @param callbackFunction
*
* @throw std::exception
* @throw StatusCodeException
*/
ACTIV_FRAMEWORK_API
static Timer CreateTickChime(ManagedEndPoint &managedEndPoint, const String &name, const Interval interval,
const TickChimeCallbackFunction &callbackFunction);
/**
* @brief Create countdown (one shot).
*
* @param managedEndPoint
* @param name (optional)
* @param interval, one of Microseconds, Milliseconds, Seconds, Minutes, Hours or Days.
* @param callbackFunction
*
* @throw std::exception
* @throw StatusCodeException
*/
ACTIV_FRAMEWORK_API
static Timer CreateCountdown(ManagedEndPoint &managedEndPoint, const String &name, const Interval interval,
const TickChimeCallbackFunction &callbackFunction);
/**
* @brief Create local clock chime (repeating).
*
* @param managedEndPoint
* @param name (optional)
* @param startDateTime date and time of first tick.
* @param interval, one of Microseconds, Milliseconds, Seconds, Minutes, Hours or Days.
* @param callbackFunction
*
* @throw std::exception
* @throw StatusCodeException
*/
ACTIV_FRAMEWORK_API
static Timer CreateLocalClockChime(ManagedEndPoint &managedEndPoint, const String &name, const DateTime &startDateTime,
const Interval interval, const ClockChimeCallbackFunction &callbackFunction);
/**
* @brief Create daily chime (repeating).
*
* @param managedEndPoint
* @param name (optional)
* @param localTime local time of daily chime.
* @param callbackFunction
*
* @throw std::exception
* @throw StatusCodeException
*/
ACTIV_FRAMEWORK_API
static Timer CreateDailyChime(ManagedEndPoint &managedEndPoint, const String &name, const Time &localTime,
const ClockChimeCallbackFunction &callbackFunction);
/**
* @brief Create utc clock chime (repeating).
*
* @param managedEndPoint
* @param name (optional)
* @param startDateTime date and time of first tick.
* @param interval, one of Microseconds, Milliseconds, Seconds, Minutes, Hours or Days.
* @param callbackFunction
*
* @throw std::exception
* @throw StatusCodeException
*/
ACTIV_FRAMEWORK_API
static Timer CreateUtcClockChime(ManagedEndPoint &managedEndPoint, const String &name, const DateTime &startDateTime,
const Interval interval, const ClockChimeCallbackFunction &callbackFunction);
/**
* @brief Create local clock alarm (one shot).
*
* @param managedEndPoint
* @param name (optional)
* @param alarmDateTime date and time of the alarm.
* @param callbackFunction
*
* @throw std::exception
* @throw StatusCodeException
*/
ACTIV_FRAMEWORK_API
static Timer CreateLocalClockAlarm(ManagedEndPoint &managedEndPoint, const String &name, const DateTime &alarmDateTime,
const ClockChimeCallbackFunction &callbackFunction);
/**
* @brief Create utc clock alarm (one shot).
*
* @param managedEndPoint
* @param name (optional)
* @param alarmDateTime date and time of the alarm.
* @param callbackFunction
*
* @throw std::exception
* @throw StatusCodeException
*/
ACTIV_FRAMEWORK_API
static Timer CreateUtcClockAlarm(ManagedEndPoint &managedEndPoint, const String &name, const DateTime &alarmDateTime,
const ClockChimeCallbackFunction &callbackFunction);
private:
ACTIV_BOOST_MOVABLE_BUT_NOT_COPYABLE(Timer)
//! Constructor.
ACTIV_FRAMEWORK_API
Timer(ManagedEndPoint &managedEndPoint, const Type type, const Interval timerInterval);
ManagedEndPoint * m_pManagedEndPoint;
Type m_type; ///< The type of this timer.
uint64_t m_interval; ///< Timer interval in microseconds.
Boost::optional<Id> m_id; ///< The timer service id for this timer.
friend class ManagedEndPointTimerService;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Timer::IsSet() const
{
return bool(m_id);
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_TIMER_H)
@@ -1,304 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/TimerServiceApi.h
*
* @brief Header file for the timer service api.
*/
#if (!defined ACTIV_FRAMEWORK_TIMER_SERVICE_API_H)
#define ACTIV_FRAMEWORK_TIMER_SERVICE_API_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/DateTime.h"
//! Activ namespace.
namespace Activ
{
class Component;
class ScopedAddress;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Api to the agent's timer service.
*/
class TimerServiceApi
{
public:
/**
* @brief Request helper class.
*
* @param REQUEST_TYPE the request type.
* @param PARAMETERS the type of request parameters.
*/
template<MessageType REQUEST_TYPE, typename PARAMETERS>
class RequestHelper
{
public:
typedef PARAMETERS Parameters; ///< The parameters typedef.
/**
* @brief Create a new timer
*
* @param component the component wanting to set the timer.
* @param parameters the request parameters for the timer.
* @param address reference to a scoped address object to receive the address of the new timer.
*/
ACTIV_FRAMEWORK_API static StatusCode Create(Component &component, const Parameters &parameters, ScopedAddress &address);
static const MessageType REQUEST = REQUEST_TYPE; ///< The request type.
};
/**
* @brief Request parameters for setting an alarm timer (triggered by system clock).
*/
class AlarmParameters
{
public:
/**
* @brief Constructor.
*
* @param dateTime the alarm date time.
*/
ACTIV_FRAMEWORK_API AlarmParameters(const DateTime &dateTime);
DateTime m_dateTime; ///< DateTime of alarm.
};
/**
* @brief Request parameters for setting a countdown timer (triggered by system tick count).
*/
class CountdownParameters
{
public:
/**
* @brief Constructor.
*
* @param countdownDuration the countdown duration in milliseconds.
*/
ACTIV_FRAMEWORK_API CountdownParameters(const uint64_t countdownDuration);
/**
* @brief Constructor.
*
* @param t1 Date::Days or Time::Hours, Time::Minutes, Time::Seconds, Time::Milliseconds references,
* which will be used to calculate the total countdown duration in milliseconds.
* @param dummy unused.
*/
template<typename T1>
CountdownParameters(const T1 &t1, typename Boost::disable_if<Boost::is_integral<T1> >::type *dummy = 0);
template<typename T1, typename T2>
CountdownParameters(const T1 &t1, const T2 &t2);
template<typename T1, typename T2, typename T3>
CountdownParameters(const T1 &t1, const T2 &t2, const T3 &t3);
template<typename T1, typename T2, typename T3, typename T4>
CountdownParameters(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4);
template<typename T1, typename T2, typename T3, typename T4, typename T5>
CountdownParameters(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5);
uint64_t m_countdownDuration; ///< Countdown duration in milliseconds.
};
/**
* @brief Request parameters for setting a chime, by default triggered by system tick count.
*/
class ChimeParameters
{
public:
/**
* @brief Constructor.
*
* @param intervalBetweenChimes the interval between chimes.
*/
ACTIV_FRAMEWORK_API ChimeParameters(const uint64_t intervalBetweenChimes);
uint64_t m_intervalBetweenChimes; ///< Interval between chimes.
};
/**
* @brief Request parameters for setting a chime triggered by system clock.
*/
class ClockBasedChimeParameters : public ChimeParameters
{
public:
/**
* @brief Constructor.
*
* @param intervalBetweenChimes the interval between chimes.
* @param startDateTime the date time of the first chime.
*/
ACTIV_FRAMEWORK_API ClockBasedChimeParameters(const uint64_t intervalBetweenChimes, const DateTime &startDateTime);
DateTime m_startDateTime; ///< Date time of first chime.
};
/**
* @brief Local alarm, triggered when local system clock reaches the target date time.
*/
typedef RequestHelper<TIMER_REQUEST_SET_LOCAL_ALARM, AlarmParameters> LocalAlarm;
/**
* @brief Countdown timer, triggered when a specified number of system ticks have elapsed after the timer was created.
*/
typedef RequestHelper<TIMER_REQUEST_SET_COUNTDOWN, CountdownParameters> Countdown;
/**
* @brief Available tick-based chimes, triggered by system tick count.
*/
class TickChime
{
public:
typedef RequestHelper<TIMER_REQUEST_SET_TICK_BASED_MILLISECOND_CHIME, ChimeParameters> Millisecond;
typedef RequestHelper<TIMER_REQUEST_SET_TICK_BASED_SECOND_CHIME, ChimeParameters> Second;
typedef RequestHelper<TIMER_REQUEST_SET_TICK_BASED_MINUTE_CHIME, ChimeParameters> Minute;
typedef RequestHelper<TIMER_REQUEST_SET_TICK_BASED_HOUR_CHIME, ChimeParameters> Hour;
};
/**
* @brief Available clock-based chimes, triggered by local system clock.
*/
class LocalClockChime
{
public:
typedef RequestHelper<TIMER_REQUEST_SET_LOCAL_CLOCK_BASED_SECOND_CHIME, ClockBasedChimeParameters> Second;
typedef RequestHelper<TIMER_REQUEST_SET_LOCAL_CLOCK_BASED_MINUTE_CHIME, ClockBasedChimeParameters> Minute;
typedef RequestHelper<TIMER_REQUEST_SET_LOCAL_CLOCK_BASED_HOUR_CHIME, ClockBasedChimeParameters> Hour;
typedef RequestHelper<TIMER_REQUEST_SET_LOCAL_CLOCK_BASED_DAY_CHIME, ClockBasedChimeParameters> Day;
};
/**
* @brief Available clock-based chimes, triggered by UTC system clock.
*/
class UtcClockChime
{
public:
typedef RequestHelper<TIMER_REQUEST_SET_UTC_CLOCK_BASED_SECOND_CHIME, ClockBasedChimeParameters> Second;
typedef RequestHelper<TIMER_REQUEST_SET_UTC_CLOCK_BASED_MINUTE_CHIME, ClockBasedChimeParameters> Minute;
typedef RequestHelper<TIMER_REQUEST_SET_UTC_CLOCK_BASED_HOUR_CHIME, ClockBasedChimeParameters> Hour;
typedef RequestHelper<TIMER_REQUEST_SET_UTC_CLOCK_BASED_DAY_CHIME, ClockBasedChimeParameters> Day;
};
/**
* @brief Get current date (utc).
*
* @param date reference to a Date object to set.
*/
ACTIV_FRAMEWORK_API static void GetCurrentUtcDate(const Component &, Date &date);
/**
* @brief Get current time (utc).
*
* @param time reference to a Time object to set.
* @param shouldSetMilliseconds whether to set the milliseconds component of @a time.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static void GetCurrentUtcTime(const Component &, Time &time, const bool shouldSetMilliseconds = false);
/**
* @brief Get current date & time (utc).
*
* @param dateTime reference to a DateTime object to set.
* @param shouldSetMilliseconds whether to set the milliseconds component of @a dateTime.
*/
ACTIV_FRAMEWORK_API static void GetCurrentUtcDateTime(const Component &, DateTime &dateTime, const bool shouldSetMilliseconds = false);
/**
* @brief Get current date (local).
*
* @param date reference to a Date object to set.
*/
ACTIV_FRAMEWORK_API static void GetCurrentLocalDate(const Component &, Date &date);
/**
* @brief Get current time (local).
*
* @param time reference to a Time object to set.
* @param shouldSetMilliseconds whether to set the milliseconds component of @a time.
*/
ACTIV_FRAMEWORK_API static void GetCurrentLocalTime(const Component &, Time &time, const bool shouldSetMilliseconds = false);
/**
* @brief Get current date & time (local).
*
* @param dateTime reference to a DateTime object to set.
* @param shouldSetMilliseconds whether to set the milliseconds component of @a dateTime.
*/
ACTIV_FRAMEWORK_API static void GetCurrentLocalDateTime(const Component &, DateTime &dateTime, const bool shouldSetMilliseconds = false);
/**
* @brief Adjust the system time.
*
* May adjust the system time immediately, or gradually, depending on the underlying platform.
* The TimerService may need to be running in a process with root privileges, depending on the platform.
*
* @param component
* @param milliseconds milliseconds to adjust by.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API static StatusCode AdjustSystemTime(const Component &component, const int32_t milliseconds);
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T1>
TimerServiceApi::CountdownParameters::CountdownParameters(const T1 &t1,
typename Boost::disable_if<Boost::is_integral<T1> >::type *dummy) :
m_countdownDuration(T1::MILLISECONDS_PER_UNIT * t1.m_value)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T1, typename T2>
TimerServiceApi::CountdownParameters::CountdownParameters(const T1 &t1, const T2 &t2) :
m_countdownDuration((T1::MILLISECONDS_PER_UNIT * t1.m_value) +
(T2::MILLISECONDS_PER_UNIT * t2.m_value))
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T1, typename T2, typename T3>
TimerServiceApi::CountdownParameters::CountdownParameters(const T1 &t1, const T2 &t2, const T3 &t3) :
m_countdownDuration((T1::MILLISECONDS_PER_UNIT * t1.m_value) +
(T2::MILLISECONDS_PER_UNIT * t2.m_value) +
(T3::MILLISECONDS_PER_UNIT * t3.m_value))
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T1, typename T2, typename T3, typename T4>
TimerServiceApi::CountdownParameters::CountdownParameters(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4) :
m_countdownDuration((T1::MILLISECONDS_PER_UNIT * t1.m_value) +
(T2::MILLISECONDS_PER_UNIT * t2.m_value) +
(T3::MILLISECONDS_PER_UNIT * t3.m_value) +
(T4::MILLISECONDS_PER_UNIT * t4.m_value))
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T1, typename T2, typename T3, typename T4, typename T5>
TimerServiceApi::CountdownParameters::CountdownParameters(const T1 &t1, const T2 &t2, const T3 &t3, const T4 &t4, const T5 &t5) :
m_countdownDuration((T1::MILLISECONDS_PER_UNIT * t1.m_value) +
(T2::MILLISECONDS_PER_UNIT * t2.m_value) +
(T3::MILLISECONDS_PER_UNIT * t3.m_value) +
(T4::MILLISECONDS_PER_UNIT * t4.m_value) +
(T5::MILLISECONDS_PER_UNIT * t5.m_value))
{
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_TIMER_SERVICE_API_H)
@@ -1,151 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/TraceBuffer.h
*
* @brief Header for the TraceBuffer class.
*/
#if (!defined ACTIV_FRAMEWORK_TRACE_BUFFER_H)
#define ACTIV_FRAMEWORK_TRACE_BUFFER_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/IniFileParser.h"
#include "ActivMiddleware/ActivBase/Tracing/ScopedTracePoint.h"
#include "ActivMiddleware/ActivBase/Tracing/TraceBufferBase.h"
#include "ActivMiddleware/CxxYZ/string_view.h"
//! Activ namespace.
namespace Activ
{
class ManagedEndPoint;
//! Buffer to store recent trace history.
class TraceBuffer : public TraceBufferBase
{
public:
//! Settings class.
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);
bool m_isEnabled; ///< Whether trace logging is enabled.
uint32_t m_eventCount; ///< Number of events to count, must be a power of 2.
String m_logFileName; ///< Name of the log file to write to, filled in automatically if empty.
size_t m_numberOfBackups; ///< Number of backups of the log file.
size_t m_minLogInterval; ///< Minimum number of nanoseconds between logging two trace dumps.
uint64_t m_logCountInterval; ///< Interval in nanoseconds to track number of logs produced.
size_t m_maxLogCount; ///< Maximum logs allowed within a log count interval.
size_t m_logBatchSize; ///< Number of entries to log per iteration.
size_t m_clearBatchSize; ///< Number of entries to clear per iteration.
size_t m_logBufferSendThreshold; ///< Size of log buffer to trigger sending.
size_t m_initialSuppressionPeriod; ///< Number of nanoseconds to suppress tracing after initialization.
};
/**
* @brief Construct the trace buffer.
*
* @param managedEndPoint
* @param settings
*/
TraceBuffer(ManagedEndPoint &managedEndPoint, const Settings &settings);
//! Destructor.
virtual ~TraceBuffer() ACTIV_OVERRIDE;
/**
* @brief Add a dynamic trace point.
*
* This method is here rather than the base class to solve a circular dependency between ScopedTracePoint and TraceBufferBase.
*
* @tparam T the event type.
*
* @return a ScopedTracePoint object.
*/
template <typename T>
ScopedTracePoint Add();
/**
* @brief Add a dynamic trace point.
*
* This method is here rather than the base class to solve a circular dependency between ScopedTracePoint and TraceBufferBase.
*
* @param staticData argument to be passed to T::Decode().
*
* @tparam T the event type.
*
* @return a ScopedTracePoint object.
*/
template <typename T, typename StaticData>
ScopedTracePoint Add(const StaticData &staticData);
/**
* @brief Should a log be generated?
*
* Use this method to check if a log should be generated to save building a string. The Log() method will check anyway.
*
* @param currentTimestamp
*
* @return whether Log() will actually log.
*/
ACTIV_FRAMEWORK_API bool ShouldLog(const uint64_t currentTimestamp);
/**
* @brief Log trace from specificed timestamp.
*
* @param currentTimestamp the current timestamp.
* @param fromTimestamp timestamp to log from.
* @param message the reason for generating the log.
*/
ACTIV_FRAMEWORK_API void Log(const uint64_t currentTimestamp, const uint64_t fromTimestamp, const CxxYZ::string_view &message);
private:
//! Initialize, called after ManagedEndPoint constructor.
void Initialize();
//! Destroy the buffer internals before the ManagedEndPoint destructor.
ACTIV_FRAMEWORK_API void Destroy();
class Impl;
CxxYZ::unique_ptr<Impl> m_pImpl;
friend class AgentApplication;
friend class ManagedEndPoint;
friend class ManagedEndPointImpl;
friend class ThinApplication;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T>
ScopedTracePoint TraceBuffer::Add()
{
CxxYZ::unique_ptr<ITracePoint> pTracePoint(new TracePointT<T, EmptyStaticData>(EmptyStaticData()));
return ScopedTracePoint(*this, this->TraceBufferBase::Add(pTracePoint));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template <typename T, typename StaticData>
ScopedTracePoint TraceBuffer::Add(const StaticData &staticData)
{
CxxYZ::unique_ptr<ITracePoint> pTracePoint(new TracePointT<T, StaticData>(staticData));
return ScopedTracePoint(*this, this->TraceBufferBase::Add(pTracePoint));
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_TRACE_BUFFER_H)
@@ -1,235 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/UdpComponent.h
*
* @brief Header file for udp component class.
*/
#if (!defined ACTIV_FRAMEWORK_UDP_COMPONENT_H)
#define ACTIV_FRAMEWORK_UDP_COMPONENT_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/Component.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Udp ingest component
*/
class UdpComponent : public Component
{
public:
/**
* @brief Constructor.
*
* Attaches this object to a managed endpoint at the next available slot.
*
* @param managedEndPoint reference to a ManagedEndPoint object to which this component is to be attached.
* @param name name of the component, local to the endpoint.
* @param pHeap heap to use for messaging, or 0 for the system heap.
* @param componentId the component id.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API UdpComponent(ManagedEndPoint &managedEndPoint, const String &name = Component::anonymousName,
IHeap * const pHeap = 0, const String &componentId = defaultComponentId);
/**
* @brief Destructor.
*/
ACTIV_FRAMEWORK_API ~UdpComponent();
/**
* @brief Create a socket and bind it to a local address.
*
* @param localAddress local address to bind to.
* @param localPort local port to bind to.
* @param maxRxSize maximum size of a datagram that can be received.
* @param socketAddress reference to an Address object to receive the address of the socket.
* @param pHeap the heap to use for received messages. Default is this component's heap.
*
* @retval STATUS_CODE_SUCCESS.
* @retval STATUS_CODE_TIMEOUT.
* @retval STATUS_CODE_FAILURE ...
*/
ACTIV_FRAMEWORK_API StatusCode CreateSocket(const String &localAddress, const uint16_t localPort, const uint16_t maxRxSize,
Address &socketAddress, IHeap * const pHeap = 0) const;
/**
* @brief Initiate a read on a socket.
*
* @param socketAddress address of the socket to connect.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode Read(const Address &socketAddress) const;
/**
* @brief Connect a socket to a remote address (filter all traffic from other addresses).
*
* @param socketAddress address of the socket to connect.
* @param remoteAddressString the remote address to connect to in string form.
* @param remotePort the remote port to connect to (local endian).
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode Connect(const Address &socketAddress, const String &remoteAddressString,
const uint16_t remotePort) const;
/**
* @brief Disconnect a socket from a remote address (allow all traffic).
*
* @param socketAddress address of the socket to disconnect.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode Disconnect(const Address &socketAddress) const;
/**
* @brief Close a socket.
*
* @param socketAddress address of the socket to shutdown.
* @param gracefully true to only close the socket once any outstanding tx has completed,
* false to force the socket closed immediately.
*
* @retval STATUS_CODE_SUCCESS the socket is fully closed.
* @retval STATUS_CODE_PENDING the socket is closing and OnSocketClose() will be called.
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode Close(const Address &socketAddress, const bool gracefully = false) const;
/**
* @brief Join a multicast group.
*
* @param socketAddress address of the socket to join the multicast group on.
* @param multicastGroupString an ipv4 or ipv6 multicast address string.
* @param interfaceAddressString an ipv4 or ipv6 interface address string.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode JoinMulticastGroup(const Address &socketAddress, const String &multicastGroupString,
const String &interfaceAddressString) const;
/**
* @brief Leave a multicast group.
*
* @param socketAddress address of the socket to leave the multicast group.
* @param multicastGroupString an ipv4 or ipv6 multicast address string.
* @param interfaceAddressString an ipv4 or ipv6 interface address string.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode LeaveMulticastGroup(const Address &socketAddress, const String &multicastGroupString,
const String &interfaceAddressString) const;
/**
* @brief Set multicast interface for transmission.
*
* @param socketAddress address of the socket to set multicast interface on.
* @param interfaceAddressString an ipv4 or ipv6 address string.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetMulticastTxInterface(const Address &socketAddress,
const String &interfaceAddressString) const;
/**
* @brief Set TTL to be used for multicasting.
*
* @param socketAddress address of the socket to set the ttl on.
* @param ttl the TTL.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetMulticastTtl(const Address &socketAddress, const int ttl) const;
/**
* @brief Set TTL to be used for unicasting.
*
* @param socketAddress address of the socket to set unicast ttl on.
* @param ttl the TTL.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetUnicastTtl(const Address &socketAddress, const int ttl) const;
/**
* @brief Set the internal rx buffer size of a socket.
*
* @param socketAddress address of the socket to set receive buffer size.
* @param size the rx buffer size.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetRxBufferSize(const Address &socketAddress, const int size) const;
/**
* @brief Set the internal tx buffer size of a socket.
*
* @param socketAddress address of the socket to set transmit buffer size on.
* @param size the tx buffer size.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetTxBufferSize(const Address &socketAddress, const int size) const;
/**
* @brief Set the receive multicast loopback option of a socket.
*
* @param socketAddress address of the socket to set transmit buffer size on.
* @param enable true to enable receipt of multicast loopback data, else false.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetMulticastLoopback(const Address &socketAddress, const bool enable) const;
/**
* @brief Get the underying socket handle.
*
* @param socketAddress the socket to get the handle of.
* @param socket reference to a SOCKET variable to receive the handle.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode GetSocketHandle(const Address &socketAddress, SOCKET &socket) const;
/**
* @brief Post some data.
*
* @param socketAddress the socket to send the data on.
* @param heapMessage the message to send.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode PostData(const Address &socketAddress, HeapMessage &heapMessage) const;
/**
* @brief Post some data.
*
* @param socketAddress the socket to send the data on.
* @param pData pointer to data to send.
* @param dataLength length of data.
*
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode PostData(const Address &socketAddress, const void *pData, const size_t dataLength) const;
protected:
ACTIV_FRAMEWORK_API virtual StatusCode OnMessage(HeapMessage &message) ACTIV_OVERRIDE;
/**
* @brief Socket has closed due to an error.
*/
ACTIV_FRAMEWORK_API virtual void OnSocketError(const Address &socketAddress);
/**
* @brief Socket has closed due to being shutdown.
*/
ACTIV_FRAMEWORK_API virtual void OnSocketClose(const Address &socketAddress);
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_UDP_COMPONENT_H)
@@ -1,228 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/UdpHelper.h
*
* @brief Header file for the udp helper class.
*/
#if (!defined ACTIV_FRAMEWORK_UDP_HELPER_H)
#define ACTIV_FRAMEWORK_UDP_HELPER_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/FieldTypes/SInt.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include "ActivMiddleware/ActivBase/Ip/NetworkAffinityFilter.h"
#include "ActivMiddleware/ActivBase/Ip/UdpDatagramInfo.h"
#include "ActivMiddleware/ActivFramework/IHeap.h"
//! Activ namespace.
namespace Activ
{
class ManagedEndPoint;
class UdpHelperImpl;
class IpAddress;
// ---------------------------------------------------------------------------------------------------------------------------------
//! Udp helper class
class UdpHelper : private Boost::noncopyable
{
public:
//! Receive callback function type definition.
typedef UdpDatagramCallbackFunction ReceiveCallbackFunction;
//! Settings class.
class Settings
{
public:
/**
* @brief Constructor.
*
* @param pHeap heap to use if heap settings are not defined, or 0 for system heap.
*/
ACTIV_FRAMEWORK_API Settings(IHeap * const pHeap = 0);
/**
* @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);
IHeap * m_pHeap; ///< Default: 0 (system heap).
IHeap::Settings m_heapSettings; ///< Default: empty. Otherwise, create a heap of this size to use.
bool m_shouldStartEnabled; ///< Default: true. Should this helper startup enabled.
bool m_shouldPostReadOnStartup; ///< Default: false. Should this helper post read on startup.
String m_interfaceAddress; ///< The interface address.
String m_remoteAddress; ///< The remote address (source/destination for unicast).
String m_multicastGroup; ///< The multicast group.
uint16_t m_port; ///< Default: 0. The port.
uint16_t m_localUnicastPort; ///< Default: 0. The local port used for the local unicast interface.
// Receive settings.
UInt m_socketRxBufferSize; ///< Default: [NotInitialized]. Leave as system assigned.
uint16_t m_maximumTransmissionUnitSize; ///< Default: 1500. The maximum transmission unit size.
// Posix only receive settings.
UInt m_maxLocalReadBytes; ///< Default: 65536. Posix only. Read this number of bytes max from socket before checking others. 0 for no limit.
uint16_t m_idealTransmissionUnitSize; ///< Default: 1500. Posix only. The expected normal maximum datagram size.
// Transmit settings.
UInt m_socketTxBufferSize; ///< Default: [NotInitialized]. leave as system assigned.
uint32_t m_ttl; ///< Default 8. Ttl for socket.
UInt m_typeOfService; ///< IP_TOS value (Linux only). Supported string values "low-delay", "throughput", "reliable", "min-cost" in ini-file key TypeOfService.
NetworkAffinityFilter::Settings m_networkAffinityFilterSettings;
};
//! Statistics class.
class Statistics
{
public:
//! Default constructor.
ACTIV_FRAMEWORK_API Statistics();
//! Reset.
ACTIV_FRAMEWORK_API void Reset();
size_t m_numberOfTransmittedDatagrams; ///< Number of datagrams successfully written to underlying socket.
uint64_t m_numberOfTransmittedBytes; ///< Number of bytes successfully written to underlying socket.
size_t m_numberOfTransmitFailures; ///< Number of datagrams failed to write to underlying socket.
size_t m_numberOfBlockingTransmits; ///< Number of datagram transmissions that blocked.
size_t m_numberOfReceivedDatagrams; ///< Number of datagrams received from the underlying socket.
uint64_t m_numberOfReceivedBytes; ///< Number of bytes received from the underlying socket.
};
/**
* @brief Constructor.
*
* @param managedEndPoint reference to a ManagedEndPoint object.
* @param name the name of this helper.
* @param settings setting to use for this object.
* @param receiveCallBackFunction receive callback function to send data to, if null then do not configure rx.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API UdpHelper(ManagedEndPoint &managedEndPoint, const String &name, const Settings &settings,
ReceiveCallbackFunction receiveCallBackFunction = 0);
//! Destructor
ACTIV_FRAMEWORK_API ~UdpHelper();
//! Get the settings.
ACTIV_FRAMEWORK_API const Settings &GetSettings() const;
//! Get the settings.
ACTIV_FRAMEWORK_API const Statistics &GetStatistics() const;
//! Get name.
ACTIV_FRAMEWORK_API const String &GetName() const;
//! Is constructed (is the underlying socket valid).
ACTIV_FRAMEWORK_API bool IsConstructed() const;
//! Is enabled.
ACTIV_FRAMEWORK_API bool IsEnabled() const;
//! Reset statistics.
ACTIV_FRAMEWORK_API void ResetStatistics();
/**
* @brief Set enabled state.
*
* @param isEnabled
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode SetEnabledState(const bool isEnabled);
//! Is read posted.
ACTIV_FRAMEWORK_API bool IsReadPosted() const;
/**
* @brief Initiate read.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode InitiateRead();
/**
* @brief Join multicast group.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode JoinMulticastGroup();
/**
* @brief Leave multicast group.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode LeaveMulticastGroup();
/**
* @brief Post data.
*
* @param messageBuilder message builder containing the data to send.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode PostData(const MessageBuilder &messageBuilder) const;
/**
* @brief Post data.
*
* @param pData pointer to data to send.
* @param dataLength length of data.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode PostData(const void * const pData, const size_t dataLength) const;
/**
* @brief Post data.
*
* @param messageBuilder message builder containing the data to send.
* @param destinationIpAddress ip address to send the data to.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode PostData(const MessageBuilder &messageBuilder, const IpAddress &destinationIpAddress) const;
/**
* @brief Post data.
*
* @param pData pointer to data to send.
* @param dataLength length of data.
* @param destinationIpAddress ip address to send the data to.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode PostData(const void * const pData, const size_t dataLength,
const IpAddress &destinationIpAddress) const;
//! Get local IpAddress.
ACTIV_FRAMEWORK_API const IpAddress &GetLocalIpAddress() const;
private:
Boost::scoped_ptr<UdpHelperImpl> m_pImpl; ///< Udp helper implementation.
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_UDP_HELPER_H)
@@ -1,204 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/UiComponent.h
*
* @brief Header file for the ui component class.
*/
#if (!defined ACTIV_FRAMEWORK_UI_COMPONENT_H)
#define ACTIV_FRAMEWORK_UI_COMPONENT_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/Component.h"
#include "ActivMiddleware/ActivFramework/Application.h"
//! Activ namespace.
namespace Activ
{
class UiUser;
class UiIo;
class UiComponentMap;
class UiMainComponent;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Ui component class.
*
* Note a ui component cannot be attached to the ui service endpoint.
*/
class UiComponent : public Component
{
public:
//! Ui component type enumeration.
enum UnderlyingType
{
TYPE_STANDARD, ///< Normal user uis.
TYPE_MAIN, ///< For main menu component.
TYPE_MIDDLEWARE, ///< For core service / middleware provided uis.
TYPE_LITE, ///< Lite ui.
TYPE_TAGGED ///< Distinguished by a string. For grouping, for example, worker thread uis of some service.
};
//! Ui component type.
class Type
{
public:
//! Default constructor to TYPE_STANDARD.
ACTIV_FRAMEWORK_API Type();
/**
* @brief Constructor.
*
* @param type the UnderlyinType for the ui, except TYPE_TAGGED.
*/
ACTIV_FRAMEWORK_API Type(const UnderlyingType type);
/**
* @brief Constructor for TYPE_TAGGED.
*
* @param tag string to associate with the type TYPE_TAGGED.
*/
ACTIV_FRAMEWORK_API explicit Type(const String &tag);
//! Equality operator.
ACTIV_FRAMEWORK_API bool operator==(const Type &rhs) const;
UnderlyingType m_value;
String m_tag;
};
/**
* @brief Constructor.
*
* @param managedEndPoint endpoint to attach to - must be singly threaded.
* @param uiComponentName name of the ui component. This name is used to register the component with the main menu.
* @param type the type to register as.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API UiComponent(ManagedEndPoint &managedEndPoint, const String &uiComponentName,
const Type type = TYPE_STANDARD, const String &uiServiceName = Application::GetUiServiceName());
/**
* @brief Constructor.
*
* @param managedEndPoint endpoint to attach to - must be singly threaded.
* @param uiComponentName name of the ui component. This name is used to register the component with parent UiComponent.
* @param parentUiComponent UiComponent that will allow switching to this ui.
* @param type the type to register as.
* @param uiServiceName name of the ui service.
*
* @throw Exception.
*/
ACTIV_FRAMEWORK_API UiComponent(ManagedEndPoint &managedEndPoint, const String &uiComponentName,
const UiComponent &parentUiComponent, const Type type, const String &uiServiceName = Application::GetUiServiceName());
//! Destructor.
ACTIV_FRAMEWORK_API ~UiComponent();
/**
* @brief Run the component.
*
* An override of this function must construct a menu using uiUser, and call Run() on the menu object.
*
* @param uiUser the user wishing to communicate with this component.
*/
virtual void Run(UiUser &uiUser) = 0;
//! Get the name of the ui service this component is attached to.
ACTIV_FRAMEWORK_API const String &GetUiServiceName() const;
//! Get the name of this ui component.
ACTIV_FRAMEWORK_API const String &GetName() const;
// Component overrides.
ACTIV_FRAMEWORK_API virtual void Enable() ACTIV_OVERRIDE;
ACTIV_FRAMEWORK_API virtual void Disable() ACTIV_OVERRIDE;
//! Convert component type to string.
ACTIV_FRAMEWORK_API static const String UiComponentTypeToString(const Type type);
/**
* @brief Display registered UiComponents.
*
* @param uiIo
* @param type optional type to filter the display by.
*/
ACTIV_FRAMEWORK_API void UiDisplayComponentMenu(const UiIo &uiIo, const Boost::optional<Type> &type);
/**
* @brief Switch to a registered UiComponent.
*
* @param uiIo
* @param uiComponentAddress
*
* @return True if @a uiComponentAddress was a valid UiComponent and a message was sent to the UiService to switch this
* user to it.
*/
ACTIV_FRAMEWORK_API bool UiSwitchToUiComponent(const UiIo &uiIo, const Address &uiComponentAddress);
protected:
ACTIV_FRAMEWORK_API StatusCode OnMessage(HeapMessage &heapMessage) ACTIV_OVERRIDE;
/**
* @brief Is the type of a ui component that is attemting to register with us one we'll accept?
*
* The default implementation allows:
* TYPE_STANDARD
* TYPE_MIDDLEWARE
* TYPE_TAGGED
* Override to allow other types.
*
* @param type
*
* @return Boolean.
*/
ACTIV_FRAMEWORK_API virtual bool IsValidRegistrationType(const UnderlyingType type) const;
const Type m_type; ///< Ui component type.
const Address m_uiServiceAddress;
private:
/**
* @brief Register the ui component with the main menu.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode Register() const;
/**
* @brief Deregister the ui component.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode Deregister() const;
// Component overrides.
ACTIV_FRAMEWORK_API virtual StatusCode OnRequest(HeapMessage &request) ACTIV_OVERRIDE;
/**
* @brief Process a new user request.
*
* @param request the request HeapMessage.
*/
void ProcessNewUserRequest(HeapMessage &request);
const String m_uiServiceName; ///< Name of ui service.
const String m_name; ///< Name of the component as provided to constructor.
const String m_hierarchicalName; ///< Name decorated by any parent UiComponent names.
const Address m_parentUiComponentAddress;
const Address m_registrationAddress;
Boost::scoped_ptr<UiComponentMap> m_pUiComponentMap;
friend class UiComponentMap;
friend class UiMainComponent;
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_UI_COMPONENT_H)
@@ -1,293 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/UiContainerHelpers.h
*
* @brief U/i container helpers functions.
*/
#if (!defined ACTIV_FRAMEWORK_UI_CONTAINER_HELPERS_H)
#define ACTIV_FRAMEWORK_UI_CONTAINER_HELPERS_H
#include "ActivMiddleware/ActivFramework/UiIo.h"
#include ACTIV_BOOST_INCLUDE(type_traits/remove_const.hpp)
//! Activ namespace.
namespace Activ
{
//! UiContainerHelpers namespace.
namespace UiContainerHelpers
{
//! Functor to get the key from a map iterator.
template <typename MAP>
class GetMapKey
{
public:
typedef typename MAP::key_type key_type;
typedef typename MAP::const_iterator const_iterator;
const key_type &operator()(const const_iterator &iterator) const
{
return iterator->first;
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Functor to get the key from a set iterator.
template <typename SET>
class GetSetKey
{
public:
typedef typename SET::key_type key_type;
typedef typename SET::const_iterator const_iterator;
const key_type &operator()(const const_iterator &iterator) const
{
return *iterator;
}
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Functor to get the key from a multi index iterator.
template <typename INDEX>
class GetMultiIndexKey
{
public:
typedef typename INDEX::key_type key_type;
typedef typename INDEX::const_iterator const_iterator;
inline GetMultiIndexKey(const INDEX &index) :
m_keyExtractor(index.key_extractor())
{
};
const key_type &operator()(const const_iterator &iterator) const
{
return m_keyExtractor(*iterator);
}
private:
typename INDEX::key_from_value m_keyExtractor;
};
} // namespace UiContainerHelpers
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Display an ordered container one page at a time, starting from startKey. The container can be modified between pages.
*
* @tparam CONTAINER the container type.
* @tparam F functor to convert the container entries to strings, with signature String F(const CONTAINER::value_type &)
* @tparam GET_KEY functor to get the key from an iterator.
*
* @param container
* @param uiIo
* @param function function to display the container entry.
* @param header
* @param startKey key to start displaying the container from.
* @param getKey function to get the key from an iterator.
*/
template <typename CONTAINER, typename F, typename GET_KEY>
inline void UiDisplayContainer(const CONTAINER &container, const UiIo &uiIo, const F &function, const String &header,
const typename CONTAINER::key_type &startKey, const GET_KEY &getKey)
{
typedef typename CONTAINER::key_type Key;
typedef typename Boost::remove_const<Key>::type NonConstKey;
typedef typename CONTAINER::const_iterator const_iterator;
static const size_t DEFAULT_NUMBER_OF_LINES = 22;
ConsoleWindow::Coord windowSize;
uiIo.GetWindowSize(windowSize);
const size_t linesToDisplay = ((windowSize.m_y > 2) ? windowSize.m_y - 2 : DEFAULT_NUMBER_OF_LINES);
if (container.empty())
{
uiIo.PutString(header + "\n");
return;
}
bool isFirst = true;
NonConstKey key = startKey;
const_iterator iterator = container.lower_bound(key);
do
{
uiIo.PutString(header + "\n");
if (!isFirst)
{
iterator = container.lower_bound(key);
if (container.end() != iterator)
++iterator;
}
isFirst = false;
for (size_t i = 0; (i < linesToDisplay) && (container.end() != iterator); ++iterator)
{
const String &line = function(*iterator);
if (!line.empty())
{
++i;
uiIo.PutString(function(*iterator) + "\n");
}
key = getKey(iterator);
}
}
while ((container.end() != iterator) && (STATUS_CODE_SUCCESS == uiIo.GetConfirmation("Continue", true)));
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Display a map one page at a time. The map can be modified between pages.
*
* @tparam MAP the map type.
* @tparam F functor to convert the map entries to strings, with signature String F(const MAP::value_type &)
*
* @param map
* @param uiIo
* @param function function to display the map entry.
* @param header optional header.
*/
template <typename MAP, typename F>
inline void UiDisplayMap(const MAP &map, const UiIo &uiIo, const F &function, const String &header = String())
{
if (map.empty())
{
if (!header.empty())
uiIo.PutString(header + "\n");
return;
}
UiDisplayMap(map, uiIo, function, header, map.begin()->first);
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Display a map one page at a time, starting from startKey. The map can be modified between pages.
*
* @tparam MAP the map type.
* @tparam F functor to convert the map entries to strings, with signature String F(const MAP::value_type &)
*
* @param map
* @param uiIo
* @param function function to display the map entry.
* @param header optional header.
* @param startKey the start key.
*/
template <typename MAP, typename F>
inline void UiDisplayMap(const MAP &map, const UiIo &uiIo, const F &function, const String &header,
const typename MAP::key_type &startKey)
{
UiDisplayContainer(map, uiIo, function, header, startKey, UiContainerHelpers::GetMapKey<MAP>());
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Display a set one page at a time. The set can be modified between pages.
*
* @tparam SET the set type.
* @tparam F functor to convert the set entries to strings, with signature String F(const SET::value_type &)
*
* @param set
* @param uiIo
* @param function function to display the set entry.
* @param header optional header.
*/
template <typename SET, typename F>
inline void UiDisplaySet(const SET &set, const UiIo &uiIo, const F &function, const String &header = String())
{
if (set.empty())
{
if (!header.empty())
uiIo.PutString(header + "\n");
return;
}
UiDisplaySet(set, uiIo, function, header, *(set.begin()));
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Display a set one page at a time, starting from startKey. The set can be modified between pages.
*
* @tparam SET the set type.
* @tparam F functor to convert the set entries to strings, with signature String F(const SET::value_type &)
*
* @param set
* @param uiIo
* @param function function to display the set entry.
* @param header optional header.
* @param startKey the start key.
*/
template <typename SET, typename F>
inline void UiDisplaySet(const SET &set, const UiIo &uiIo, const F &function, const String &header,
const typename SET::key_type &startKey)
{
UiDisplayContainer(set, uiIo, function, header, startKey, UiContainerHelpers::GetSetKey<SET>());
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Display a multi index one page at a time. The index can be modified between pages.
*
* @tparam INDEX the index type.
* @tparam F functor to convert the index entries to strings, with signature String F(const INDEX::value_type &)
*
* @param index
* @param uiIo
* @param function function to display the index entry.
* @param header optional header.
*/
template <typename INDEX, typename F>
inline void UiDisplayMultiIndex(const INDEX &index, const UiIo &uiIo, const F &function, const String &header = String())
{
if (index.empty())
{
if (!header.empty())
uiIo.PutString(header + "\n");
return;
}
UiDisplayMultiIndex(index, uiIo, function, header, index.key_extractor()(*index.begin()));
}
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Display a multi index one page at a time, starting from startKey. The index can be modified between pages.
*
* @tparam INDEX the index type.
* @tparam F functor to convert the index entries to strings, with signature String F(const INDEX::value_type &)
*
* @param index
* @param uiIo
* @param function function to display the index entry.
* @param header optional header.
* @param startKey the start key.
*/
template <typename INDEX, typename F>
inline void UiDisplayMultiIndex(const INDEX &index, const UiIo &uiIo, const F &function, const String &header,
const typename INDEX::key_type &startKey)
{
UiDisplayContainer(index, uiIo, function, header, startKey, UiContainerHelpers::GetMultiIndexKey<INDEX>(index));
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_UI_CONTAINER_HELPERS_H)
File diff suppressed because it is too large. Load diff
@@ -1,580 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/UiMenu.h
*
* @brief Header file for the ui menu class.
*/
#if (!defined ACTIV_FRAMEWORK_UI_MENU_H)
#define ACTIV_FRAMEWORK_UI_MENU_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivFramework/UiPermissions.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#include <vector>
//! Activ namespace.
namespace Activ
{
class UiUser;
class UiIo;
//! Section name when creating a menu option.
class UiSectionName : public String
{
public:
//! Default constructor.
UiSectionName();
/**
* @brief Constructor.
*
* @param sectionName
*/
UiSectionName(const String &sectionName);
};
// ---------------------------------------------------------------------------------------------------------------------------------
//! Help text when creating a menu option.
class UiHelpText : public String
{
public:
//! Default constructor.
UiHelpText();
/**
* @brief Constructor.
*
* @param helpText
*/
UiHelpText(const String &helpText);
};
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Ui menu class.
*/
class UiMenu
{
public:
/**
* @brief Option attributes.
*
* Currently supported attributes are:
* * permissioning
* * section heading for grouping options
* * help text displayed if the user enters "help <option number>"
*/
class OptionAttributes
{
public:
/**
* @brief Default constructor.
*
* UiPermissions::READ, no section name or help text.
*/
OptionAttributes();
/**
* @brief Constructor.
*
* @param uiPermissions user permissions for the option.
*/
OptionAttributes(const UiPermissions &uiPermissions);
/**
* @brief Constructor.
*
* @param sectionName start a new section in the menu with this name.
*/
OptionAttributes(const String &sectionName);
/**
* @brief Constructor.
*
* @param uiPermissions user permissions for the option.
* @param sectionName start a new section in the menu with this name.
*/
OptionAttributes(const UiPermissions &uiPermissions, const String &sectionName);
/**
* @brief << operator to create a new OptionAttributes with provided UiPermissions.
*
* @param uiPermissions
*
* @return Copy of *this but with the permissions set to @a uiPermissions.
*/
const OptionAttributes operator<<(const UiPermissions &uiPermissions) const;
/**
* @brief << operator to create a new OptionAttributes with provided UiSectionName.
*
* @param uiSectionName
*
* @return Copy of *this but with the section name set to @a uiSectionName.
*/
const OptionAttributes operator<<(const UiSectionName &uiSectionName) const;
/**
* @brief << operator to create a new OptionAttributes with provided UiHelpText.
*
* @param uiHelpText
*
* @return Copy of *this but with the help text set to @a uiHelpText.
*/
const OptionAttributes operator<<(const UiHelpText &uiHelpText) const;
const UiPermissions m_uiPermissions; ///< The ui permissions required to use this option.
const String m_sectionName;
const String m_helpText;
private:
//! Constructor for all members.
OptionAttributes(const UiPermissions &uiPermissions, const String &sectionName, const String &helpText);
};
/**
* @brief Constructor.
*
* Use this constructor for a top level menu.
*
* @param name name of the menu.
* @param uiUser user using this menu.
* @param showQuitOption show a quit option to move back to a parent menu.
*/
ACTIV_FRAMEWORK_API UiMenu(const String &name, UiUser &uiUser, const bool showQuitOption = true);
/**
* @brief Constructor.
*
* Use this constructor for a sub-menu. Note a sub-menu always has a quit option.
*
* @param name name of the sub-menu.
* @param uiIo as passed to the menu option that is creating the sub-menu.
*/
ACTIV_FRAMEWORK_API UiMenu(const String &name, const UiIo &uiIo);
/**
* @brief Destructor.
*/
ACTIV_FRAMEWORK_API virtual ~UiMenu();
/**
* @brief Get the name of the menu.
*
* @return The name of the menu.
*/
ACTIV_FRAMEWORK_API String GetName() const;
/**
* @brief Set the name of the section for the next option added.
*
* If a section name is provided in the next option added then the section name added with this option will be ignored.
*
* @param sectionName name of the section to apply to the next option added.
*/
ACTIV_FRAMEWORK_API void SetSectionName(const String &sectionName);
/**
* @brief Add a member function menu option.
*
* @param name name of the menu option.
* @param object reference to the object the function is to be run on.
* @param pFunction member function in class T.
* @param optionAttributes optional option attributes.
*/
template<typename T>
void AddOption(const String &name, T &object, void (T::*pFunction)(const UiIo &),
const OptionAttributes &optionAttributes = OptionAttributes())
{
Option *pOption = MakeOptionTemplate(CxxYZ::bind(pFunction, CxxYZ::ref(object), CxxYZ::_1), name, optionAttributes);
if (0 == pOption)
return;
m_optionVector.push_back(pOption);
}
/**
* @brief Add a const member function menu option.
*
* @param name name of the menu option.
* @param object reference to the object the function is to be run on.
* @param pFunction member function in class T.
* @param optionAttributes optional option attributes.
*/
template<typename T>
void AddOption(const String &name, const T &object, void (T::*pFunction)(const UiIo &) const,
const OptionAttributes &optionAttributes = OptionAttributes())
{
Option *pOption = MakeOptionTemplate(CxxYZ::bind(pFunction, CxxYZ::cref(object), CxxYZ::_1), name, optionAttributes);
if (0 == pOption)
return;
m_optionVector.push_back(pOption);
}
/**
* @brief Add a function object menu option.
*
* @param name name of the menu option.
* @param functionObject reference to a unary function object (where the parameter is const UiIo &) of the menu option.
* @param optionAttributes optional option attributes.
*/
template<typename T>
void AddOption(const String &name, const T &functionObject, const OptionAttributes &optionAttributes = OptionAttributes())
{
Option *pOption = MakeOptionTemplate(functionObject, name, optionAttributes);
if (0 == pOption)
return;
m_optionVector.push_back(pOption);
}
/**
* @brief Add a global function menu option.
*
* @param name name of the menu option.
* @param pFunction pointer to a global function to run.
* @param optionAttributes optional option attributes.
*/
void AddOption(const String &name, void (*pFunction)(const UiIo &uiIo),
const OptionAttributes &optionAttributes = OptionAttributes())
{
Option *pOption = MakeOptionTemplate(CxxYZ::bind(pFunction, CxxYZ::_1), name, optionAttributes);
if (0 == pOption)
return;
m_optionVector.push_back(pOption);
}
/**
* @brief Run the menu.
*/
ACTIV_FRAMEWORK_API void Run();
protected:
/**
* @brief Display a menu title.
*
* Default is "<name> options:". Override to change.
*
* @param uiIo to read / write to / from the user.
*/
ACTIV_FRAMEWORK_API virtual void DisplayTitle(const UiIo &uiIo) const;
/**
* @brief Display an option.
*
* Override this to change the format of menu option displays.
*
* @param uiIo to read / write to / from the user.
* @param optionIndex the index of the option.
* @param name the name of the option.
* @param optionAttributes attributes for this option.
*/
ACTIV_FRAMEWORK_API virtual void DisplayOption(const UiIo &uiIo, const size_t optionIndex, const String &name,
const OptionAttributes &optionAttributes) const;
/**
* @brief Display message after options.
*
* @param uiIo to read / write to / from the user.
*/
ACTIV_FRAMEWORK_API virtual void DisplayFooter(const UiIo &uiIo) const;
/**
* @brief Display the prompt that is used when selecting a menu option.
*
* Default is "# ". Override to change.
*
* @param uiIo to read / write to / from the user.
*/
ACTIV_FRAMEWORK_API virtual void DisplayOptionPrompt(const UiIo &uiIo) const;
/**
* @brief Get an option from the user.
*
* @param uiIo to read / write to / from the user.
* @param timeoutPeriod to pass to the UiIo option used to get input.
* @param optionString to receive the option.
*
* @retval STATUS_CODE_SUCCESS optionString populated.
* @retval STATUS_CODE_UNCHANGED enter hit with no input.
* @retval STATUS_CODE_TIMEOUT
* @retval ...
*/
ACTIV_FRAMEWORK_API virtual StatusCode GetOption(const UiIo &uiIo, const TimeoutPeriod timeoutPeriod,
String &optionString) const;
/**
* @brief User has entered an option; run it.
*
* Checks for quit (if the menu was constructed with a quit option),
* then for an unsigned integer in the range 1 ... number of options in menu, running the option if in range.
*
* @param uiIo to read / write to / from the user.
* @param optionString the entered option string.
*
* @retval STATUS_CODE_SUCCESS option has been run.
* @retval ...
*
* @throw UiMenuQuitException to leave the menu.
*/
ACTIV_FRAMEWORK_API virtual StatusCode ProcessOption(const UiIo &uiIo, const String &optionString);
private:
/**
* @brief Option class.
*/
class Option
{
public:
/**
* @brief Constructor.
*
* @param name name of the menu option.
* @param optionAttributes attributes for the menu option.
*/
ACTIV_FRAMEWORK_API Option(const String &name, const OptionAttributes &optionAttributes);
/**
* @brief Destructor.
*/
ACTIV_FRAMEWORK_API virtual ~Option();
/**
* @brief Run the option.
*
* @param uiIo to read / write to / from the user.
*/
virtual void Run(const UiIo &uiIo) const = 0;
String m_name;
OptionAttributes m_attributes;
};
/**
* @brief Template for member function options.
*/
template <typename T>
class OptionTemplate : public Option
{
public:
/**
* @brief Constructor.
*
* @param functionObject function object wrapping the member function to be run.
* @param name name of the menu option.
* @param optionAttributes attributes for the menu option.
*/
OptionTemplate(const T &functionObject, const String &name, const OptionAttributes &optionAttributes) :
Option(name, optionAttributes),
m_functionObject(functionObject)
{
}
private:
virtual void Run(const UiIo &uiIo) const ACTIV_OVERRIDE
{
m_functionObject(uiIo);
}
T m_functionObject; ///< Function object wrapping the ui function to run.
};
/**
* @brief Common construction code.
*/
void CommonCtor();
/**
* @brief Helper to create OptionTemplate from a function object.
*
* @param functionObject the function object.
* @param name name of the menu option.
* @param optionAttributes attributes for the menu option.
*
* @return Pointer to new OptionTemplate.
*/
template<typename T>
OptionTemplate<T> *MakeOptionTemplate(const T &functionObject, const String &name,
const OptionAttributes &optionAttributes)
{
OptionTemplate<T> *pOption = ACTIV_NULLPTR;
if ((!m_nextSectionName.empty()) && optionAttributes.m_sectionName.empty())
{
pOption = new (std::nothrow) OptionTemplate<T>(
functionObject, name, optionAttributes << UiSectionName(m_nextSectionName));
}
else
{
pOption = new (std::nothrow) OptionTemplate<T>(functionObject, name, optionAttributes);
}
m_nextSectionName.clear();
return pOption;
}
/**
* @brief Display the menu.
*
* @param uiIo to read / write to / from the user.
*/
void Display(const UiIo &uiIo) const;
/**
* @brief Display the list of options.
*
* @param uiIo to read / write to / from the user.
*/
void DisplayOptions(const UiIo &uiIo) const;
/**
* @brief Display the list of options that have help.
*
* @param uiIo to read / write to / from the user.
*/
void DisplayAvailableHelpOptions(const UiIo &uiIo) const;
/**
* @brief Run an option.
*
* @param uiIo to read / write to / from the user.
* @param optionIndex the index of the option (0 .. number of options - 1).
*
* @retval STATUS_CODE_SUCCESS option has been run.
* @retval STATUS_CODE_INVALID_INDEX @a optionIndex is null in m_optionVector.
* @retval STATUS_CODE_ACCESS_DENIED user is not permissioned for the option.
* @retval STATUS_CODE_EXIT to leave a menu.
* @retval ... current menu is redisplayed.
*/
StatusCode RunOption(const UiIo &uiIo, const size_t optionIndex);
/**
* @brief Display help for an option, if available.
*
* @param uiIo to read / write to / from the user.
* @param optionIndex the index of the option (0 .. number of options - 1).
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_INDEX @a optionIndex is null in m_optionVector.
*/
StatusCode HelpOption(const UiIo &uiIo, const size_t optionIndex) const;
/**
* @brief Check if the user is sufficiently permissioned to use an option.
*
* @return true if the user meets the permissioning requirements to use the option.
*/
bool IsUserPermissionedForOption(const UiPermissions &optionUiPermissions) const;
typedef std::vector<Option *> OptionVector; ///< Option vector type.
const String m_name; ///< The name of the menu.
UiUser & m_uiUser; ///< The user of this menu.
UiMenu * const m_pParentMenu; ///< Parent menu, or 0.
const bool m_showQuitOption; ///< Show quit menu option.
OptionVector m_optionVector; ///< Vector of menu options.
String m_nextSectionName; ///< Name of the section to apply to the next option added.
friend class UiIo;
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiSectionName::UiSectionName()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiSectionName::UiSectionName(const String &sectionName) :
String(sectionName)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiHelpText::UiHelpText()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiHelpText::UiHelpText(const String &helpText) :
String(helpText)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiMenu::OptionAttributes::OptionAttributes() :
m_uiPermissions(UiPermissions::READ)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiMenu::OptionAttributes::OptionAttributes(const UiPermissions &uiPermissions) :
m_uiPermissions(uiPermissions)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiMenu::OptionAttributes::OptionAttributes(const String &sectionName) :
m_uiPermissions(UiPermissions::READ),
m_sectionName(sectionName)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiMenu::OptionAttributes::OptionAttributes(const UiPermissions &uiPermissions, const String &sectionName) :
m_uiPermissions(uiPermissions),
m_sectionName(sectionName)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const UiMenu::OptionAttributes UiMenu::OptionAttributes::operator<<(const UiPermissions &uiPermissions) const
{
return OptionAttributes(uiPermissions, m_sectionName, m_helpText);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const UiMenu::OptionAttributes UiMenu::OptionAttributes::operator<<(const UiSectionName &uiSectionName) const
{
return OptionAttributes(m_uiPermissions, uiSectionName, m_helpText);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const UiMenu::OptionAttributes UiMenu::OptionAttributes::operator<<(const UiHelpText &uiHelpText) const
{
return OptionAttributes(m_uiPermissions, m_sectionName, uiHelpText);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiMenu::OptionAttributes::OptionAttributes(const UiPermissions &uiPermissions, const String &sectionName,
const String &helpText) :
m_uiPermissions(uiPermissions),
m_sectionName(sectionName),
m_helpText(helpText)
{
}
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_UI_MENU_H)
@@ -1,111 +0,0 @@
/**
* @file include/ActivMiddleware/ActivFramework/UiPermissions.h
*
* @brief Header file for the ui permissions class.
*/
#if (!defined ACTIV_FRAMEWORK_UI_PERMISSIONS_H)
#define ACTIV_FRAMEWORK_UI_PERMISSIONS_H
#include "ActivMiddleware/ActivFramework/External.h"
//! Activ namespace.
namespace Activ
{
class MessageBuilder;
class MessageValidator;
/**
* @brief Ui permissions class.
*/
class UiPermissions
{
public:
/**
* @brief Ui permissions list.
*/
#define ACTIV_UI_PERMISSIONS_LIST(d) \
d(READ, READ_BIT) \
d(MODIFY, (READ_BIT | MODIFY_BIT)) \
d(SHUTDOWN, (READ_BIT | SHUTDOWN_BIT)) \
d(FULL, ((0x01 << NUMBER_OF_PERMISSIONS_BITS) - 1))
#define ACTIV_DECLARE_UI_PERMISSIONS(name, bitmap) ACTIV_FRAMEWORK_API static const UiPermissions name;
ACTIV_UI_PERMISSIONS_LIST(ACTIV_DECLARE_UI_PERMISSIONS)
#undef ACTIV_DECLARE_UI_PERMISSIONS
/**
* @brief Default constructor.
*/
ACTIV_FRAMEWORK_API UiPermissions();
/**
* @brief Convert the permissions value from a string.
*
* @param string the string to convert from.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
*/
ACTIV_FRAMEWORK_API StatusCode FromString(const String &string);
/**
* @brief Get a pretty-printed string of the FromString() format.
*
* @return String.
*/
ACTIV_FRAMEWORK_API static const String GetFromStringFormat();
/**
* @brief Convert the permissions value to a string.
*
* @return The converted string representation.
*/
ACTIV_FRAMEWORK_API String ToString() const;
/**
* @brief Serialize.
*
* @param messageBuilder message builder.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode Serialize(MessageBuilder &messageBuilder) const;
/**
* @brief Deserialize.
*
* @param messageValidator message validator.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode Deserialize(MessageValidator &messageValidator);
/**
* @brief Check the permissions meets another permissions value.
*
* @param uiPermissions to compare with.
*
* @return true if this permissions meets the other permissions value.
*/
ACTIV_FRAMEWORK_API bool HasPermissions(const UiPermissions &uiPermissions) const;
typedef int32_t Bitmap;
private:
/**
* @brief Constructor.
*
* @param bitmap bitmap of permissions.
*/
UiPermissions(const Bitmap bitmap);
Bitmap m_bitmap;
};
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_UI_PERMISSIONS_H)