ThingsBoard Common
Note:
This is not an official project of the ThingsBoard authors! Please refer to ThingsBoard - Open-source IoT Platform for official ThingsBoard projects!
This project serves as a toolkit allowing other projects to use the same packages/modules as codebase.
These projects are using the ThingsBoard platform and extend it with additional functionality.
What it is for
thingsboard.common holds what the ThingsBoard applications of this family (endpoint, monitor, ...) share. The
core of it is how to run a worker thread that keeps going when the world around it fails:
| You want | Use |
|---|---|
| A thread that repeats a step, retries it when it fails, and stops cleanly | Threaded |
| Growing, jittered delays between attempts of anything | Backoff |
| To know which threads are dead or stuck | ThreadMonitor |
Besides, thingsboard.common.utils has small helpers (strings, paths, timestamps, resources). It needs Python 3.13 or
later and ships type hints (py.typed). It has no dependency on an MQTT client.
The snippets below are excerpts. The complete scripts are in examples/, and the tests run them:
PYTHONPATH=src python examples/threaded_retry.py.
Threaded: a worker thread that retries
Subclass Threaded and implement _step(). The thread calls it again and again, with no pause of its own: _step()
blocks, or calls _thread_sleep_interval() to sleep one control interval.
from thingsboard.common.core import Backoff, Threaded
class Connector(Threaded):
def __init__(self):
# Retry after 0.1 s, 0.2 s, ... at most 1 s (the defaults are 2 s up to 60 s)
super().__init__(control_interval_in_seconds=0.1, backoff=Backoff(initial=0.1, maximum=1.0))
def _step(self): # Raise to tell it failed
connect_and_work()
self._thread_sleep_interval() # Ends at once on stop_thread()
def _is_fatal(self, exc): # Retrying cannot help: the thread ends, see last_error
return isinstance(exc, PermissionError)
connector = Connector()
connector.setup_thread() # Creates the thread (and registers it, see ThreadMonitor)
connector.start_thread()
...
connector.stop_thread() # Ends the wait or sleep at once, then joins the thread
Full example: examples/threaded_retry.py.
Retry mode (retry_on_error = True, the default). If _step() raises an Exception, the thread:
- ends if
_is_fatal(exc)says so, with the exception inlast_error(and logged); - else logs it, calls
_on_failure(exc, delay)(e.g. to release what the failed step left open), waitsdelayseconds and calls_step()again.
The delay comes from the Backoff and grows while the failures last. The wait is cut short by stop_thread(), by
retry_now() (also if the step is still running, for a request to retry) and by wakeup_thread() (only if the thread
is waiting).
What is logged. The first failure of an outage is logged with its traceback, then at most one per
failure_log_interval seconds (default 60); the others go to debug level. Override _describe_failure(exc, delay) to
change level, message or traceback, e.g. to log an outage that is expected as a warning without a traceback.
Hooks and knobs: _step(), _is_fatal(), _on_failure(), _describe_failure(), retry_on_error,
failure_log_interval, backoff, last_error, thread_alive, retry_now(), wakeup_thread().
Stopping. stop_thread() is safe to call at any time (never started, already stopped, died, or from the thread
itself). A thread that is blocked in a step and does not leave in time is retired: it ends on its own as soon as it
gets back, and changes nothing of the object, even if the thread was started again meanwhile.
Not retrying. Set retry_on_error = False in the subclass to have a failure end the thread (with the error in
last_error). A subclass may also override _run() with a loop of its own, then _step(), retry and backoff are not
used. Its thread still beats when it calls _thread_sleep_interval(), but the ThreadMonitor then checks it for DEAD
only, as there is no telling how often it beats; register it with your own stalled_after to change that.
Backoff: delays between attempts
Threaded uses it in retry mode. Use it directly for a loop of your own:
from thingsboard.common.core import Backoff
backoff = Backoff(initial=2.0, maximum=60.0, factor=2.0, jitter=0.25, stable_after=10.0)
backoff.record_success() # whenever an attempt went well
delay = backoff.next_delay() # whenever one failed
backoff.wait(delay) # blocks until the delay is over, or interrupt() / skip_next_wait()
The delay grows by factor after each failure up to maximum, and restarts at initial once things went well for
stable_after seconds: a flapping connection keeps its long delay, one that was good for a while gets a quick retry.
The jitter only shortens the delay, so maximum always holds. Full example, on a clock of its own so that nothing has to
wait: examples/backoff.py.
ThreadMonitor: which threads are not live, and why
ThreadMonitor is an ordinary object (no singleton, no class state), so several may coexist. It is passive: call
check() regularly, e.g. from the main loop of your application, and decide what to do about a fault (restart, exit,
...). The monitor does neither.
from thingsboard.common.core import Fault, ThreadMonitor
monitor = ThreadMonitor()
poller = Poller(thread_monitor=monitor) # A Threaded registers its thread in setup_thread()
poller.setup_thread()
poller.start_thread()
for fault in monitor.check(): # Every thread that is not live, [] if all are
print(fault.name, fault.reason, fault.since, fault.last_error)
if fault.reason is Fault.DEAD: # The thread ended, last_error tells why
poller.start_thread() # Restarting registers the new thread with a fresh heartbeat
# Fault.STALLED: alive, but no cycle completed for too long (e.g. blocked in a call)
monitor.is_live() # True if check() finds nothing
Full example, with a thread that stalls and one that dies: examples/thread_monitor.py.
-
A thread is
DEADif it ended andSTALLEDif it is alive but has not beaten itsHeartbeatforstalled_afterseconds.sinceis the time (on the monitor's clock,time.monotonicby default) of its last sign of life. -
Threadedbeats after each_step(), failed or not, and in each_thread_sleep_interval(). Its defaultstalled_afteris 10 control intervals plus the longest backoff delay, as it does not beat while it waits to retry. A step that blocks for longer than that makes the thread look stalled. -
Any other thread registers itself and beats on its own:
heartbeat = monitor.register(thread, name='reader', stalled_after=30.0) # stalled_after=None: dead-only ... heartbeat.beat() # once per completed cycle monitor.deregister(thread)
-
check()changes nothing of the threads. The monitor logs once when a thread stops being live and once when it is live again, not on everycheck(). A restarted thread takes over the state of the one it replaces (same thread registered again, or same name afterderegister()): a thread that was logged as dead is logged as live again.
On failure: what the library does, and what it leaves to you
| The library does | You do |
|---|---|
| Catches the exception of a step, logs it (throttled), waits and retries with growing delays | Decide what is fatal (_is_fatal), what to release (_on_failure), how loud to be (_describe_failure) |
Ends the thread on a fatal error, or in retry_on_error = False, keeps the error in last_error and logs it |
Restart it, or exit: call start_thread() again |
Keeps heartbeats and tells, on check(), which threads are dead or stalled, and logs each change once |
Call check() regularly and act on the faults |
| Stops threads quickly and retires one that does not leave in time | Make steps that block return when _thread_should_run is false |
| Never kills a thread, never restarts one | Everything else: reconnecting, giving up, alerting |
Migrating to 1.0.0
Breaking changes, for the changelog:
- Retry mode is the default. A
Threadedthat implements_step()retries a failing step with backoff instead of ending. Setretry_on_error = Falsein the subclass to keep the old behavior (a failure ends the thread). A subclass that overrides_run()is not affected. ThreadMonitoris an instance, not a singleton. Gone:ThreadMonitor.instance(), the class-levelregister(),deregister()andthreadList, thelog_name_prefixargument. Create one withThreadMonitor()and pass it to what is to be monitored (Threaded(thread_monitor=monitor), ormonitor.register(thread)).check_threads()is nowcheck(). It returns a list ofLivenessFault(empty if all threads are live) instead of abool, and finds stalled threads as well as dead ones.is_live()gives the old yes/no.register()takes athreading.Thread(not aThreaded) and returns aHeartbeat(notTrue);deregister()returnsNone(notTrue).- A thread that crashes is logged by the class's logger and ends at once. Before, the error went to the root logger
and the thread lingered for 5 s before it ended. The error is now also in
last_error, and theThreadMonitorreports the thread as dead without that delay. - The
tb-mqtt-clientrequirement is gone. An application that imports it must depend on it itself. - Python 3.13 or later is required (it was 3.9).
Also new, not breaking: Backoff, RetryLoop, LogThrottle, last_error, retry_now(), thread_alive, type hints
and py.typed, and a stop_thread() that is safe to call at any time.
Metadata
Release files for thingsboard-common 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| thingsboard_common-1.0.0.tar.gz | 41.8 kB | Without provenance | Details for thingsboard_common-1.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| thingsboard_common-1.0.0-py3-none-any.whl | Python 3 | none | any | Details for thingsboard_common-1.0.0-py3-none-any.whl |
Total release size: 66.9 kB
Release files / thingsboard_common-1.0.0.tar.gz
| Download URL | thingsboard_common-1.0.0.tar.gz |
|---|---|
| Size | 41.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
66b500407d54cb13a790eec9f4217c3c57afd21c980abbfce3f09ec708e0c711
|
|
BLAKE2b-256 checksum How to use checksums |
cbe8e48cddd790ede697829d756821d443146833d9064d628fe21c89feac4e95
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Release files / thingsboard_common-1.0.0-py3-none-any.whl
| Download URL | thingsboard_common-1.0.0-py3-none-any.whl |
|---|---|
| Size | 25.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1b349d7def77d4230a4a780ac492e1790345c5ebd869f57df549697ad605ac00
|
|
BLAKE2b-256 checksum How to use checksums |
360cb9230465932fbad1d2c142c091703fa850b14a38b2e8ec522f0082e776c4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Security for thingsboard-common 1.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.