Core

This section contains source code documentation of hydratk.core modules.

bootstrapper

HydraTK core bootstrapper

hydratk.core.bootstrapper._check_dependencies(dep_modules={'psutil': {'min-version': '3.1.1', 'package': 'psutil'}, 'importlib': {'package': 'importlib'}, 'setproctitle': {'min-version': '1.1.9', 'package': 'setproctitle'}, 'yaml': {'min-version': '3.11', 'package': 'pyyaml'}, 'zmq': {'min-version': '14.7.0', 'package': 'pyzmq'}, 'xtermcolor': {'min-version': '1.3', 'package': 'xtermcolor'}}, source='hydratk')

Method checks if all dependent modules can be loaded

Parameters:
  • dep_modules (dict) – dependent modules
  • source (str) – source hydratk module
Returns:

result, False if any module is missing

Return type:

bool

hydratk.core.bootstrapper.check_home_param()

Method checks for home parameter presence –home or -h to replace htk_root_dir location

Parameters:none
Returns:htk_root_changed
Return type:bool
hydratk.core.bootstrapper.check_profiler_param()

Method checks for profiler parameter presence –profiler or -p to start in profiling mode

Parameters:none
Returns:True if parameter present otherwise False
Return type:bool
hydratk.core.bootstrapper.run_app()

Method runs HydraTK application

Method is executed from htk command (automatically installed)

Parameters:none
Returns:void

corehead

HydraTK core module

class hydratk.core.corehead.AsyncCallBackHandler(hc)

Class AsyncCallBackHandler

__weakref__

list of weak references to the object (if defined)

class hydratk.core.corehead.CoreHead

Class CoreHead

Inherited from MessageHead, EventHandler, Debugger, Profiler, Logger

_bootstrap()

Method executes specific processing according to runlevel

Callback for functionality h_bootstrap

Parameters:none
Returns:True
Return type:bool
_create_config_db()

Method creates configuration database

Callback for command create-config-db Database filename is taken from option –config-db-file (prio 1), configuration System/DBConfig/db_file (prio 2)

If database exists it can be recreated using option -f|–force, otherwise is kept

Parameters:none
Returns:result
Return type:bool
_c_observer(init_by_start=False)

Method creates observer process and watches it during its lifecycle

When it is not active, application is stopped

Configuration options: Core/MessageService/id Core/MessageService/transport_type Core/MessageService/address Core/Service/pid_file

Parameters:

none

Returns:

void

Raises:
  • event – htk_before_cw_activity_check
  • event – htk_on_cobserver_ctx_switch
_c_worker(i, status, action_status, pipe_conn, is_alive_check)

Method watches worker process during its lifecycle

Process polls messages from queue

Parameters:
  • i (int) – process id
  • status (int) – activity status
  • action_status (int) – action status
  • pipe_conn (obj) – pipe process connection
  • is_alive_check (float) – time interval check
Returns:

void

Raises:

event – htk_on_cworker_init

_check_co_privmsg()

Method checks queue for observer messages and processes them

Parameters:none
Returns:void
_write_config_db(db_file)

Method writes data from configuration file to database

Parameters:db_file (str) – database filename including path
Returns:void
_dopoll(poller)

Method reads message from queue

Parameters:poller (obj) – message queue receiver
Returns:message
Return type:obj
_check_core_msg_queue()

Method checks queue for message

Message is sent via event if present (method doesn’t wait if queue is empty)

Parameters:none
Returns:True/False if queue is/isn’t empty
Return type:bool
_check_cw_privmsg()

Method checks queue for worker messages and processes them

Parameters:none
Returns:void
_check_cw_activity()

Method checks worker activity

Parameters:none
Returns:void
_do_command_action()

Method processes command

Command must have registered callback

Parameters:none
Returns:void
_load_db_config()

Method loads configuration from database

Database file is stored in configuration System/DBConfig/db_file

Parameters:none
Returns:void
_process_extension_configs()

Method searches configuration directory for extension specific configuration files

Each file is reported via event htk_before_append_extension_config_file

Parameters:none
Returns:void
Raises:event – htk_before_append_extension_config_file
_append_extension_config_from_file(ext_config_file)

Method parses extension configuration file

Parameters:ext_config_file (str) – config filename including path
Returns:void
_merge_base_config(config)

Method merges configuration with in memory configuration

Parameters:config (dict) – configuration with dictionary structure
Returns:void
config_var_default_processor(match)

Method is processing config variable definition from macro processor

Parameters:match (obj) – regexp object
Returns:parsed variable content
Return type:mixed
Raises:KeyError – for unavailable config variable keys
_load_base_config()

Method loads base configuration from file

Parameters:none
Returns:void
_apply_config()

Method initializes several configurable options

Debug, language, message router, count of workers

Configuration options: System/Debug/enabled System/Debug/level System/Language/id Core/Options/run_mode Core/MessageRoute/id Core/Workers/total

Parameters:none
Returns:void
_load_extensions()

Method loads extensions specified in configuration

Internal extensions are imported as module

External extensions are included to PYTHONPATH

Parameters:none
Returns:void
_load_extension(ext_name, ext_cfg)

Method loads internal extension

Parameters:
  • ext_name (str) – extension name
  • ext_cfg (dict) – extension configuration
Returns:

void

Raises:

exception – Exception

_extension_module_import(ext_full_path)

Method imports extension

Parameters:ext_full_path (str) – full module package name
Returns:module
Return type:obj
_load_module_from_file(filepath)

Method loads module from file

Supported formats: py (source code), pyc (compiled code)

Parameters:filepath (str) – filename including path
Returns:module
Return type:obj
_import_extension_messages(ext_path)

Method imports extension langtexts and commands help

Parameters:ext_path (str) – filename including path
Returns:void
_import_package_messages(import_package, msg_package)

Method imports package langtexts

Parameters:
  • import_package (str) – full package name
  • msg_package (str) – full package directory name
Returns:

void

_import_global_messages()

Method imports global langtexts and command help

Parameters:none
Returns:void
_reg_self_command_hooks()

Method registers global commands hooks

Parameters:none
Returns:void
_core_base_init()

Method executes specific processing for runlevel baseinit

Initialize translator, import global langtexts, register hooks

Parameters:none
Returns:True
Return type:bool
_runlevel_baseinit()

Method executes specific processing for runlevel baseinit

Initialize translator, import global langtexts, register hooks

Parameters:none
Returns:True
Return type:bool
_runlevel_config()

Method executes specific processing for runlevel config

Load configuration from several sources - base, extensions, database

Parameters:none
Returns:True
Return type:bool
_runlevel_extensions()

Method executes specific processing for runlevel extensions

Load extensions

Parameters:

none

Returns:

True

Return type:

bool

Raises:
  • event – htk_before_load_extensions
  • event – htk_after_load_extensions
_runlevel_cli()

Method executes specific processing for runlevel cli

Parse command options

Parameters:none
Returns:True
Return type:bool
_runlevel_core()

Method executes specific processing for runlevel core

Subscribe managers if running in parallel processing mode

Parameters:none
Returns:True
Return type:bool
_runlevel_appl()

Method executes specific processing for runlevel appl

Process command

Parameters:none
Returns:True
Return type:bool
_run_command_option_hooks(command_opt, command_opt_value)

Method is processing specified command option callbacks.

This method runs automatically in runlevel cli, if there’re specified options.

Parameters:
  • command_opt (str) – command option
  • command_opt_value (str) – option value
Returns:

number of processed callbacks

Return type:

int

_run_command_hooks(command)

Method is processing specified command callbacks.

By default this method is called in runlevel appl if there’s command specified

Parameters:command (str) – command
Returns:number of processed callbacks
Return type:int
_set_default_cli_params()

Method initializes command line according to configuration

Parameters:none
Returns:void
_set_pid_file(pid_file)

Method creates PID file

Parameters:pid_file (str) – PID filename including path
Returns:PID
Return type:int
_notify_thread(pid)

Method notifies thread via signal SIGPIPE

Parameters:pid (int) – PID to be notified
Returns:void
_send_ping(thr)

Method sends PING message to thread

Parameters:thr (obj) – thread to be pinged
Returns:void
_service_starter(cb, service_status, parent_conn)

Method starts service process

Parameters:
  • cb (method) – callback method
  • service_status (int) – service status
  • parent_conn (obj) – pipe connection
Returns:

void

_sig_retriever(signum, frame)

Method handles received signal

If signal is supported (see hydratk.core.hsignal), new event is fired Not supported signals are ignored

Parameters:
  • signum (int) – signal number
  • frame – NOT USED
Returns:

void

Raises:
  • event – htk_on_signal
  • event – htk_on_sigterm|htk_on_sigint|htk_on_sigpipe|htk_on_sigalamr
_reg_service_signal_hooks()

Method registers signal hooks supported for services

Parameters:none
Returns:void
_reg_self_fn_hooks()

Method registers functionality hooks

Bootstrap, runlevels

Parameters:none
Returns:void
_reg_self_event_hooks()

Method registers event hooks

Parameters:none
Returns:void
_parse_cli_args()

Method parses command and options

Recognized commands are handled, unrecognized are ignored

Parameters:none
Returns:void
Raises:event – htk_on_cmd_options
_process_cw_msg(msg, thr)

Method processes PONG message from worker

Parameters:
  • msg (dict) – message
  • thr (obj) – thread
Returns:

void

_trigger_cmsg(msg)

Method sends message in event

Parameters:msg (dict) – message
Returns:void
Raises:event – htk_on_cmsg_recv
_response_ping(msg)

Method sends PONG message

Parameters:msg (dict) – message
Returns:void
_process_privmsg(msg)

Method processes private message

If PING message is received, PONG message is sent as response

Parameters:msg (dict) – message
Returns:void
Raises:event – h_privmsg_recv
_remove_pid_file(pid_file)

Method deletes PID file

Parameters:pid_file (str) – PID filename including path
Returns:result
Return type:bool
_reg_self_signal_hooks()

Method registers signal hooks

Parameters:none
Returns:void
_start_app()

Method starts application

Initialize observer process

Parameters:none
Returns:void
Raises:event – htk_on_start
_stop_app(force_exit=False)

Method stops application

Parameters:force_exit (bool) – force application stopping
Returns:void
Raises:event – htk_on_stop
_stop_app_command()

Method stops application in controlled way

Process is terminated using signal SIGTERM

Configuration options - Core/Service/pid_file

Parameters:none
Returns:void
_init_message_router()

Method initializes message router

Parameters:none
Returns:void
_list_extensions()

Method prints extension list

Parameters:none
Returns:void

dbconfig

HydraTK database configuration and settings module

class hydratk.core.dbconfig.DBConfig(db_file)

Class DBConfig

__init__(db_file)

Class constructor

called when the object is initialized
Parameters:db_file (str) – database file path
connect()

Method connects configuration database

Parameters:none
Returns:void
writedb(base_config)

Method writes configuration database using basic configuration

Parameters:base_config (dict) – configuration
Returns:result
Return type:bool
cfg2db(d)

Method converts base config data to the database input format

Parameters:d (dict) – base configuration
Returns:cfg
Return type:dict
db2cfg(active_only=False)

Method converts config database data to base config input format

Parameters:active_only (bool) – whether to load only active settings, default False
Returns:records
Return type:list

debugger

HydraTK core integrated debugger

class hydratk.core.debugger.Debugger

Class Debugger

dbg_class_has_method(class_type, method_name)

Method returns class type if class has implemented selected method_name

Dictionary {file, module, func, line, call_path}

Parameters:
  • class_type (mixed) – class type definition or tuple of class types
  • method_name (str) – method name
Returns:

class type - if class has implemented selected method_name bool: False

Return type:

type

fromhere(trace_level=1)

Method returns location of executed code

Dictionary {file, module, class, func, line, call_path}

Parameters:trace_level (int) – level in stacktrace
Returns:code location
Return type:dict
function()

Method returns executed function name

Parameters:none
Returns:function
Return type:str
file()

Method returns executed filename

Parameters:none
Returns:filename
Return type:str
line()

Method returns executed line number

Parameters:none
Returns:line number
Return type:int
module()

Method returns executed module name

Parameters:none
Returns:module
Return type:str
errmsg(msg)

Method sends error message

Parameters:msg (str) – error message
Returns:void
warnmsg(msg)

Method sends warning message

Parameters:msg (str) – warning message
Returns:void
demsg(event_id, *args)

Method sends debug message via event

Parameters:
  • event_id (str) – event
  • args (args) – arguments
Returns:

void

Raises:

event – event_id

dmsg(msg, level=1, channel=[1, 10])

Method sends debug message

Parameters:
  • msg (str) – message
  • level (int) – debug level
  • channel (list) – debug channel
Returns:

True if message was send to processing otherwise False

Return type:

bool

match_channel(channel, profile_channel=None)

Method checks if required channels are tracked by debugger

Parameters:
  • channel (obj) – required channel as int (channel id), list (channel ids)
  • profile_channel (list) – logger profile channels
Returns:

result

Return type:

bool

dbg_format_msg(profile, msg, location={'call_path': None, 'file': None, 'module': None, 'func': None, 'line': None, 'class': None}, level=1, channel=[])

Method implements message formating

Parameters:
  • profile (dict) – logger dictionary profile
  • msg (string) – message
  • location (dict) – message trace parameters
  • level (int) – debug level
  • channel (list) – channel filter list
Returns:

result

Return type:

bool

__weakref__

list of weak references to the object (if defined)

event

HydraTK default event class

class hydratk.core.event.Event(event_id, *args, **kwargs)

Class Event

__init__(event_id, *args, **kwargs)

Class constructor

Called when the object is initialized

Parameters:
  • event_id (str) – event
  • args (args) – arguments
  • kwargs (kwargs) – key value arguments
Raises:

error – ValueError

id

Method gets id attribute

Parameters:none
Returns:str
argc()

Method gets count of arguments

Parameters:none
Returns:count of arguments
Return type:int
args()

Method gets args attribute

Parameters:none
Returns:tuple
get_all_data()

Method gets event data

Parameters:none
Returns:data
Return type:dict
get_data(key)

Method gets requested event data

Parameters:key (str) – data key
Returns:data value
Return type:obj
set_data(key, value)

Method sets requested event data

Parameters:
  • key (str) – data key
  • value (obj) – data value
Returns:

void

Raises:

error – ValueError

__weakref__

list of weak references to the object (if defined)

argv(num)

Method gets request event argument

Parameters:num (int) – argument index
Returns:argument value
Return type:obj
set_argv(num, val=None)

Method sets requested event argument

Parameters:
  • num (int) – argument index
  • val (obj) – argument value
Returns:

void

stop_propagation()

Method stops event propagation

Parameters:none
Returns:void
skip_before_hook

skip_before_hook property getter

skip_after_hook

skip_after_hook property getter

prevent_default()

Method prevents default event processing

Parameters:none
Returns:void
run_default()

Method enables default event processing

Parameters:none
Returns:void
will_run_default()

Method gets default event processing

Parameters:none
Returns:run_default
Return type:bool
propagate()

Method gets propagate attribute

Parameters:none
Returns:bool

eventhandler

HydraTK core event handling implementation class

class hydratk.core.eventhandler.EventHandler

Class EventHandler

__weakref__

list of weak references to the object (if defined)

extension

HydraTK extensions implementation class

class hydratk.core.extension.Extension(core_instance=None)

Class Extension

__getattr__(name)

Method gets required MasterHead attribute

Subclass must have enabled attribute _wrap_hydra_attrs

Parameters:name (str) – attribute name
Returns:attribute value
Return type:obj
Raises:error – AttributeError
__init__(core_instance=None)

Class constructor

Called when object is initialized Set extensions metadata If implemented in subclass - check dependencies, import modules, register actions

Parameters:core_instance (obj) – CoreHead reference
get_ext_name()

Method gets extension name

Parameters:none
Returns:name
Return type:str
get_ext_version()

Method gets extension version

Parameters:none
Returns:version
Return type:str
__weakref__

list of weak references to the object (if defined)

get_ext_author()

Method gets extension author

Parameters:none
Returns:author
Return type:str
get_ext_info()

Method gets extension summary info

Parameters:none
Returns:info
Return type:str

hookhead

HydraTK python system hooks

class hydratk.core.hookhead.ModuleLoader

Class ModuleLoader

find_module(module_name, package_path)

Method imports module langtexts

Parameters:
  • module_name (str) – full module name
  • package_path (str) – full package
Returns:

ModuleLoeader

Return type:

obj

load_module(module_name)

Method loads module

Parameters:module_name (str) – full module name
Returns:module
Return type:obj

logger

HydraTK core integrated logging features

class hydratk.core.logger.Logger

Class Logger

spout(data)

Method prints data

Parameters:data (str) – data

Returns:

_log_init_handlers()

Method initialize default Logger output handlers

Args:

Returns:void
_log_init_msg_formaters()

Method initialize default Logger output formaters

Args:

Returns:void
_log_init_profiles()

Method loads active Logger profiles from config

Parameters:data (str) – data
Returns:void
_log_event(ev, *args)

Method is transforming event data through the Logger profiles

Parameters:
  • ev (obj) – Event object
  • *args (mixed) – unpacked Event parameters
Returns:

result

Return type:

bool

_log_screen_handler(profile, *args)

Method is default screen output handler implementation

Parameters:
  • profile (dict) – logger dictionary profile
  • *args (mixed) – unpacked message parameters
Returns:

result

Return type:

bool

_log_file_handler(profile, *args)

Method is default logfile output handler implementation

Parameters:
  • profile (dict) – logger dictionary profile
  • *args (mixed) – unpacked message parameters
Returns:

result

Return type:

bool

__weakref__

list of weak references to the object (if defined)

masterhead

HydraTK master module

class hydratk.core.masterhead.MasterHead

Class MasterHead extends from CoreHead decorated by EventHandler, Debugger and Profiler

__init__()

Class constructor

MasterHead use singleton pattern, constructor should never be called directly

Parameters:none
Raises:error – ValueError
exception_handler(extype, value, traceb)

Exception handler hook

This method is registered as sys.excepthook callback and transforms unhandled exceptions to the HydraTK Event
Parameters:
  • extype (str) – Exception type
  • value (str) – Exception message info
  • (obj) Exception traceback object (traceb) –
Returns:

void

Raises:

event – htk_on_uncaught_exception

get_translator()

Method returns current traslator object initialized from hydratrk.lib.translation.translator.Translator

Parameters:none
Returns:Translator
Return type:obj
static get_head()

Method is primary connector to HydraTK core

This method returns current active MasterHead instance or creates a new one For preventing inner conflicts it’s designed as singleton
Parameters:none
Returns:MasterHead
Return type:obj

Example:

from hydratk.core.masterhead import MasterHead

mh = MasterHead.get_head()
get_config(var_filter=None, str_eval=True)

Method return current loaded configuration

Parameters:none
Returns:self._config
Return type:dict

Example:

from hydratk.core.masterhead import MasterHead

mh = MasterHead.get_head()
config = mh.get_config()
get_config_var(cfg_var, bind_vars=None, str_eval=True)

Method returns config varible

Parameters:
  • cfg_var (str) – config variable in format Group.Section.varname, eg.: System.Language.id
  • bind_vars (dict) – dictionary with bindable variables: $(var), which can be additionaly used while evaluating string value
  • str_eval (bool) – evaluate string value, default is True
Returns:

evaluated or raw string value

Return type:

str

Example:

from hydratk.core.masterhead import MasterHead

mh = MasterHead.get_head()
langue = mh.get_config_var('System.Language.id')
check_run_mode()

Method checks for run_mode input parameter (-m, –run-mode) from command line and validates if it’s supported

Parameters:none
Returns:run_mode_changed, True in case if it’s supported otherwise False
Return type:bool
check_language()

Method checks for language change input parameters (-l, –language) from command line and validates if it’s supported

Parameters:none
Returns:language_changed, True in case if it’s supported otherwise False
Return type:bool
check_config()
Method checks for config file change input parameters (-c, –config) from command line and validates its existence
If the new config file exists, then current config file path will be replaced by new one
Parameters:none
Returns:config_changed, True in case if config file exists otherwise False
Return type:bool
check_profile()

Method checks for profile option parameter (help, -p, –profile) with specified output statistics file

Parameters:none
Returns:result, bool enable_profiler, string statistics file
Return type:tuple
check_debug()

Method checks for debug option with specified level parameter (-d, –debug) from command line

Parameters:none
Returns:debug_changed, True in case if it’s set otherwise False
Return type:bool
check_debug_channel()

Method checks for debug channel option with specified channel filters from command line (-d, –debug-channel)

Parameters:none
Returns:debug_channel_changed, True in case if it’s set otherwise False
Return type:bool
match_short_option(opt, value_expected=False, d_opt=None, allow_multiple=False, opt_group='htk')

Method registers command line short option check

Parameters:
  • opt (str) – Short option string
  • value_expected (bool) – Whether the option value is expected or not
  • d_opt (str) – target option
  • allow_multiple (bool) – multiple option occurences allowed
  • opt_group (obj) – list or str, option group, default htk
Returns:

void

Raises:

error – TypeError

match_long_option(opt, value_expected=False, d_opt=None, allow_multiple=False, opt_group='htk')

Method registers command line long option check

Parameters:
  • opt (str) – long option string
  • value_expected (bool) – Whether the option value is expected or not
  • d_opt (str) – target option
  • allow_multiple (bool) – multiple option occurences allowed
  • opt_group (obj) – list or str, option group, default htk
Returns:

void

Raises:

error – TypeError

match_cli_option(opt, value_expected=False, d_opt=None, allow_multiple=False, opt_group='htk')

Method registers command option check

Parameters:
  • opt (obj) – tuple or list, short and long option strings
  • value_expected (bool) – Whether the option value is expected or not
  • d_opt (str) – target option
  • allow_multiple (bool) – multiple option occurences allowed
  • opt_group (obj) – list or str, option group, default htk
Raises:

error – TypeError

match_cli_command(cmd, opt_group='htk')

Method registers command line command check

Parameters:
  • cmd (str) – Command string
  • opt_group (str) – option group, default htk
Returns:

void

Raises:

error – ValueError: if the command is already registered for matching or the command is an empty string

set_cli_cmdopt_profile(profile)

Method sets new command option profile

Parameters:profile (str) – option group
Returns:void
Raises:error – InputError
set_cli_appl_title(help_title, cp_string)

Method sets custom application title

Parameters:
  • help_title (str) – help
  • cp_string (str) – copyright
Returns:

void

Raises:

error – InputError

register_log_output_profile(log_type, options={})

Method adds logger output profile functionality hook

Only one callback can be registered. This method is usable for functionality extending, replacement.
Parameters:
  • log_type (mixed) – string log_type id or list of dictionaries in format {‘log_type’ : ‘log_type_id’, ‘options’ : { ‘opt’ : ‘val’} }
  • options (dict) – Log profile options alse extended for specified output handler
Returns:

register success in case that log_type is non-empty string int: number of successfully registered handlers in case that log_type is list of dictionaries with multiple defined hooks

Return type:

bool

Example:

from hydratk.core.MasterHead import MasterHead

mh = MasterHead.get_head()
mh.register_log_output_handler('error', my_error_log_handler)
register_fn_hook(fn_id, callback='')

Method adds/replaces functionality hook

Only one callback can be registered. This method is usable for functionality extending, replacement.
Parameters:
  • fn_id (mixed) – string functionality id or list of dictionaries in format {‘fn_id’ : ‘functionality_id’, ‘callback’ : callable_fc }
  • callback (callable) – User defined callback
Returns:

register success in case that fn_id is non-empty string int: number of successfully registered fn hooks in case that fn_id is list of dictionaries with multiple defined hooks

Return type:

bool

Example:

from hydratk.core.MasterHead import MasterHead

mh = MasterHead.get_head()
mh.register_fn_hook('mh_bootstrap', my_bootstrapper)
run_fn_hook(fn_id, *args, **kwargs)

Method is processing registered callback for specified fn_id.

This method is usable for functionality extending, replacement.
Parameters:
  • fn_id (str) – functionality id
  • args (mixed) – optional arguments
  • kwargs (mixed) – optional keyword arguments
Returns:

void

Raises:

exception – Exception

Example:

from hydratk.core.masterhead import MasterHead
from hydratk.core.event import Event

mh = MasterHead.get_head()
mh.run_fn_hook('mh_bootstrap')
dummy_fn_hook()

Method runs dummy hook

Parameters:none
Returns:True
Return type:bool
start_pp_app()

Method starts application in parallel mode

Parameters:none
Returns:void
stop_pp_app(force_exit=False)

Method stops application in parallel mode

Parameters:force_exit (bool) – force application termination
Returns:void
register_command_hook(cmd, callback='')

Method adds command hook

This method is usable for functionality extending, replacement, notification purposes etc.
Parameters:
  • cmd (mixed) – string Command or list of dictionaries in format {‘command’ : ‘defined_command’, ‘callback’ : callable_fc }
  • callback (callable) – User defined callback
Returns:

in case that cmd is defined by string int: number of successfully added hooks in case that cmd is dictionary with multiple defined callbacks

Return type:

bool

Example:

from hydratk.core.MasterHead import MasterHead

multi_hook = [
              {'command' : 'mycommand1', 'callback' : obj1.fc_command_handler1 }, # you can specify multiple command hooks
              {'command' : 'mycommand2', 'callback' : obj2.fc_command_handler2 },
              {'command' : 'mycommand3', 'callback' : fc_command_handler3 }
             ]

mh = MasterHead.get_head()
mh.register_command_hook(multi_hook) # register all hooks at once
mh.register_command_hook('mycommand4', fc_command_handler) # single registration
register_command_option_hook(cmd_opt, callback='')

Methods adds command option listener.

This method is usable for functionality extending, replacement, notification purposes etc.

Parameters:
  • cmd_opt (list or string) – Command option
  • callback (callable) – Function callback
Returns:

in case that cmd_opt is defined by string int: number of successfully added hooks in case that cmd_opt is dictionary with multiple defined callbacks

Return type:

bool

Example:

from hydratk.core.MasterHead import MasterHead

multi_hook = [
             {'command_option' : 'option', 'callback' : obj1.fc_command_handler1 }, # you can specify multiple option hooks
             {'command_option' : 'mycommand2', 'callback' : obj2.fc_command_handler2 },
             {'command_option' : 'mycommand3', 'callback' : fc_command_handler3 }
            ]

mh = MasterHead.get_head().
register_event_hook(event, callback='', unpack_args=False, priority=50)

Methods registers event listener.

This method is useful for extending the system functionality
Parameters:
  • event (list or string) – event
  • callback (callable) – function callback
  • unpack_args (bool) – optional request that arguments from event object will be passed directly to the listener, default false
  • priority (int) – optional priority number > 0, lower number means higher priority, default value is const.EVENT_HOOK_PRIORITY
Returns:

in case that cmd_opt is defined by string int: number of successfully registered hooks in case that event is dictionary with multiple defined callbacks

Return type:

bool

Example:

from hydratk.core.masterhead import MasterHead
from hydratk.core import const

mh = MasterHead.get_head()

hook = [
        {'event' : 'htk_on_error', 'callback' : self.my_error_handler, 'unpack_args' : True, 'priority' : const.EVENT_HOOK_PRIORITY - 1}, # will be prioritized
        {'event' : 'htk_on_warning', 'callback' : self.my_warning_handler, 'unpack_args' : False}
       ]

mh.register_event_hook(hook)
unregister_event_hook(event, callback=None)

Methods unregisters event listener(s) for specified event.

This method is useful for extending the system functionality
Parameters:
Returns:

in case that callback is not specified int: number of successfully unregistered hooks for matching callback

Return type:

bool

Example:

from hydratk.core.masterhead import MasterHead


mh = MasterHead.get_head()

hook = [
        {'event' : 'htk_on_error', 'callback' : self.my_error_handler, 'unpack_args' : True, 'priority' : const.EVENT_HOOK_PRIORITY - 1}, # will be prioritized
        {'event' : 'htk_on_warning', 'callback' : self.my_warning_handler, 'unpack_args' : False}
       ]

mh.register_event_hook(hook)
mh.unregister_event_hook('htk_on_error') # unregisters all hooks, returns True
mh.unregister_event_hook('htk_on_warning', self.my_warning_handler) # unregisers matching hook only, returns 1
replace_event_hook(event, callback, record)

Methods replaces event listener(s) for specified event.

This method is useful for extending the system functionality
Parameters:
  • event (string) – event
  • callback (callable) – matching callback
  • record (dict) – new callback record
Returns:

number of successfully replaced hooks for matching callback

Return type:

int

Raises:

exception – Exception

Example:

from hydratk.core.masterhead import MasterHead


mh = MasterHead.get_head()

hook = [
        {'event' : 'htk_on_error', 'callback' : self.my_error_handler, 'unpack_args' : True, 'priority' : const.EVENT_HOOK_PRIORITY - 1}, # will be prioritized
        {'event' : 'htk_on_warning', 'callback' : self.my_warning_handler, 'unpack_args' : False}
       ]

mh.register_event_hook(hook)

new_record = {
   'callback' : another_warning_handler,
   'unpack_args' : False
}

mh.replace_event_hook('htk_on_warning', self.my_warning_handler, new_record) # replaces matching hook only, returns 1
fire_event(oevent)

Method is processing specified event callbacks.

This method is usable for functionality extending, replacement, notification purposes etc.
Parameters:oevent (obj) – Event object type hydratk.core.event.Event
Returns:number of successfully processed event registered callbacks
Return type:int

Example:

from hydratk.core.masterhead import MasterHead
from hydratk.core.event import Event

mh = MasterHead.get_head()
event_id = 'myprefix_on_something_important'
oevent = Event('event_id')
oevent.set_data('alert','I just finished work')
print('This event was processed %d times' % mh.fire_event(oevent))
apply_command_options()

Method sets several command options

Debugging, language

Parameters:none
Returns:void
get_language()

Method gets language

Parameters:none
Returns:language
Return type:str
have_command_action()

Method checks if command is set

Parameters:none
Returns:result
Return type:bool
get_command_action()

Method gets command

Parameters:none
Returns:command
Return type:str
service_registered(service_name)

Method checks if service is registered

Parameters:service_name (str) – service
Returns:result
Return type:bool
register_service(service_name, description, cb)

Method registers given service and creates own process

Parameters:
  • service_name (str) – service
  • description (str) – description
  • cb (callable) – callback
Returns:

True

Return type:

bool

Raises:
  • error – TypeError
  • error – SystemError
  • error – ValueError
start_service(service_name)

Method starts service

Parameters:service_name (str) – service
Returns:result
Return type:bool
stop_services()

Method stops all running services

Service is tried via signal SIGINT first If not successful it is stopped via signal SIGKILL

Args:

Returns:void
init_core_threads()

Method initializes threads according to configuration

Parameters:none
Returns:void
destroy_core_threads()

Method destroys threads

Parameters:none
Returns:void
add_core_thread(i=None)

Method adds new thread to the pool

Parameters:i (int) – thread id
Returns:void
get_thrid()

Method gets thread id (name)

Parameters:none
Returns:id
Return type:str
create_ext_skel()

Method creates extension skeleton

Skeleton contains extension module, configuration, langtexts, installation In default (non-interactive) mode the skeleton is created from template in ~/hydratk directory In interactive mode the skeleton wizard asks the user for several data (path, name, author, ...)

Command line options - –force, –interactive, –ext-skel-path

Parameters:none
Returns:result
Return type:bool
create_lib_skel()

Method creates library skeleton

Skeleton contains extension module, installation In default (non-interactive) mode the skeleton is created from template in ~/hydratk directory In interactive mode the skeleton wizard asks the user for several data (path, name, author, ...)

Command line options - –force, –interactive, –lib-skel-path

Parameters:none
Returns:result
Return type:bool
async_fn_ex(fn_id, *args, **kwargs)

Method sends functionality hook in asynchronous way as message

Parameters:
  • fn_id (str) – functionality
  • args (args) – arguments
  • kwargs (kwargs) – key value arguments
Returns:

void

send_msg(msg)

Method send message to queue

Parameters:msg (obj) – message
Returns:void
async_ext_fn(callback, result_callback, *args, **kwargs)

Method sends extension hook in asynchronous way as message

Parameters:
  • callback (tuple) – callback
  • result_callback (obj) – str or tuple, callback
  • args (args) – arguments
  • kwargs (kwargs) – key value arguments
Returns:

ticket id

Return type:

str

Raises:
  • error – TypeError
  • error – KeyError
get_async_ticket_content(ticket_id)

Method gets ticket content

Parameters:

ticket_id (str) – ticket

Returns:

content

Return type:

obj

Raises:
  • error – KeyError
  • error – TypeError
async_ticket_completed(ticket_id)

Method checks if ticket processing is completed

Parameters:

ticket_id (str) – ticket

Returns:

result

Return type:

bool

Raises:
  • error – KeyError
  • error – TypeError
delete_async_ticket(ticket_id)

Method deletes ticket

Parameters:ticket_id (str) – ticket
Returns:void
register_async_fn_ex(fn_id, callback, result_callback=None)

Method registers functionality hook in asynchronous way

Parameters:
  • fn_id (str) – functionality hook
  • callback (callable) – callback
  • result_callback (callable) – result callback
Returns:

True

Return type:

bool

Raises:

error – TypeError

reg_fn_cb(fn_id, callback, options=None)

Method is registering callback with specified fn_id.

This method is usable for functionality extending, replacement.
Parameters:
  • fn_id (str) – functionality id
  • callback (callable) – callback
  • options – not used
Returns:

True

Return type:

bool

Raises:

error – TypeError

register_async_fn(fn_id, callback)

Method registers functionality hook in asynchronous way

Parameters:
  • fn_id (str) – functionality hook
  • callback (callable) – callback
Returns:

True

Return type:

bool

Raises:

error – TypeError

get_ext(extension_name)

Method gets extensions

Parameters:

extension_name (str) – extension

Returns:

Extension

Return type:

obj

Raises:
  • error – IndexError
  • error – TypeError

message

HydraTK core commmunication messages definition

class hydratk.core.message.Message

Class Message

__weakref__

list of weak references to the object (if defined)

class hydratk.core.message.FnCallBackMsg(callback, *args, **kwargs)

Class FnCallBackMsg

Inherited from Message

__init__(callback, *args, **kwargs)

Class constructor

Called when object is initialized

Parameters:
  • callback (callable) – callback
  • args (args) – arguments
  • kwargs (kwargs) – key value arguments
set_callback(callback)

Method sets callback

Parameters:callback (callable) – callback
Returns:void
Raises:error – TypeError
set_args(*args, **kwargs)

Method sets arguments

Parameters:
  • args (args) – arguments
  • kwargs (kwargs) – key value arguments
Returns:

void

run()

Method executes callback

Args:

Returns:callback output
Return type:obj

messagehead

HydraTK core commmunication messages processing fuctionality

class hydratk.core.messagehead.MessageHead

Class MessageHead

_new_async_ticket_id()

Method creates new ticket

Parameters:none
Returns:ticket id
Return type:str
_new_async_ticket(ticket_id)

Method creates dummy ticket

Parameters:ticket_id (str) – ticket
Returns:void
_delete_async_ticket(ticket_id)

Method deletes ticket

Parameters:

ticket_id (str) – ticket

Returns:

void

Raises:
  • error – KeyError
  • error – TypeError
_reset_async_ticket_seq()

Method resets ticket id sequence

Parameters:none
Returns:void
_reg_msg_handlers()

Method registers message handlers to functionality hooks

Parameters:none
Returns:void
_process_cmsg(ev, msg)

Method processes message

Message contains functionality hook to be executed

Parameters:
  • ev – not used
  • msg (obj) – message in Base64 format
Returns:

void

_send_msg(msg)

Method sends message

Parameters:msg (dict) – message
Returns:True
Return type:bool
_msg_async_ext_fn(msg)

Method runs funcionality hook callback from message

Parameters:msg (dict) – message
Returns:True
Return type:bool
__weakref__

list of weak references to the object (if defined)

messagerouter

HydraTK message router

class hydratk.core.messagerouter.MessageRouter(id)

Class MessageRoute

__init__(id)

Class constructor

Called when object is initialized

Parameters:id (str) – message router id
Returns:void
Raises:error – TypeError
register_service(id, transport_type, options)

Method will add router service identificator using specified parameters

Parameters:
  • id (str) – service identifier
  • transport_type (int) – supported transport type, currently only IPC and TCP is supported
  • options (dict) – transport_type supported options
Returns:

True

Return type:

bool

Raises:

error – InputError

get_queue(service_id, action, options={})

Method will return a new instance of queue object for specified service_id

Parameters:
  • service_id (str) – service identifier
  • options (dict) – queue type optional settings
Returns:

socket

Return type:

obj

get_service_address(service_id)

Method gets service address

Parameters:service_id (str) – service identifier
Returns:address
Return type:str

profiler

HydraTK core integrated profiler

class hydratk.core.profiler.Profiler

Class Profiler

__init__()

Class constructor

Called when object is initialized

Parameters:none
check_profile_param()

Method checks for home parameter presence –home or -h to replace htk_root_dir location

Parameters:none
Returns:htk_root_changed
Return type:bool
start()

Method starts profiler

Parameters:none
Returns:void
finish()

Method stops profiler

Parameters:none
Returns:void
_configure_profiler_options()

Method sets profiler command line configuration (options -p, –profile)

Parameters:none
Returns:void

propertyhead

HydraTK properties module

class hydratk.core.propertyhead.PropertyHead

Class PropertyHead

current_async_ticket_id

current_async_ticket_id property getter

async_fn_tickets

async_fn_tickets property getter, setter

fn_cb_shared

fn_cb_shared property getter, setter

cbm

cbm property getter

cli_cmdopt_profile

opt_profile property getter

cfg

config property getter

config_mp

Config macro processor instance

debug

debug property getter

debug_level

debug_level property getter

debug_channel

debug_channel property getter

ext_cfg

extensions config property getter

extensions

extensions list property getter

lang

language property getter, setter

__weakref__

list of weak references to the object (if defined)

runlevel

runlevel property getter

run_mode

run_mode property getter, setter

trn

Translator instance getter

servicehead

HydraTK core services

class hydratk.core.servicehead.ServiceHead

Class ServiceHead

srv_async_cb(cbo)

Method sends callback message

Parameters:cbo (obj) – callback object
Returns:void
__weakref__

list of weak references to the object (if defined)