Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/nokia/moler/llms.txt

Use this file to discover all available pages before exploring further.

Overview

Event extends ConnectionObserver for long-running observation tasks. Unlike Command, which fires once and completes, an Event keeps watching the connection and triggers a callback every time a matching pattern appears.
moler.event.Event
  └── moler.connection_observer.ConnectionObserver
Typical use cases:
  • Monitoring for log messages, alarms, or state changes.
  • Collecting repeated occurrences of a pattern (e.g., every SNMP trap).
  • Triggering actions in response to device output without stopping the observation.
Event is abstract. Subclass it and implement data_received(), pause(), and resume().

Constructor

Event(connection=None, till_occurs_times=-1, runner=None)
connection
AbstractMolerConnection
default:"None"
The connection to observe.
till_occurs_times
int
default:"-1"
How many times the event must occur before it automatically finishes. -1 means infinite — the event keeps running until explicitly cancelled or break_event() is called.
runner
ConnectionObserverRunner
default:"None"
The runner managing background execution. Resolved from the connection or the global default if None.
The default timeout is set to approximately 100 years so events do not timeout under normal circumstances.

Public methods

start

event.start(timeout=None, *args, **kwargs) -> Event
Start background observation. Validates the observer before delegating to the parent ConnectionObserver.start().
timeout
float
default:"None"
Override the event’s timeout. Rarely needed given the default infinite-like timeout.
Returns self.

add_event_occurred_callback

event.add_event_occurred_callback(callback, callback_params=None) -> None
Register a callable to be invoked each time the event occurs. Only one callback may be registered at a time.
callback
callable
required
Function to call when the event fires. Called as callback(**callback_params).
callback_params
dict
default:"{}"
Keyword arguments passed to callback each time it is called.
Raises MolerException if a callback is already registered.

remove_event_occurred_callback

event.remove_event_occurred_callback() -> None
Unregister the current callback. After this call, occurrences are still recorded but no function is invoked.

event_occurred

event.event_occurred(event_data) -> None
Record one occurrence of the event. Call this from data_received() when a match is found. Appends event_data to the internal occurrence list, triggers notify(), and — if till_occurs_times is positive and the count is reached — calls break_event() automatically.
event_data
Any
required
Data associated with this occurrence (e.g., the matched line or a parsed dict).
Raises ResultAlreadySet if the event is already done.

notify

event.notify() -> None
Logs the occurrence and invokes the registered callback (if any). Called automatically by event_occurred().

get_last_occurrence

event.get_last_occurrence() -> Any
Returns the event_data value from the most recent occurrence, or None if the event has not yet occurred.

break_event

event.break_event(force=False) -> None
Stop the event and record its final result as the list of all occurrences so far.
force
boolean
default:"False"
If False and the number of occurrences is less than till_occurs_times, a MolerException is set instead of a result. Set to True to force completion regardless of occurrence count.

get_long_desc / get_short_desc

event.get_long_desc() -> str
event.get_short_desc() -> str
Both return a string of the form "Event '<module>.<ClassName>(id:...)'". Override in subclasses for more informative output.

enable_log_occurrence / disable_log_occurrence

event.enable_log_occurrence() -> None
event.disable_log_occurrence() -> None
Control whether each occurrence is logged at INFO level. Logging is enabled by default.

Abstract methods to implement

data_received (from ConnectionObserver)

event.data_received(data, recv_time) -> None
Parse incoming data. Call self.event_occurred(parsed_data) whenever a match is found.

pause

event.pause() -> None
Suspend processing without stopping. The connection continues to deliver data, but the event ignores it until resume() is called.

resume

event.resume() -> None
Resume processing after pause().

Key attributes

AttributeTypeDescription
callbackcallable | NoneThe registered callback (as a functools.partial).
callback_paramsdictParameters passed to the callback.
till_occurs_timesintTarget occurrence count. -1 = infinite.
event_namestrLower-case underscore form of the class name.

Usage examples

import re
from moler.event import Event

class ErrorLogEvent(Event):
    """Fires whenever an ERROR line appears on the connection."""

    def __init__(self, connection=None, runner=None):
        super().__init__(connection=connection, runner=runner)
        self._pattern = re.compile(r'ERROR:(.+)')
        self._paused = False

    def data_received(self, data, recv_time):
        if self._paused:
            return
        for line in data:
            match = self._pattern.search(line)
            if match:
                self.event_occurred({'message': match.group(1).strip(),
                                     'time': recv_time})

    def pause(self):
        self._paused = True

    def resume(self):
        self._paused = False
Use till_occurs_times when you need exactly N occurrences. The event sets its result to the list of all collected event_data values, which you can retrieve with await_done() or result().
Only one callback may be attached at a time. Calling add_event_occurred_callback() when one is already registered raises MolerException. Remove the existing callback with remove_event_occurred_callback() first.

Build docs developers (and LLMs) love