Documentation

12.4. Python API Event Handler

12.4.1. Introduction

SFTPPlus allows developers to write custom event handlers using the Python programming language.

The handlers are execute in separate independent processes / CPU cores, without shared memory. This is why the handle() method of the extension needs to be a @staticmethod and always received the configuration.

The handler is initialized multiple time. One instance is created in the main process and extra instances are created for each CPU.

A single extension instance can have the onStart(configuration) / onStop() method called multiple times during its lifetime. onStart(configuration) and onStop() methods are only called for the instance running in the main process.

The code for the event handler needs to be placed in a Python file (module) inside the extension/ folder from the SFTPPlus installation folder.

You can find an extensive example inside the extension/demo_event_handler.py folder of the default SFTPPlus installation.

Below is an example extension code that is also used to document the available API and functionalities.

  1# Place this file in `extension/demo_event_handler.py`
  2# inside SFTPPlus' installation folder.
  3#
  4# For the event handler set
  5# type = extension
  6# entry_point = python:demo_event_handler.DemoEventHandler
  7#
  8from __future__ import unicode_literals
  9import json
 10
 11
 12class DemoEventHandler(object):
 13    """
 14    An event handler which just emits another event with details of the
 15    received events.
 16
 17    Events handler API extensions can emit the events:
 18
 19    * 20174 - Emitted by SFTPPlus for critical errors.
 20              Should not be explicitly emitted by the extension.
 21    * 20000 - For debug messages.
 22    * 20200 - For normal messages.
 23
 24    This is also used as a documentation for the API and is included in
 25    the automated regression testing process.
 26    """
 27
 28    def __init__(self):
 29        """
 30        Called when the event handler is initialized in each worker and
 31        in the main process.
 32        """
 33        self._configuration = None
 34
 35    def onStart(self, parent):
 36        """
 37        Called in the main process when the event handler starts.
 38
 39        `parent.configuration` is the Unicode string defined in the
 40        extension configuration option.
 41
 42        Any exception raised here will stop the event handler from
 43        starting.
 44        """
 45        self._parent = parent
 46        self._configuration = parent.configuration
 47
 48    def onStop(self):
 49        """
 50        Called in the main process when the event handler stops.
 51        """
 52        self._configuration = None
 53
 54    def getConfiguration(self, event):
 55        """
 56        Called in the main process before dispatching the event to
 57        the worker process.
 58
 59        It can be used as validation for the event,
 60        before handling the event in a separate CPU core.
 61
 62        Return the configuration for the event as Unicode.
 63
 64        Return `None` when the event handling should be skipped and the
 65        `handle` function will no longer be called for this emitted event.
 66
 67        As advanced usage, it can return a `deferred` which will delay
 68        the execution of the event, without keeping a worker process busy.
 69        This mechanism can also be used for implementing a wait condition
 70        based on which the event is handled or not.
 71        """
 72        if event.id == '1234' or event.account.name == 'fail-user':
 73            # Any exception raised here will stop the handling of this
 74            # specific event instance by the extension.
 75            raise RuntimeError('Rejected event.')
 76
 77        if event.account.name == 'skip-user':
 78            # When `None` is returned the handling is skipped and the
 79            # `handle` function will not be called.
 80            return None
 81
 82        if event.account.name == 'skip-emit':
 83            # When skipping, you can trigger emitting an event with custom
 84            # message and attached data.
 85            return None, {'message': 'Handling skipped.', 'extra': 'skip-emit'}
 86
 87        if event.account.name == 'error-user':
 88            # You can skip and emit an event ID dedicated to errors.
 89            return None, {
 90                'event_id': '20202',
 91                'message': 'Can be a generic description for the error case.',
 92                'details': (
 93                    'Can contain details specific to this error. '
 94                    'Example a path to a file.'
 95                    ),
 96                'tb': 'Can include option traceback info as text.',
 97                }
 98
 99        if event.account.name == 'delay-user':
100            # For username `delay-user` we delay processing of the event
101            # for 0.5 seconds.
102            return self._parent.delay(0.5, lambda: 'delayed-configuration')
103
104        # Events can be triggered as part of the event handling configuration.
105        # You can have one for more events.
106        # Event can have custom ID or use default ID.
107        events = [
108            {'event_id': '20201', 'message': 'Handling started.'},
109            {'message': 'Default ID is 20200 as informational.'},
110            ]
111        # There is also the option of returning just the configuration,
112        # without any extra events.
113        return self._configuration, events
114
115    @staticmethod
116    def handle(event, configuration):
117        """
118        Called in a separate process when it should handle the event.
119
120        This is a static function that must work even when
121        onStart and onStop were not called.
122
123        `configuration` is the Unicode value returned by
124        getConfiguration(event).
125
126        If an exception is raised the processing is stopped for this event.
127        Future events will continue to be processed.
128        """
129        # Output will overlap with the output from other events as each
130        # event is handled in a separate thread.
131
132        if event.account.name == 'inactive-user':
133            # The extension can return a text that is logged as an event.
134            return 'Extension is not active from this user.'
135
136        if event.account.name == 'test@proatria.onmicrosoft.com':
137            # The extension has access to the Entra ID OAuth2 token.
138            return 'Entra ID token: {}'.format(event.account.token)
139
140        if event.account.name == 'ignored-user':
141            # Don't handle events from a certain username.
142            # The extension can return without any value, and no
143            # event is emitted.
144            return
145
146        # Here we get the full event, and then we sample a few fields.
147        message = (
148            'Received new event for DemoEventHandler\n'
149            '{event_json}\n'
150            '-----------------\n'
151            'configuration: {configuration}\n'
152            '-----------------\n'
153            'id: {event.id}\n'
154            'account: {event.account.name}\n'
155            'at: {event.timestamp.timestamp:f}\n'
156            'from: {event.component.name}\n'
157            'data: {event_data_json}\n'
158            '---\n'
159            )
160        output = message.format(
161            event=event,
162            event_json=json.dumps(event, indent=2),
163            event_data_json=json.dumps(event.data, indent=2),
164            configuration=configuration,
165            )
166
167        # Inform the handler to emit several events at the end.
168        # For a single event, it is recommended to pass only a dictionary.
169        return [
170            # The "message" attribute is required.
171            {'message': 'A simple message.'},
172            # Other attributes are allowed.
173            {'message': 'state', 'value': 'OK'},
174            # Explicit Event ID is also supported
175            # For this case the attributes should match the attributes
176            # required by the requested Event ID.
177            # Event '20201' requires the `message` attribute.
178            # Any extra attributes are allowed.
179            {'event_id': '20201', 'message': output, 'extra': configuration},
180            ]

This event handler can be configured as:

[event-handlers/56df1d0a-78c6-11e9-a2ff-137be4dbb9a8]
enabled = yes
type = extension
name = python-extension

entry_point = python:extensions.demo_event_handler.DemoEventHandler

configuration = some-free-text-configuration

12.4.2. Execution queue

SFTPPlus will only handle in parallel N events, where N is based on the number of CPUs available to the OS.

All the other events required to be handled by the extensions are placed into a queue.

The extension is called to handle the event only when there are free CPUs.

To prevent misconfiguration, there is a hard limit of 10 minutes for how long an event can stay in the queue and for processing the event.

12.4.3. Event data members

The event object received in the handler has the following structure.

The overall structure of the event object is presented below.

The following variables (case-insensitive) are provided as context data containing information about the event being triggered:

  • id

  • uuid

  • message

  • account.name

  • account.email

  • account.peer.address

  • account.peer.port

  • account.peer.protocol

  • account.peer.family

  • account.uuid

  • component.name

  • component.type

  • component.uuid

  • timestamp.cwa_14051

  • timestamp.iso_8601

  • timestamp.iso_8601_fractional

  • timestamp.iso_8601_local

  • timestamp.iso_8601_basic

  • timestamp.iso_8601_compact

  • timestamp.timestamp

  • server.name

  • server.uuid

  • data.DATA_MEMBER_NAME

  • data_json

The members of data are specific to each event. See Events page for more details regarding the data available for each event.

Many events have data.path and data.real_path, together with the associated data.file_name, data.directory_name, data.real_file_name, and data.real_directory_name.

Below is the description for the main members of the event object.


name:

id

type:

string

optional:

No

description:

ID of this event. See Events page for the list of all available events.


name:

message

type:

string

optional:

No

description:

A human readable description of this event.


The timestmap contains the following attributes:


name:

timestamp

type:

string

optional:

No

description:

Date and time at which this event was created, as Unix timestamp with milliseconds.


name:

cwa_14051

type:

string

optional:

No

description:

Date and time in CWA 14051 at which this event was emitted.


The account contains the following attributes:


name:

uuid

type:

string

optional:

No

description:

UUID of the account emitting this event. In case no account is associated with the event, this will be the special process account. In case the associated account is not yet authenticated this will be the special peer account.


name:

name

type:

string

optional:

No

description:

Name of the account emitting this event.


name:

email

type:

string

optional:

yes

description:

The primary email, as text associated to this account.


name:

emails

type:

string

optional:

yes

description:

A list of 2 value tuples (name, email) for the emails associated to this account.


name:

token

type:

string

optional:

Yes

description:

For Windows local or domain accounts a token that can be use to impersonate the account. For Azure AD accounts, when extra api_scopes are configured, this is the latest OAuth2 token that can be use to obtain access to an extra API or refresh a token.


name:

peer

type:

JSON Object

optional:

No

description:

Address of the peer attached to this account. This might be a local or remote address, depending on whether the account is used for client side or server side interaction.


The peer contains the following attributes:


name:

address

type:

string

optional:

No

description:

IP address of this connection.


name:

port

type:

integer

optional:

No

description:

Port number of this connection.


name:

protocol

type:

string

optional:

No

description:

OSI Layer 4 transport layer protocol used for this connection in the form of either TCP or UDP.


The component contains the following attributes:


name:

uuid

type:

string

optional:

No

description:

UUID of the component (service or transfer) emitting this event.


name:

type

type:

string

optional:

No

description:

Type of the component emitting this event.


The server contains the following attributes:


name:

uuid

type:

string

optional:

No

description:

UUID of the server emitting this event.


name:

type

type:

string

optional:

No

description:

Type of the server emitting this event.