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.

Parameters
  • clientId – client identifier number

  • sessionId – session identifier number

  • dispatcher – message dispatching functionality for the session.

  • instanceName – name for the service/session instance

Returns

newly allocated session. ownership not transfered.

virtual InvokableOperationResult addCustomType(const string &xml)

Add a custom type to the service.

Parameters

xml – Contains the xml definition for the custom type

Returns

InvokableOperationResult defining the success

virtual InvokableOperationResult addCustomTypeDecoded(const string &decodedXml)

Add a custom type to the service.

Parameters

decodedXml – Contains the xml definition for the custom type in clear xml without base64 encoding

Returns

InvokableOperationResult defining the success

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.

Parameters

xml – Contains the xml definition for the route

Returns

InvokableOperationResult defining the success

virtual InvokableOperationResult addRouteDecoded(const string &decodedXml)

Add new P2P route(s) for the service.

Parameters

decodedXml – Contains the xml definition for the route

Returns

InvokableOperationResult defining the success

RuntimeDataSchemaChangeSubscriptionToken addRuntimeDataSchemaChangeSubscription(RuntimeDataSchemaChangeCallback function)

Adds a callback to invoke when runtime data schema changes.

Note

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

Parameters

function – function to be called on schema change.

Returns

token that can be used to remove subscription

StateChangedSubscriptionToken addStateChangeSubscription(StateCallbackFunction function)

Adds a state change callback subscription.

Note

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

Parameters

function – function to be called on state change

Returns

token that can be used to remove subscription

bool addSubscription(const string &identifier, AbstractSessionSharedPtr session)

Add subscription to the given session for this service.

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

  • session – The session to subscribe

Returns

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

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.

Returns

amount of sessions

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

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

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

  • xml – Contains the xml defining the element contents

Returns

Is the operation successful or not

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

Find all subscribers for the given identifier.

Parameters

identifier – Identifies the subscriptions, what this means is implementation specific

Returns

vector listing all subscribers

const SessionContainer &getAllSessions() const

Returns all currently active sessions.

Returns

All sessions that are currently active.

SessionContainer getAllSessionsOfClient(int clientId)

Returns all sessions for a given client.

Parameters

clientId – Id of the client.

Returns

All sessions that were acquired for given client.

KanziStringVectorSharedPtr getAttributes()

Lists all service attributes.

Returns

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.

Returns

shared pointer to runtime data containing configuration properties.

ContentClientSharedPtr getContentClient() const

Access to content system.

Returns

Content client instance.

virtual ContentProviderCollectionSharedPtr getContentProvider()

Returns content provider for this service.

Returns

Collection of content providers, created by this service.

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

Get the custom types defined for this service.

Returns

Vector containing the custom types

KanziStringVectorSharedPtr getDisabledInvokables()
ConnectDomain *getDomain() const

Retrieves the connect domain.

Returns

the domain.

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

Find out value for enumeration string.

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

Returns

value if found.

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”.

Parameters

name – the name where the fully qualified name is to be composed

Returns

fully qualified configuration property name.

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.

Returns

pointer to generic invoker. ownership not transfered.

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

Access to interface domain.

Returns

Interface domain pointer.

inline virtual RuntimeDataObjectSharedPtr getModifiedConfigurationProperties()

Retrieves modified configuration properties as runtime data object.

Overriden by corresponding Concept class.

Returns

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

virtual string getName()

Returns the override name.

Returns

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.

Returns

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.

Returns

schema as xml.

virtual const ServiceDescription &getServiceDescription() const

Access the static service description info.

Returns

reference to service information.

inline virtual p2p::RoutingRulesSharedPtr getServiceRoutingInformation()

Return service routing information.

Returns

XML format string describing the preferred routing instructions.

virtual const ServiceState &getServiceState() const

Gets service state information.

Returns

the state.

AbstractSessionSharedPtr getSession(int clientId, int sessionId)

Returns session by client & session id.

Parameters
  • clientId – Id of the client.

  • sessionId – Id of the session.

Returns

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

int getStopInterval() const

Retrieve service stop interval.

Returns

stop interval in seconds.

WorkQueueInterface *getWorkQueue() const

Access to signal that allows to invoke work().

Returns

The signal.

bool hasEnumValues(const string &name)

Checks if enum has been defined on this service.

Parameters

name – Name of the enum definition.

Returns

True if values have been registered for the name.

bool hasSubscriptions(const string &identifier)

Check if the given identifier has any subscriptions.

Parameters

identifier – The identifier to check, what this means is implementation specific

Returns

True if at least one subscriber is found

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.

Returns

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

Parameters
  • clientId – client identifier number

  • sessionId – session identifier number

  • dispatcher – message dispatching functionality for the session.

  • instanceName – name for the service/session instance

Returns

newly allocated session. ownership is transfered.

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.

Parameters

typeName – The name of the type

Returns

InvokableOperationResult defining the success

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.

Parameters

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

Returns

InvokableOperationResult defining the success

virtual InvokableOperationResult removeRuntimedataElement(const string &elementIdentifier)

Remove runtime data element from the service runtime data.

Parameters

elementIdentifier – Specifies which element to remove

Returns

Is the operation successful or not

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.

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

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

Returns

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

AbstractService::ServiceControlResult resetService(ServiceArgumentsSharedPtr arguments)

Tries to reset service.

Returnvalue indicates the status of execution.

Parameters

arguments – optional arguments passed along with the control request.

Returns

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

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.

Returns

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).

Parameters

xml – XML format schema

Returns

true if succeeded. false if problems.

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.

Parameters
  • milliseconds – timeout in milliseconds

  • callback – function to be called when timer expires.

Returns

handle that can then be used cancel the timer.

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.

Parameters
  • milliseconds – timeout in milliseconds

  • callback – function to be called when timer expires.

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

Returns

handle that can then be used cancel the timer.

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

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.

Returns

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

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

Parameters

serviceControlSource – what caused the service control to be accomplished.

Returns

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

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.

Returns

version as string “1.0”

bool valid() const

Is version number valid.

Returns

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 bool operator!=(const Version &lhs, const Version &rhs)
inline friend bool operator<(const Version &lhs, const Version &rhs)
inline friend bool operator<=(const Version &lhs, const Version &rhs)
inline friend bool operator==(const Version &lhs, const Version &rhs)
inline friend bool operator>(const Version &lhs, const Version &rhs)
inline 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.

Returns

true if service is initialized.

inline bool running() const

Checks whether service is running.

Returns

true if service is running.

inline bool stopped() const

Checks whether service is stopped.

Returns

true if service is stopped.

Public Members

int m_state

Service state value.

string m_stateDescription

detailed description