Worker Base
Job(worker: object = None, juuid: str = None, client_address: str = None, timeout: int = None, args: list = None, kwargs: dict = None, task: str = None, client_input_queue: object = None)
¤
Source code in norfab\core\worker.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
is_timed_out() -> bool
¤
Check if the job has exceeded its timeout.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the job has timed out, False otherwise or if timeout is not set. |
Source code in norfab\core\worker.py
96 97 98 99 100 101 102 103 104 | |
event(message: str, **kwargs: Any) -> None
¤
Handles an event by forwarding it to the worker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The message describing the event. |
required |
**kwargs
|
Any
|
Additional keyword arguments to include in the event. |
{}
|
Source code in norfab\core\worker.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
stream(data: bytes) -> None
¤
Streams data to the broker.
This method sends a message containing the client address, a unique identifier (UUID), a status code, and the provided data to the broker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
The data to be streamed to the broker. |
required |
Source code in norfab\core\worker.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | |
wait_client_input(timeout: int = 10) -> Any
¤
Waits for input from the client within a specified timeout period if no item
is available within the specified timeout, it returns None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
int
|
The maximum time (in seconds) to wait for input |
10
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The item retrieved from the |
Source code in norfab\core\worker.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
Task(input: Optional[BaseModel] = None, output: Optional[BaseModel] = None, description: Optional[str] = None, fastapi: Optional[dict] = None, mcp: Optional[dict] = None, agent: Optional[dict] = None)
¤
Validate is a class-based decorator that accept arguments, designed to validate the input arguments of a task function using a specified Pydantic model. It ensures that the arguments passed to the decorated function conform to the schema defined in the model.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
BaseModel
|
A Pydantic model used to validate the function arguments. |
name |
str
|
The name of the task, which is used to register the task for calling, by default set equal to the name of decorated function. |
result_model |
BaseModel
|
A Pydantic model used to validate the function's return value. |
fastapi |
dict
|
Dictionary with parameters for FastAPI |
mcp |
dict
|
Dictionary with parameters for MCP |
Methods:
| Name | Description |
|---|---|
__call__ |
Callable) -> Callable: Wraps the target function and validates its arguments before execution. |
merge_args_to_kwargs |
List, kwargs: Dict) -> Dict:
Merges positional arguments ( |
validate_input |
List, kwargs: Dict) -> None: Validates merged arguments against Pydantic model. If validation fails, an exception is raised. |
Usage
@Task()(input=YourPydanticModel) def your_function(arg1, arg2, ...): # Function implementation pass
Notes
- The decorator uses
inspect.getfullargspecto analyze the function's signature and properly map arguments for validation.
Source code in norfab\core\worker.py
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | |
__call__(function: Callable) -> Callable
¤
Decorator to register a function as a worker task with input/output validation and optional argument filtering.
This method wraps the provided function, validates its input arguments and output, and registers it as a task. It also removes 'job' and 'progress' keyword arguments if the wrapped function does not accept them.
Side Effects:
- Sets self.function, self.description, and self.name based on the provided function.
- Initializes input model if not already set.
- Updates the global NORFAB_WORKER_TASKS with the task schema.
Source code in norfab\core\worker.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 | |
make_input_model() -> None
¤
Dynamically creates a Pydantic input model for the worker's function by inspecting its signature.
This method uses inspect.getfullargspec to extract the function's argument names, default values,
keyword-only arguments, and type annotations. It then constructs a dictionary of field specifications,
giving preference to type annotations where available, and excluding special parameters such as 'self',
'return', 'job', and any args or *kwargs. The resulting specification is used to create a Pydantic
model, which is assigned to self.input.
The generated model used for input validation.
Source code in norfab\core\worker.py
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 | |
make_task_schema(wrapper) -> dict
¤
Generates a task schema dictionary for the current worker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wrapper
|
Callable
|
The function wrapper to be associated with the task. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
A dictionary containing the task's metadata, including: - function: The provided wrapper function. - module: The module name where the original function is defined. - schema: A dictionary with the following keys: - name (str): The name of the task. - description (str): The description of the task. - inputSchema (dict): The JSON schema for the input model. - outputSchema (dict): The JSON schema for the output model. - fastapi: FastAPI-specific metadata. - mcp: Model Context protocol metadata |
Source code in norfab\core\worker.py
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 | |
is_need_argument(function: callable, argument: str) -> bool
¤
Determines whether a given argument name is required by the function.
Source code in norfab\core\worker.py
570 571 572 573 574 575 | |
merge_args_to_kwargs(args: List, kwargs: Dict) -> Dict
¤
Merges positional arguments (args) and keyword arguments (kwargs)
into a single dictionary.
This function uses the argument specification of the decorated function to ensure that all arguments are properly combined into a dictionary. This is particularly useful for scenarios where **kwargs need to be passed to another function or model (e.g., for validation purposes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
list
|
A list of positional arguments passed to the decorated function. |
required |
kwargs
|
dict
|
A dictionary of keyword arguments passed to the decorated function. |
required |
Return
dict: A dictionary containing the merged arguments, where positional arguments are mapped to their corresponding parameter names.
Source code in norfab\core\worker.py
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 | |
validate_input(args: List, kwargs: Dict) -> None
¤
Function to validate provided arguments against model
Source code in norfab\core\worker.py
617 618 619 620 621 622 623 624 625 | |
JobDatabase(db_path: str, jobs_compress: bool = True)
¤
Thread-safe SQLite database manager for worker jobs.
Handles all job persistence operations with proper thread safety through connection-level locking and WAL mode for concurrent reads.
Attributes:
| Name | Type | Description |
|---|---|---|
db_path |
str
|
Path to the SQLite database file. |
_local |
local
|
Thread-local storage for database connections. |
_lock |
Lock
|
Lock for write operations to ensure thread safety. |
Initialize the job database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_path
|
str
|
Path to the SQLite database file. |
required |
jobs_compress
|
bool
|
If True, compress args, kwargs, and result_data fields. Defaults to True. |
True
|
Source code in norfab\core\worker.py
651 652 653 654 655 656 657 658 659 660 661 662 663 | |
add_job(uuid: str, client_address: str, task: str, args: list, kwargs: dict, timeout: int, timestamp: str) -> None
¤
Add a new job to the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uuid
|
str
|
Job UUID. |
required |
client_address
|
str
|
Client address. |
required |
task
|
str
|
Task name. |
required |
args
|
list
|
Task arguments. |
required |
kwargs
|
dict
|
Task keyword arguments. |
required |
timeout
|
int
|
Job timeout. |
required |
timestamp
|
str
|
Received timestamp. |
required |
Source code in norfab\core\worker.py
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 | |
get_next_pending_job() -> tuple
¤
Get the next pending job and mark it as STARTED.
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple
|
(uuid, received_timestamp) or None if no pending jobs. |
Source code in norfab\core\worker.py
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 | |
complete_job(uuid: str, result_data: dict) -> None
¤
Mark a job as completed and store its result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uuid
|
str
|
Job UUID. |
required |
result_data
|
dict
|
Result data as dictionary. |
required |
Source code in norfab\core\worker.py
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 | |
fail_job(uuid: str, result_data: dict) -> None
¤
Mark a job as failed and store its result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uuid
|
str
|
Job UUID. |
required |
result_data
|
dict
|
Result data as dictionary. |
required |
Source code in norfab\core\worker.py
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 | |
get_job_info(uuid: str, include_result: bool = False, include_events: bool = False) -> dict
¤
Get comprehensive job information including status, execution data, and optionally result data and events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uuid
|
str
|
Job UUID. |
required |
include_result
|
bool
|
If True, include result_data in the response. Defaults to False. |
False
|
include_events
|
bool
|
If True, include job events. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Job information with the following fields: - uuid: Job UUID - status: Job status (PENDING, STARTED, COMPLETED, FAILED, WAITING_CLIENT_INPUT) - received_timestamp: When job was received - started_timestamp: When job started execution - completed_timestamp: When job completed - client_address: Client address - task: Task name - args: Parsed task arguments list - kwargs: Parsed task keyword arguments dict - timeout: Job timeout |
dict
|
If include_result=True, also includes: - result_data: Result data dictionary (if available) |
|
dict
|
If include_events=True, also includes: - job_events: List of event dictionaries |
|
dict
|
Returns None if job not found. |
Source code in norfab\core\worker.py
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 | |
add_event(job_uuid: str, message: str, severity: str, task: str, event_data: dict) -> None
¤
Add an event for a job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_uuid
|
str
|
Job UUID. |
required |
message
|
str
|
Event message. |
required |
severity
|
str
|
Event severity. |
required |
task
|
str
|
Task name. |
required |
event_data
|
dict
|
Event data dictionary. |
required |
Source code in norfab\core\worker.py
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 | |
get_job_events(uuid: str) -> list
¤
Get all events for a job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uuid
|
str
|
Job UUID. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
List of event dictionaries. |
Source code in norfab\core\worker.py
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 | |
list_jobs(pending: bool = True, completed: bool = True, task: str = None, last: int = None, client: str = None, uuid: str = None) -> list
¤
List jobs based on filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pending
|
bool
|
Include pending jobs. |
True
|
completed
|
bool
|
Include completed jobs. |
True
|
task
|
str
|
Filter by task name. |
None
|
last
|
int
|
Return only last N jobs. |
None
|
client
|
str
|
Filter by client address. |
None
|
uuid
|
str
|
Filter by specific UUID. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
List of job dictionaries. |
Source code in norfab\core\worker.py
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 | |
close() -> None
¤
Close all database connections.
Source code in norfab\core\worker.py
1147 1148 1149 1150 1151 | |
WorkerWatchDog(worker)
¤
Bases: Thread
Class to monitor worker performance.
Attributes:
| Name | Type | Description |
|---|---|---|
worker |
object
|
The worker instance being monitored. |
worker_process |
Process
|
The process of the worker. |
watchdog_interval |
int
|
Interval in seconds for the watchdog to check the worker's status. |
memory_threshold_mbyte |
int
|
Memory usage threshold in megabytes. |
memory_threshold_action |
str
|
Action to take when memory threshold is exceeded ("log" or "shutdown"). |
runs |
int
|
Counter for the number of times the watchdog has run. |
watchdog_tasks |
list
|
List of additional tasks to run during each watchdog interval. |
Methods:
| Name | Description |
|---|---|
check_ram |
Checks the worker's RAM usage and takes action if it exceeds the threshold. |
get_ram_usage |
Returns the worker's RAM usage in megabytes. |
run |
Main loop of the watchdog thread, periodically checks the worker's status and runs tasks. |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
worker
|
object
|
The worker object containing inventory attributes. |
required |
Source code in norfab\core\worker.py
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 | |
stats() -> Dict
¤
Collects and returns statistics about the worker.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dict
|
A dictionary containing the following keys:
|
Source code in norfab\core\worker.py
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 | |
check_ram() -> None
¤
Checks the current RAM usage and performs an action if it exceeds the threshold.
This method retrieves the current RAM usage and compares it to the predefined
memory threshold. If the RAM usage exceeds the threshold, it performs an action
based on the memory_threshold_action attribute. The possible actions are:
- "log": Logs a warning message.
- "shutdown": Raises a SystemExit exception to terminate the program.
Raises:
| Type | Description |
|---|---|
SystemExit
|
If the memory usage exceeds the threshold and the action is "shutdown". |
Source code in norfab\core\worker.py
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 | |
get_ram_usage() -> float
¤
Get the RAM usage of the worker process.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The RAM usage in megabytes. |
Source code in norfab\core\worker.py
1251 1252 1253 1254 1255 1256 1257 1258 | |
run() -> None
¤
Executes the worker's watchdog main loop, periodically running tasks and checking conditions. The method performs the following steps in a loop until the worker's exit event is set:
- Sleeps in increments of 0.1 seconds until the total sleep time reaches the watchdog interval.
- Runs built-in tasks such as checking RAM usage.
- Executes additional tasks provided by child classes.
- Updates the run counter.
- Resets the sleep counter to start the cycle again.
Attributes:
| Name | Type | Description |
|---|---|---|
slept |
float
|
The total time slept in the current cycle. |
Source code in norfab\core\worker.py
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 | |
NFPWorker(inventory: NorFabInventory, broker: str, service: str, name: str, exit_event: object, log_level: str = None, multiplier: int = 6, keepalive: int = 2500)
¤
NFPWorker class is responsible for managing worker operations, including connecting to a broker, handling jobs, and maintaining keepalive connections. It interacts with the broker using ZeroMQ and manages job queues and events.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inventory
|
NorFabInventory
|
The inventory object containing base directory information. |
required |
broker
|
str
|
The broker address. |
required |
service
|
str
|
The service name. |
required |
name
|
str
|
The name of the worker. |
required |
exit_event
|
object
|
The event used to signal the worker to exit. |
required |
log_level
|
str
|
Logging level configured from worker inventory. |
None
|
multiplier
|
int
|
The multiplier value. Defaults to 6. |
6
|
keepalive
|
int
|
The keepalive interval in milliseconds. Defaults to 2500. |
2500
|
Source code in norfab\core\worker.py
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 | |
setup_logging(log_level: str = None) -> dict
¤
Configure logging for this worker process.
The worker uses the logging inventory it received during construction
as a per-process template and writes its default NorFab file sink to
__norfab__/logs/worker-<worker-name>.jsonl.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_level
|
str
|
Optional logging level override. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Logging configuration applied to this process. |
Source code in norfab\core\worker.py
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 | |
reconnect_to_broker() -> None
¤
Connect or reconnect to the broker.
This method handles the connection or reconnection process to the broker. It performs the following steps:
- If there is an existing broker socket, it sends a disconnect message, unregisters the socket from the poller, and closes the socket.
- Creates a new DEALER socket and sets its identity.
- Loads the client's secret and public keys for CURVE authentication.
- Loads the server's public key for CURVE authentication.
- Connects the socket to the broker.
- Registers the socket with the poller for incoming messages.
- Sends a READY message to the broker to register the service.
- Starts or restarts the keepalive mechanism to maintain the connection.
- Increments the reconnect statistics counter.
- Logs the successful registration to the broker.
Source code in norfab\core\worker.py
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 | |
send_to_broker(command: str, msg: list = None) -> None
¤
Send a message to the broker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
The command to send to the broker. Must be one of NFP.READY, NFP.DISCONNECT, NFP.RESPONSE, or NFP.EVENT. |
required |
msg
|
list
|
The message to send. If not provided, a default message will be created based on the command. |
None
|
Logs
Logs an error if the command is unsupported. Logs a debug message with the message being sent.
Thread Safety
This method is thread-safe and uses a lock to ensure that the broker socket is accessed by only one thread at a time.
Source code in norfab\core\worker.py
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 | |
load_inventory() -> dict
¤
Load inventory data from the broker for this worker.
This function retrieves inventory data from the broker service using the worker's name. It logs the received inventory data and returns the results if available.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
The inventory data results if available, otherwise an empty dictionary. |
Source code in norfab\core\worker.py
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 | |
worker_exit() -> None
¤
Method to override in child classes with a set of actions to perform on exit call.
This method should be implemented by subclasses to define any cleanup or finalization tasks that need to be performed when the worker is exiting.
Source code in norfab\core\worker.py
1843 1844 1845 1846 1847 1848 1849 1850 | |
get_inventory(job: Job) -> Result
¤
Retrieve the worker's inventory.
This method should be overridden in child classes to provide the specific implementation for retrieving the inventory of a worker.
Returns:
| Name | Type | Description |
|---|---|---|
Dict |
Result
|
A dictionary representing the worker's inventory. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the method is not overridden in a child class. |
Source code in norfab\core\worker.py
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 | |
get_version() -> Result
¤
Retrieve the version report of the worker.
This method should be overridden in child classes to provide the specific version report of the worker.
Returns:
| Name | Type | Description |
|---|---|---|
Dict |
Result
|
A dictionary containing the version information of the worker. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the method is not overridden in a child class. |
Source code in norfab\core\worker.py
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 | |
destroy(message: str = None) -> None
¤
Cleanly shuts down the worker by performing the following steps:
- Calls the worker_exit method to handle any worker-specific exit procedures.
- Sets the destroy_event to signal that the worker is being destroyed.
- Calls the destroy method on the client to clean up client resources.
- Joins all the threads (request_thread, reply_thread, event_thread, recv_thread) if they are not None, ensuring they have finished execution.
- Closes the database connections.
- Destroys the context with a linger period of 0 to immediately close all sockets.
- Stops the keepaliver to cease any keepalive signals.
- Logs an informational message indicating that the worker has been destroyed, including an optional message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
An optional message to include in the log when the worker is destroyed. |
None
|
Source code in norfab\core\worker.py
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 | |
is_url(url: str) -> bool
¤
Check if the given string is a URL supported by NorFab File Service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The URL to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if the URL supported by NorFab File Service, False otherwise. |
Source code in norfab\core\worker.py
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 | |
fetch_file(url: str, raise_on_fail: bool = False, read: bool = True) -> str
¤
Function to download file from broker File Sharing Service
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
file location string in |
required |
raise_on_fail
|
bool
|
raise FIleNotFoundError if download fails |
False
|
read
|
bool
|
if True returns file content, return OS path to saved file otherwise |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
File content if read is True, otherwise OS path to the saved file. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If raise_on_fail is True and the download fails. |
Source code in norfab\core\worker.py
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 | |
jinja2_render_templates(templates: list[str], context: dict = None, filters: dict = None) -> str
¤
Download (if needed) and render a list of Jinja2 templates with the given context and optional filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
templates
|
list[str]
|
A list of Jinja2 template strings or NorFab file paths. |
required |
context
|
dict
|
A dictionary containing the context variables for rendering the templates. |
None
|
filters
|
dict
|
A dictionary of custom Jinja2 filters to be used during rendering. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The rendered templates concatenated into a single string. |
Source code in norfab\core\worker.py
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 | |
jinja2_fetch_template(url: str) -> str
¤
Helper function to recursively download a Jinja2 template along with other templates referenced using "include" statements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
A URL in the format |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The file path of the downloaded Jinja2 template. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file download fails. |
Exception
|
If Jinja2 template parsing fails. |
Source code in norfab\core\worker.py
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 | |
event(message: str, juuid: str, task: str, client_address: str, **kwargs: Any) -> None
¤
Handles the creation and emission of an event.
This method takes event data, processes it, and sends it to the event queue. It also saves the event data to the database for future reference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The event message |
required |
juuid
|
str
|
Job ID for which this event is generated |
required |
task
|
str
|
Task name |
required |
client_address
|
str
|
Client address |
required |
**kwargs
|
Any
|
Additional keyword arguments to be passed when creating a NorFabEvent instance |
{}
|
Logs
Error: Logs an error message if the event data cannot be formed.
Source code in norfab\core\worker.py
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 | |
job_details(uuid: str = None, result: bool = True, events: bool = True) -> Result
¤
Method to get job details by UUID for completed jobs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uuid
|
str
|
The job UUID to return details for. |
None
|
result
|
bool
|
If True, return job result. |
True
|
events
|
bool
|
If True, return job events. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
Result |
Result
|
A Result object with the job details. |
Source code in norfab\core\worker.py
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 | |
job_list(pending: bool = True, completed: bool = True, task: str = None, last: int = None, client: str = None, uuid: str = None) -> Result
¤
Method to list worker jobs completed and pending.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pending
|
bool
|
If True or None, return pending jobs. If False, skip pending jobs. |
True
|
completed
|
bool
|
If True or None, return completed jobs. If False, skip completed jobs. |
True
|
task
|
str
|
If provided, return only jobs with this task name. |
None
|
last
|
int
|
If provided, return only the last N completed and last N pending jobs. |
None
|
client
|
str
|
If provided, return only jobs submitted by this client. |
None
|
uuid
|
str
|
If provided, return only the job with this UUID. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Result |
Result
|
Result object with a list of jobs. |
Source code in norfab\core\worker.py
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 | |
get_logs(last: int = 100, level: str = None, logger: str = None, since: str = None, until: str = None) -> Result
¤
Return this worker process JSONL log records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
last
|
int
|
Return the last N records after filtering. |
100
|
level
|
str
|
Filter by log severity. |
None
|
logger
|
str
|
Filter by logger name. |
None
|
since
|
str
|
Return records at or after this timestamp. |
None
|
until
|
str
|
Return records at or before this timestamp. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Result |
Result
|
Log records from this worker's process log file. |
Source code in norfab\core\worker.py
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 | |
echo(job: Job, raise_error: Union[bool, int, str] = None, sleep: int = None, *args: Any, **kwargs: Any) -> Result
¤
Echoes the job information and optional arguments, optionally sleeping or raising an error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job
|
Job
|
The job instance containing job details. |
required |
raise_error
|
str
|
If provided, raises a RuntimeError with this message. |
None
|
sleep
|
int
|
If provided, sleeps for the specified number of seconds. |
None
|
*args
|
Any
|
Additional positional arguments to include in the result. |
()
|
**kwargs
|
Any
|
Additional keyword arguments to include in the result. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Result |
Result
|
An object containing job details and any provided arguments. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in norfab\core\worker.py
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 | |
run_shell_cmd(job: Job, command: str, timeout: int = None) -> Result
¤
Runs a shell command on the worker host.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
str
|
Shell command to execute. |
required |
timeout
|
int
|
Maximum command runtime in seconds. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Result |
Result
|
Command execution details including stdout, stderr, and return code. |
Source code in norfab\core\worker.py
2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 | |
list_tasks(name: Union[None, str] = None, brief: bool = False) -> Result
¤
Lists tasks supported by worker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of a specific task to retrieve |
None
|
brief
|
bool
|
If True, returns only the list of task names |
False
|
Returns:
| Type | Description |
|---|---|
Result
|
Results returned controlled by this logic:
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If a specific task name is provided but not registered in NORFAB_WORKER_TASKS. |
Source code in norfab\core\worker.py
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 | |
get_watchdog_stats() -> Result
¤
Retrieve worker statistics from the watchdog.
Returns:
| Name | Type | Description |
|---|---|---|
Result |
Result
|
An object containing the statistics from the watchdog. |
Source code in norfab\core\worker.py
2361 2362 2363 2364 2365 2366 2367 2368 2369 | |
get_watchdog_configuration() -> Result
¤
Retrieves the current configuration of the watchdog.
Returns:
| Name | Type | Description |
|---|---|---|
Result |
Result
|
An object containing the watchdog configuration. |
Source code in norfab\core\worker.py
2371 2372 2373 2374 2375 2376 2377 2378 2379 | |
start_threads() -> None
¤
Starts multiple daemon threads required for the worker's operation.
This method initializes and starts the following threads
- request_thread: Handles posting requests using the _post function.
- reply_thread: Handles receiving replies using the _get function.
- event_thread: Handles event processing using the _event function.
- recv_thread: Handles receiving data using the recv function.
Each thread is started as a daemon and is provided with the necessary arguments, including queues and events as required.
Returns:
| Type | Description |
|---|---|
None
|
None |
Source code in norfab\core\worker.py
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 | |
run_next_job(uuid: str) -> None
¤
Processes the next job from the database.
This method performs the following steps:
- Loads job data from the database.
- Parses the job data to extract the task name, arguments, keyword arguments, and timeout.
- Executes the specified task method on the worker instance with the provided arguments.
- Handles any exceptions raised during task execution, logging errors and creating a failed Result object if needed.
- Saves the result of the job execution to the database.
- Marks the job as completed or failed in the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
uuid
|
str
|
The job UUID to process. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the executed task does not return a Result object. |
Source code in norfab\core\worker.py
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 | |
work() -> None
¤
Executes the main worker loop, managing job execution using a thread pool.
This method starts necessary background threads, then enters a loop where it:
- Queries the database for the next pending job.
- Atomically marks the job as started in the database.
- Submits the job to a thread pool executor for concurrent processing.
- Waits briefly if no pending jobs are found.
- Continues until either the exit or destroy event is set.
Upon exit, performs cleanup by calling the destroy method with a status message.
Source code in norfab\core\worker.py
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 | |
recv(worker, destroy_event) -> None
¤
Thread to process receive messages from broker.
This function runs in a loop, polling the worker's broker socket for messages every second. When a message is received, it processes the message based on the command type and places it into the appropriate queue or handles it accordingly. If the keepaliver thread is not alive, it logs a warning and attempts to reconnect to the broker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
worker
|
Worker
|
The worker instance that contains the broker socket and queues. |
required |
destroy_event
|
Event
|
An event to signal the thread to stop. |
required |
Commands
- NFP.POST: Places the message into the post_queue.
- NFP.DELETE: Places the message into the delete_queue.
- NFP.GET: Places the message into the get_queue.
- NFP.KEEPALIVE: Processes a keepalive heartbeat.
- NFP.DISCONNECT: Attempts to reconnect to the broker.
- Other: Logs an invalid input message.
Source code in norfab\core\worker.py
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 | |