05. Monitor

A Monitor is an optional helper that uses commands and events on your back to query for the status of Tor and get notified by any change. This can be used for example on startup to ensure that Tor is ready to operate before we perform any other action.

Additionally it can be used to stop or cancel asyncio tasks when Tor is no longer able to perform in good conditions (this occurs on network issues for example).

examples/monitor.py
 1#!/usr/bin/env python
 2
 3import asyncio
 4import os
 5import sys
 6from aiostem import Controller, Monitor
 7
 8async def main():
 9    password = os.environ.get('AIOSTEM_PASS', 'password')
10    host = os.environ.get('AIOSTEM_HOST', 'localhost')
11    port = os.environ.get('AIOSTEM_PORT', 9051)
12
13    print(f'[>] Connecting to {host} on port {port}')
14    async with Controller.from_port(host, int(port)) as ctrl:
15        reply = await ctrl.authenticate(password)
16        reply.raise_for_status()
17
18        async with Monitor(ctrl) as monitor:
19            status = await monitor.wait_until_healthy()
20            print('[+] Controller is healthy!')
21            print(status)
22
23if __name__ == '__main__':
24    asyncio.run(main())

Running this code should print the following output:

$ python examples/monitor.py
[>] Connecting to localhost on port 9051
[+] Controller is healthy!
ControllerStatus(bootstrap=100, has_circuits=True, has_dir_info=True, net_liveness=True)