AbstractService

class kanzi::connect::AbstractService : public MetaObject, public enable_shared_from_this<AbstractService>, public PropertyObject

Abstract base class for Kanzi Connect services.

Subclassed by ExternalServiceAdapter

Public Types

typedef map<string, EnumValues> EnumMap
typedef map<string, int> EnumValues
enum InvokableOperationResult

Values:

enumerator Success
enumerator AlreadyExists
enumerator ValidationFailed
enumerator NotFound
typedef function<void(AbstractService*)> RuntimeDataSchemaChangeCallback

Callback prototype to be invoked when runtime data schema changes.

typedef shared_ptr<void> RuntimeDataSchemaChangeSubscriptionToken

Handle given as return value to runtime data schema change callback registration.

enum ServiceControlResult

Values:

enumerator ServiceControlSuccess
enumerator ServiceControlFailed
enumerator ServiceControlNotSupported
typedef enum kanzi::connect::AbstractService::ServiceControlResult ServiceControlResult
enum ServiceControlSource

Values:

enumerator ServiceControlSourceManual
enumerator ServiceControlSourceLogic
typedef enum kanzi::connect::AbstractService::ServiceControlSource ServiceControlSource
typedef vector<AbstractSessionSharedPtr> SessionContainer

Container type for all connected sessions.

typedef function<void(AbstractService*)> StateCallbackFunction

Function prototype to be invoked when state changes.

typedef shared_ptr<void> StateChangedSubscriptionToken

Handle given as return value to state callback registration.

Public Functions

AbstractService()

Constructor.

virtual ~AbstractService()

Destructor.

AbstractSessionSharedPtr acquireSession(int clientId, int sessionId, MessageDispatcher *dispatcher, const string &instanceName)

Session factorization method.

Return

newly allocated session. ownership not transfered.

Parameters
  • clientId: client identifier number

  • sessionId: session identifier number

  • dispatcher: message dispatching functionality for the session.

  • instanceName: name for the service/session instance

virtual InvokableOperationResult addCustomType(const string &xml)

Add a custom type to the service.

Return

InvokableOperationResult defining the success

Parameters
  • xml: Contains the xml definition for the custom type

virtual InvokableOperationResult addCustomTypeDecoded(const string &decodedXml)

Add a custom type to the service.

Return

InvokableOperationResult defining the success

Parameters
  • decodedXml: Contains the xml definition for the custom type in clear xml without base64 encoding

virtual int addEvent(const string &identifier, const string &description)
virtual int addMethod(const string &identifier, const string &description)
virtual int addProperty(const string &identifier, const string &description)
virtual InvokableOperationResult addRoute(const string &xml)

Add new P2P route(s) for the service.

Return

InvokableOperationResult defining the success

Parameters
  • xml: Contains the xml definition for the route

virtual InvokableOperationResult addRouteDecoded(const string &decodedXml)

Add new P2P route(s) for the service.

Return

InvokableOperationResult defining the success

Parameters
  • decodedXml: Contains the xml definition for the route

RuntimeDataSchemaChangeSubscriptionToken addRuntimeDataSchemaChangeSubscription(RuntimeDataSchemaChangeCallback function)

Adds a callback to invoke when runtime data schema changes.

Return

token that can be used to remove subscription

Note

It is not allowed to destroy the service from the registered callback.

Parameters
  • function: function to be called on schema change.

StateChangedSubscriptionToken addStateChangeSubscription(StateCallbackFunction function)

Adds a state change callback subscription.

Return

token that can be used to remove subscription

Note

It is not allowed to destroy the service from the registered callback.

Parameters
  • function: function to be called on state change

bool addSubscription(const string &identifier, AbstractSessionSharedPtr session)

Add subscription to the given session for this service.

Return

True if subscription was added successfully, double subscription is not accepted

Parameters
  • identifier: Identifies the subscription, what this means is implementation specific

  • session: The session to subscribe

virtual void cancelTimer(int64_t timerId)

Cancels ongoing timer.

Parameters
  • timerId: identifier returned by the setTimer function.

size_t countSessions()

Return the amount of sessions towards this service amount of sessions.

int countSessions() const

Amount of allocated sessions.

Return

amount of sessions

virtual InvokableOperationResult createRuntimedata(const string &parentIdentifier, const string &xml)

Create a new runtime data element for the service runtime data.

Return

Is the operation successful or not

Parameters
  • parentIdentifier: Specifies the parent under which create the element in the hierarchy

  • xml: Contains the xml defining the element contents

EnumMap::const_iterator enumerationValuesBegin()
EnumMap::const_iterator enumerationValuesEnd()
vector<AbstractSessionSharedPtr> findSubscribers(const string &identifier)

Find all subscribers for the given identifier.

Return

vector listing all subscribers

Parameters
  • identifier: Identifies the subscriptions, what this means is implementation specific

const SessionContainer &getAllSessions() const

Returns all currently active sessions.

Return

All sessions that are currently active.

SessionContainer getAllSessionsOfClient(int clientId)

Returns all sessions for a given client.

Return

All sessions that were acquired for given client.

Parameters
  • clientId: Id of the client.

KanziStringVectorSharedPtr getAttributes()

Lists all service attributes.

Return

flat list of service attributes, key and value follow in subsequent entries.

RuntimeDataObjectSharedPtr getConfigurationProperties()

Retrieves configuration properties as a runtime data object to allow more convenient access to data.

Return

shared pointer to runtime data containing configuration properties.

ContentClientSharedPtr getContentClient() const

Access to content system.

Return

Content client instance.

virtual ContentProviderCollectionSharedPtr getContentProvider()

Returns content provider for this service.

Return

Collection of content providers, created by this service.

const vector<unique_ptr<CustomType>> &getCustomTypes() const

Get the custom types defined for this service.

Return

Vector containing the custom types

KanziStringVectorSharedPtr getDisabledInvokables()
ConnectDomain *getDomain() const

Retrieves the connect domain.

Return

the domain.

optional<int> getEnumValue(const string &name, const string &enumerator)

Find out value for enumeration string.

Return

value if found.

Parameters
  • name: Name of the enum definition. Can be empty, first matching enumerator value is returned from all enums

  • enumerator: Enumerator string, identifies the value

ServiceExtensionContainer *getExtensions()
string getFullyQualifiedConfigurationPropertyName(const string &name)

Constructs a fully qualified configuration property name, usually the fully qualified name is something like “Connect.Service.MyService.ConfigurationProperties.MyPropertyName”.

Return

fully qualified configuration property name.

Parameters
  • name: the name where the fully qualified name is to be composed

virtual GenericInvoker *getGenericInvoker()

Retrieve a generic invoker bound to this service.

Lifetime of the object is the same as the service lifetime. Can be overridden by a class to rewrite functionality.

Return

pointer to generic invoker. ownership not transfered.

virtual string getIdentifier() const = 0
InterfaceDomainBase *getInterfaceDomain() const

Access to interface domain.

Return

Interface domain pointer.

inline virtual RuntimeDataObjectSharedPtr getModifiedConfigurationProperties()

Retrieves modified configuration properties as runtime data object.

Overriden by corresponding Concept class.

Return

shared pointer to configuration properties that were modified since last called.

virtual string getName()

Returns the override name.

Return

the name that was explicitly set for the service.

WorkQueueInterface *getProxyWorkQueue()

Returns a proxied work queue instance that can be used by composited classes to to assign work to this service.

Note

Returned interface will become invalid immediately when uninitialize() gets called for this Service.

Return

pointer to interface that can be used dispatch event(s) to this particular service.

inline AbstractSessionSharedPtr getRunningSession()
virtual string getSchema()

Returns service schema in XML format.

Return

schema as xml.

virtual const ServiceDescription &getServiceDescription() const

Access the static service description info.

Return

reference to service information.

inline virtual p2p::RoutingRulesSharedPtr getServiceRoutingInformation()

Return service routing information.

Return

XML format string describing the preferred routing instructions.

virtual const ServiceState &getServiceState() const

Gets service state information.

Return

the state.

AbstractSessionSharedPtr getSession(int clientId, int sessionId)

Returns session by client & session id.

Return

Session that was acquired with given parameters, or 0 if there was no such session.

Parameters
  • clientId: Id of the client.

  • sessionId: Id of the session.

int getStopInterval() const

Retrieve service stop interval.

Return

stop interval in seconds.

WorkQueueInterface *getWorkQueue() const

Access to signal that allows to invoke work().

Return

The signal.

bool hasEnumValues(const string &name)

Checks if enum has been defined on this service.

Return

True if values have been registered for the name.

Parameters
  • name: Name of the enum definition.

bool hasSubscriptions(const string &identifier)

Check if the given identifier has any subscriptions.

Return

True if at least one subscriber is found

Parameters
  • identifier: The identifier to check, what this means is implementation specific

virtual void initialize(InterfaceDomainBase *domain, ContentClientSharedPtr contentClient, WorkQueueInterface *workQueue)

Initialize this service.

Parameters
  • domain: Interface domain.

  • contentClient: Content Client that can be used to expose runtime state of this service to clients.

  • workQueue: Interface to system work queue used to dispatch work to services.

bool manualPersistenceOverride() const

Defines whether manual persistence override is active, i.e.

user has manually configured service to a state and thus automatic shutdown is not active.

Return

true if current state is set manually.

virtual AbstractSessionSharedPtr onAcquireSession(int clientId, int sessionId, MessageDispatcher *dispatcher, const string &instanceName) = 0

Session factorization method interface.

To be overrided by concrete services

Return

newly allocated session. ownership is transfered.

Parameters
  • clientId: client identifier number

  • sessionId: session identifier number

  • dispatcher: message dispatching functionality for the session.

  • instanceName: name for the service/session instance

virtual void onReleaseSession(AbstractSessionSharedPtr session)

Virtual method that inheriting classes can implement.

Can be used to receive notifications when sessions are destroyed.

Parameters
  • session: identifies the session to be released. ownership not transfered.

void releaseAllSessions()

Unconditionally releases all sessions. use carefully.

void releaseSession(AbstractSessionSharedPtr session)

Releases previously allocated session.

Parameters
  • session: the session to release. ownership not transfered.

virtual InvokableOperationResult removeCustomType(const string &typeName)

Remove a custom type from a service.

Return

InvokableOperationResult defining the success

Parameters
  • typeName: The name of the type

virtual int removeEvent(const string &identifier)
virtual int removeMethod(const string &identifier)
virtual int removeProperty(const string &identifier)
virtual InvokableOperationResult removeRoute(const string &subjectName)

Remove a route from a service.

Return

InvokableOperationResult defining the success

Parameters
  • subjectName: The subject of the route (can be method name, event name or “runtimedata”)

virtual InvokableOperationResult removeRuntimedataElement(const string &elementIdentifier)

Remove runtime data element from the service runtime data.

Return

Is the operation successful or not

Parameters
  • elementIdentifier: Specifies which element to remove

void removeRuntimeDataSchemaChangeSubscription(RuntimeDataSchemaChangeSubscriptionToken token)

Remove schema change subscription.

Parameters
  • token: to remove.

void removeStateChangeSubscription(StateChangedSubscriptionToken token)

Remove state change subscription.

Parameters
  • token: to remove.

vector<string> removeSubscriptions(AbstractSessionSharedPtr session, const string &identifier = "")

Remove subscription to the given session for this service.

Return

Vector containing identifiers that no longer have any subscriptions left after this call

Parameters
  • session: The session whose subscriptions are to be removed

  • identifier: The subscriptions to remove, if empty all subscriptions for the session are removed

AbstractService::ServiceControlResult resetService(ServiceArgumentsSharedPtr arguments)

Tries to reset service.

Returnvalue indicates the status of execution.

Return

status indicating the success of the operation. It is up to the service to decide what “reset” means to it.

Parameters
  • arguments: optional arguments passed along with the control request.

bool runScript(const MessagePackage &message, AbstractSessionSharedPtr session, shared_ptr<GenericRPCReplyMessage> &ret)

Run a script using configured script plugin. Intended for internal use.

ServiceRuntimeData &runtimeData()

Retrieve service runtime data.

Return

reference to services runtime data.

void setAttribute(const string &key, const string &value)

Add service attributes as key value pairs.

These will be visible on service description, but don’t affect runtime state

void setDomain(ConnectDomain *domain)

Set the connect domain.

Parameters
  • domain: the domain

void setFileClient(VirtualFileClient *client)

Set the client instance to access VirtualFileService.

Parameters
  • client: Pointer to the instance which is used to access the service

virtual void setName(const string &name)

Defines a override name used to identify the service.

Parameters
  • name: the name

void setPersistence(AbstractService::ServiceDescription::Persistence persistence)

Sets the service persistence.

Parameters
  • persistence: the persistence type for the service.

inline virtual void setRunningSession(AbstractSessionSharedPtr session)

Stores the currently running session.

Should not be called from 3rd party code - used only internally by the infrastructure.

virtual InvokableOperationResult setRuntimedataValue(const string &elementIdentifier, const string &value)

Set runtime data value for the given element in the service runtime data.

Parameters
  • elementIdentifier: Identifies the element in the service runtime data

  • value: The value to set in serialized format

bool setServiceRuntimeDataSchema(const string &xml)

Set service runtime data schema.

All previously configured runtime data specific settings are discarded. New schema is also delivered to client(s).

Return

true if succeeded. false if problems.

Parameters
  • xml: XML format schema

void setServiceState(AbstractService::ServiceState state)

sets service state information.

Parameters
  • state: the state

void setServiceVersion(AbstractService::ServiceDescription::Version version, AbstractService::ServiceDescription::Version minCompatibleVersion = AbstractService::ServiceDescription::Version())

Configures the service version information.

This should be called in constructor.

Parameters
  • version: the main version of the service

  • minCompatibleVersion: minimum compatible version.

void setSettingFactory(const persistence::SettingFactory *factory)

Set the setting factory instance to allow using persistence service.

Parameters
  • factory: Pointer to the instance which is used to instantiate setting objects

void setStopInterval(int seconds)

Configures the stop interval.

Parameters
  • seconds: the value to set. Negative values are rounded to 0.

virtual int64_t setTimer(int64_t milliseconds, ConnectWorkItem::Executor callback)

Installs a timer to be called after a specified timeout in milliseconds.

Return

handle that can then be used cancel the timer.

Parameters
  • milliseconds: timeout in milliseconds

  • callback: function to be called when timer expires.

virtual int64_t setTimer(int64_t milliseconds, ConnectWorkItem::Executor callback, ConnectWorkItem::ExecutionContext executionContext)

Installs a timer to be called after a specified timeout in milliseconds.

Return

handle that can then be used cancel the timer.

Parameters
  • milliseconds: timeout in milliseconds

  • callback: function to be called when timer expires.

  • executionContext: Defines in which thread the callback should be executed.

bool simulateEvent(const string &messageName, const MessagePackage &message)

Post a message to all running sessions as event. Intended for internal use.

AbstractService::ServiceControlResult startService(ServiceControlSource serviceControlSource, ServiceArgumentsSharedPtr arguments)

Tries to start the service.

Returnvalue indicates if operation fails

Return

true if service got running. false indicates a failure in that operation.

Parameters
  • serviceControlSource: what caused the service control to be accomplished.

  • arguments: the arguments to use when starting the service. Similar to command line arguments on shell - effectively a list of strings.

AbstractService::ServiceControlResult stopService(ServiceControlSource serviceControlSource)

Tries to stop the service.

Shall the stop fail or otherwise not supported then scenario must be indicated with return value

Return

true if service got stopped or it was stopped already. false if unable to stop the service.

Parameters
  • serviceControlSource: what caused the service control to be accomplished.

virtual void uninitialize()

Uninitialize this service.

Note

Classes that inherit AbstractService class must call this base class implementation if their override this method.

virtual void work(ConnectWorkItemSharedPtr workItem)

Asks service to perform work.

class ServiceDescription

Public Types

enum Persistence

Values:

enumerator StartOnDemand

Service starts and shutdowns automatically when clients connect/disconnect.

enumerator AlwaysRunning

Service is always running regardless whether there are any clients connected.

typedef enum kanzi::connect::AbstractService::ServiceDescription::Persistence Persistence

Public Functions

ServiceDescription(ServiceDescription::Version version = ServiceDescription::Version(), ServiceDescription::Version minVersion = ServiceDescription::Version(), ServiceDescription::Persistence persistence = AlwaysRunning)

C++ constructor.

Parameters
  • version: default version

  • minVersion: minimum acceptable version

bool valid() const

Is the object validly constructed.

Public Members

bool m_manualPersistenceOverride

Whether persistence functionality has been manually overridden.

Version m_minCompatibleVersion

Minimum compatible version.

Persistence m_persistence

Execution type.

Version m_version

The version.

class Version

Encapsulates version information.

Public Types

enum [anonymous]

Values:

enumerator InvalidVersionNumber

Invalid value indicator.

Public Functions

Version(const string versionstr)

constructs object from version string

Parameters
  • versionstr: version in format “1.2”

Version(int major = InvalidVersionNumber, int minor = InvalidVersionNumber)

c++ constructor.

initialize object.

Parameters
  • major: major number

  • minor: minor number

string toString() const

Converts version information to string.

Return

version as string “1.0”

bool valid() const

Is version number valid.

Return

true if version is valid.

Public Members

int m_major

major version number “X.something”

int m_minor

Minor version number “something.Y”.

Friends

inline friend friend bool operator!= (const Version &lhs, const Version &rhs)
inline friend friend bool operator< (const Version &lhs, const Version &rhs)
inline friend friend bool operator<= (const Version &lhs, const Version &rhs)
inline friend friend bool operator== (const Version &lhs, const Version &rhs)
inline friend friend bool operator> (const Version &lhs, const Version &rhs)
inline friend friend bool operator>= (const Version &lhs, const Version &rhs)
class ServiceState

Public Types

enum State

Values:

enumerator Undefined

-> not initialized. hardly ever exposed to outside.

enumerator Initializing

-> under initialization.

enumerator Running

Running.

enumerator Stopped

Stopped.

enumerator Failed

Some error occurred.

enumerator Upgrading

under upgrade.

Public Functions

ServiceState(int State = Undefined, string description = string())

c++ constructor

inline bool initialized() const

Checks whether service has been successfully initialized.

Return

true if service is initialized.

inline bool running() const

Checks whether service is running.

Return

true if service is running.

inline bool stopped() const

Checks whether service is stopped.

Return

true if service is stopped.

Public Members

int m_state

Service state value.

string m_stateDescription

detailed description