Services Module

services.services

TcEx Framework API Service module.

class tcex.services.api_service.ApiService(tcex: object)[source]

Bases: CommonService

TcEx Framework API Service module.

property command_map: dict

Return the command map for the current Service type.

format_query_string(params: dict) str[source]

Convert name/value array to a query string.

Parameters:

params – The query params for the request.

Returns:

The query params reformatted as a string.

Return type:

str

format_request_headers(headers: dict) dict[source]

Convert name/value array to a headers dict.

Parameters:

headers – The dict of key/value header data.

Returns:

The restructured header data.

Return type:

dict

format_response_headers(headers: dict) dict[source]

Convert name/value array to a query string.

Parameters:

headers – The dict header data to be converted to key/value pairs.

Returns:

The restructured header data.

Return type:

dict

process_run_service_command(message: dict)[source]

Process the RunService command.

 1{
 2  "command": "RunService",
 3  "apiToken": "abc123",
 4  "bodyVariable": "request.body",
 5  "headers": [ { key/value pairs } ],
 6  "method": "GET",
 7  "queryParams": [ { key/value pairs } ],
 8  "requestKey": "123abc",
 9  "userConfig": [{
10    "name": "tlpExportSetting",
11    "value": "TLP:RED"
12  }],
13}
Parameters:

message – The message payload from the server topic.

process_run_service_response(*args, **kwargs)[source]

Handle service event responses.

(‘200 OK’, [(‘content-type’, ‘application/json’), (‘content-length’, ‘103’)])

process_shutdown_command(message: dict)[source]

Handle shutdown command.

service_thread(name: str, target: Callable[bool], args: Optional[tuple] = None, kwargs: Optional[dict] = None, session_id: Optional[str] = None, trigger_id: Optional[int] = None)[source]

If this is a run-service command, run it with the thread pool.

For everything else, use parent’s implementation.

Parameters:
  • name – The name of the thread.

  • target – The method to call for the thread.

  • args – The args to pass to the target method.

  • kwargs – Additional args.

  • session_id – The current session id.

  • trigger_id – The current trigger id.

TcEx Framework Service Common module

class tcex.services.common_service.CommonService(tcex: object)[source]

Bases: object

TcEx Framework Service Common module

Shared service logic between the supported service types: * API Service * Custom Trigger Service * Webhook Trigger Service

_create_logging_handler()[source]

Create a logging handler.

add_metric(label: str, value: Union[int, str])[source]

Add a metric.

Metrics are reported in heartbeat message.

Parameters:
  • label – The metric label (e.g., hits) to add.

  • value – The value for the metric.

property command_map: dict

Return the command map for the current Service type.

static create_session_id() str[source]

Return a uuid4 session id.

Returns:

A unique UUID string value.

Return type:

str

heartbeat()[source]

Start heartbeat process.

heartbeat_broker_check()[source]

Send self check message to ensure communications with message broker.

heartbeat_monitor()[source]

Publish heartbeat on timer.

increment_metric(label: str, value: Optional[int] = 1)[source]

Increment a metric if already exists.

Parameters:
  • label – The metric label (e.g., hits) to increment.

  • value – The increment value. Defaults to 1.

listen()[source]

List for message coming from broker.

loop_forever(sleep: Optional[int] = 1) bool[source]

Block and wait for shutdown.

Parameters:

sleep – The amount of time to sleep between iterations. Defaults to 1.

Returns:

Returns True until shutdown received.

Return type:

Bool

property metrics: dict

Return current metrics.

on_connect_handler(client, userdata, flags, rc)[source]

On connect method for mqtt broker.

on_message_handler(client, userdata, message)[source]

On message for mqtt.

process_acknowledged_command(message: dict)[source]

Process the Acknowledge command.

Parameters:

message – The message payload from the server topic.

process_broker_check(message: dict)[source]

Implement parent method to log a broker check message.

1{
2    "command": "BrokerCheck",
3}
Parameters:

message – The message payload from the server topic.

process_heartbeat_command(message: dict)[source]

Process the HeartBeat command.

1{
2    "command": "Heartbeat",
3    "metric": {},
4    "memoryPercent": 0,
5    "cpuPercent": 0
6}
Parameters:

message – The message payload from the server topic.

process_invalid_command(message: dict)[source]

Process all invalid commands.

Parameters:

message – The message payload from the server topic.

process_logging_change_command(message: dict)[source]

Process the LoggingChange command.

1{
2    "command": "LoggingChange",
3    "level": "DEBUG"
4}
Parameters:

message – The message payload from the server topic.

process_shutdown_command(message: dict)[source]

Implement parent method to process the shutdown command.

1{
2    "command": "Shutdown",
3    "reason": "Service disabled by user."
4}
Parameters:

message – The message payload from the server topic.

property ready: bool

Return ready boolean.

service_thread(name: str, target: Callable[bool], args: Optional[tuple] = None, kwargs: Optional[dict] = None, session_id: Optional[str] = None, trigger_id: Optional[int] = None)[source]

Start a message thread.

Parameters:
  • name – The name of the thread.

  • target – The method to call for the thread.

  • args – The args to pass to the target method.

  • kwargs – Additional args.

  • session_id – The current session id.

  • trigger_id – The current trigger id.

property session_id: Optional[str]

Return the current session_id.

property thread_name: str

Return a uuid4 session id.

property trigger_id: Optional[int]

Return the current trigger_id.

update_metric(label: str, value: Union[int, str])[source]

Update a metric if already exists.

Parameters:
  • label – The metric label (e.g., hits) to update.

  • value – The updated value for the metric.

TcEx Framework Service Trigger Common module.

class tcex.services.common_service_trigger.CommonServiceTrigger(tcex: object)[source]

Bases: CommonService

TcEx Framework Service Trigger Common module.

Shared service logic between the supported service types: * Custom Trigger Service * Webhook Trigger Service

_tcex_testing(session_id: str, trigger_id: int)[source]

Write data required for testing framework to Redis.

Parameters:
  • session_id – The context/session id value for the current operation.

  • trigger_id – The trigger ID for the current playbook.

_tcex_testing_fired_events(session_id: str, fired: bool)[source]

Write fired event data to KV Store to be used in test validation.

Parameters:
  • session_id – The context/session id value for the current operation.

  • fired – The value to increment the count by.

property command_map: dict

Return the command map for the current Service type.

create_config(trigger_id: int, message: str, status: bool)[source]

Add config item to service config object.

Parameters:
  • trigger_id – The trigger ID for the current config.

  • message – A simple message for the action.

  • status – The passed/fail status for the App handling of config.

  • logfile – The CreateConfig logfile to return in response ack.

delete_config(trigger_id: int, message: str, status: str)[source]

Delete config item from config object.

Parameters:
  • trigger_id – The trigger ID for the current config.

  • message – A simple message for the action.

  • status – The passed/fail status for the App handling of config.

fire_event(callback: Callable[bool], **kwargs)[source]

Trigger a FireEvent command.

Parameters:
  • callback – The trigger method in the App to call.

  • trigger_ids – A list of trigger ids to trigger.

fire_event_publish(trigger_id: int, session_id: str, request_key: Optional[str] = None)[source]

Send FireEvent command.

Parameters:
  • trigger_id – The ID of the trigger.

  • session_id – The generated session for this fired event.

  • request_key – The request key for this response.

fire_event_trigger(callback: Callable[bool], playbook: object, session_id: str, trigger_id: int, config: dict, **kwargs: str)[source]

Fire event for trigger.

Parameters:
  • callback – The App callback method for firing an event.

  • playbook – A configure playbook instance for using to interact with KvStore.

  • session_id – The current session Id.

  • trigger_id – The current trigger Id.

  • config – A dict containing the configuration information.

log_config(trigger_id: str, config: dict)[source]

Log the config while hiding encrypted values.

Parameters:
  • trigger_id – The current trigger Id.

  • config – The configuration to be logged.

process_create_config_command(message: dict)[source]

Process the CreateConfig command.

 1{
 2    "appId": 387,
 3    "command": "CreateConfig",
 4    "triggerId": 1,
 5    "config": {
 6        "password": "test-pass",
 7        "username": "test-user",
 8        "cc_action": "pass",
 9        "tc_playbook_out_variables": "#Trigger:1:testing.body!String"
10    },
11    "apiToken": "SVC:8:QQuyIp:1596817138182:387:+9vBOAT8Y56caHRcjLa4IwAqABoatsYOU ... ",
12    "expireSeconds": 1596817138
13}
Parameters:

message – The message payload from the server topic.

process_delete_config_command(message: dict)[source]

Process the DeleteConfig command.

1{
2    "appId": 387,
3    "command": "DeleteConfig",
4    "triggerId": 1
5}
Parameters:

message – The message payload from the server topic.

property thread_trigger_id: Optional[str]

Return the current thread trigger id.

property trigger_logfile: str

Return the logfile name based on date and thread name.

update_trigger_value(trigger_id: int, input_name: str, new_value: Any)[source]

Send UpdateTriggerValue command.

Parameters:
  • trigger_id – the ID of the trigger to update.

  • input_name – the name of the input to update.

  • new_value – the new value for the input.

TcEx Framework MQTT message broker module.

class tcex.services.mqtt_message_broker.MqttMessageBroker(broker_host: str, broker_port: int, broker_timeout: int, broker_token: Optional[Sensitive] = None, broker_cacert: Optional[str] = None)[source]

Bases: object

TcEx Framework MQTT message broker module.

add_on_connect_callback(callback: callable, index: Optional[int] = None)[source]

Add a callback for on_connect events.

Parameters:
  • callback – A callback that matches signature of an on_connect event.

  • index – The index value to insert the callback into the list.

add_on_disconnect_callback(callback: callable, index: Optional[int] = None)[source]

Add a callback for on_disconnect events.

Parameters:
  • callback – A callback that matches signature of an on_disconnect event.

  • index – The index value to insert the callback into the list.

add_on_log_callback(callback: callable, index: Optional[int] = None)[source]

Add a callback for on_log events.

Parameters:
  • callback – A callback that matches signature of an on_log event.

  • index – The index value to insert the callback into the list.

add_on_message_callback(callback: callable, index: Optional[int] = None, topics: Optional[List[str]] = None)[source]

Add a callback for on_message events.

Parameters:
  • callback – A callback that matches signature of an on_message event.

  • index – The index value to insert the callback into the list.

  • topics – A optional list of topics to call callback. If value is None then callback will always be called.

add_on_publish_callback(callback: callable, index: Optional[int] = None)[source]

Add a callback for on_publish events.

Parameters:
  • callback – A callback that matches signature of an on_publish event.

  • index – The index value to insert the callback into the list.

add_on_subscribe_callback(callback: callable, index: Optional[int] = None)[source]

Add a callback for on_subscribe events.

Parameters:
  • callback – A callback that matches signature of an on_subscribe event.

  • index – The index value to insert the callback into the list.

add_on_unsubscribe_callback(callback: callable, index: Optional[int] = None)[source]

Add a callback for on_unsubscribe events.

Parameters:
  • callback – A callback that matches signature of an on_unsubscribe event.

  • index – The index value to insert the callback into the list.

property client: object

Return MQTT client.

connect()[source]

Listen for message coming from broker.

on_connect(client, userdata, flags, rc)[source]

Handle MQTT on_connect events.

on_disconnect(client, userdata, rc)[source]

Handle MQTT on_disconnect events.

on_log(client, userdata, level, buf)[source]

Handle MQTT on_log events.

on_message(client, userdata, message)[source]

Handle MQTT on_message events.

on_publish(client, userdata, result)[source]

Handle MQTT on_publish events.

on_subscribe(client, userdata, mid, granted_qos)[source]

Handle MQTT on_subscribe events.

on_unsubscribe(client, userdata, mid)[source]

Handle MQTT on_unsubscribe events.

publish(message: str, topic: str)[source]

Publish a message on client topic.

Parameters:
  • message – The message to be sent on client topic.

  • topic – The broker topic.

register_callbacks()[source]

Register all the message broker callbacks.

TcEx Framework Webhook Service Trigger module.

class tcex.services.webhook_trigger_service.WebhookTriggerService(tcex: object)[source]

Bases: CommonServiceTrigger

TcEx Framework Webhook Service Trigger module.

callback_response_handler(callback_response: Any, message: dict)[source]

Handle the different types of callback responses.

# Webhook App (default)

  • Dict - Playbook will not be launched and provided data

    will be used in the response to the client.

  • True - Playbook will be launched.

  • Else - Playbook will NOT be launched.

# webhookResponseMarshall Feature App

  • Callable - Playbook will be launched and if marshall callback will be set to response.

  • True - Playbook will be launched.

  • Else - Playbook will NOT be launched.

# webhookServiceEndpoint Feature App

For this feature the callback method must fire the event on it’s own.

  • Dict - Playbook will not be launched and provided data

    will be used in the response to the client.

  • Else - Response will be set to default of statusCode=200, body=None, and headers=[].

Parameters:
  • callback_response – The response from the webhook callback method.

  • message – The message payload from the server topic.

callback_response_marshall(callback_response: Any, message: dict)[source]

Handle the different types of callback responses.

# webhookResponseMarshall Feature App

  • Callable - Playbook will be launched and if marshall callback will be set to response.

  • True - Playbook will be launched.

  • Else - Playbook will NOT be launched.

Parameters:
  • callback_response – The response from the webhook callback method.

  • message – The message payload from the server topic.

callback_response_service_endpoint(callback_response: Any, message: dict)[source]

Handle the different types of callback responses.

# webhookServiceEndpoint Feature App

For this feature the callback method must fire the event on it’s own.

  • Dict - Playbook will not be launched and provided data

    will be used in the response to the client.

  • Else - Response will be set to default of statusCode=200, body=None, and headers=[].

Parameters:
  • callback_response – The response from the webhook callback method.

  • message – The message payload from the server topic.

callback_response_webhook(callback_response: Any, message: dict)[source]

Handle the different types of callback responses.

  • Dict - Playbook will not be launched and provided data

    will be used in the response to the client.

  • True - Playbook will be launched.

  • Else - Playbook will NOT be launched.

Parameters:
  • callback_response – The response from the webhook callback method.

  • message – The message payload from the server topic.

property command_map: dict

Return the command map for the current Service type.

process_webhook_event_command(message: dict)[source]

Process the WebhookEvent command.

 1{
 2    "appId": 387,
 3    "command": "WebhookEvent",
 4    "triggerId": 1,
 5    "requestKey": "cd8c7a3a-7968-4b97-80c9-68b83a8ef1a1",
 6    "method": "GET",
 7    "headers": [
 8        {
 9            "name": "Accept-Encoding",
10            "value": "gzip, deflate, br"
11        }
12    ],
13    "queryParams": [
14        {
15            "name": "registration",
16            "value": "true"
17        }
18    ]
19}
Parameters:

message – The message payload from the server topic.

process_webhook_marshall_event_command(message: dict)[source]

Process the WebhookMarshallEvent command.

 1{
 2    "appId": 95,
 3    "bodyVariable": "request.body",
 4    "command": "WebhookMarshallEvent",
 5    "headers": [
 6        {
 7            "name": "Accept",
 8            "value": "*/*"
 9        }
10    ],
11    "requestKey": "c29927c8-b94d-4116-a397-e6eb7002f41c",
12    "statusCode": 200,
13    "triggerId": 1234
14}
Parameters:

message – The message payload from the server topic.

publish_webhook_event_acknowledge(message: dict)[source]

Publish the WebhookEventResponse message.

Parameters:

message – The message from the broker.

publish_webhook_event_response(message: dict, callback_response: dict)[source]

Publish the WebhookEventResponse message.

Parameters:
  • message – The message from the broker.

  • callback_response – The data from the callback method.

  • playbook – Configure instance of Playbook used to write body.

publish_webhook_marshall_event_acknowledge(message: dict)[source]

Publish the WebhookEventResponse message.

1{
2    "command": "Acknowledged",
3    "requestKey": "cd8c7a3a-7968-4b97-80c9-68b83a8ef1a1",
4    "triggerId": 1,
5    "type": "WebhookMarshallResponse"
6}
Parameters:

message – The message from the broker.