runtime.service
¶
runtime.service.broker
¶
Broker service handler.
- class runtime.service.broker.Broker(ctx, update_publisher, client, buffers, uids=<factory>, logger=<factory>)[source]¶
Bases:
runtime.remote.Handler
The coordinator between Runtime’s clients and Runtime’s other processes.
- Parameters
ctx (click.core.Context) – Command-line context.
update_publisher (runtime.remote.Client) – A client for broadcasting Smart Device parameter updates.
client (runtime.remote.Client) – A client for interprocess calls.
buffers (runtime.buffer.BufferStore) – A buffer manager.
- async get_option(option=None)[source]¶
Get a command-line option.
- Parameters
option (Optional[str]) – The option name. If not provided, all options are returned.
- Returns
If the option name was requested, a single option value. Otherwise, a mapping from all option names to their respective values.
- async lint()[source]¶
Lint student code to identify errors and suggest best practices.
- Returns
A list of warnings. See the Pylint Output documentation for details.
Note
The numerical score Pylint produces is not reported because Runtime’s API built-ins (
runtime.api
) are always flagged as undefined. There is no way to selectively exclude certain errors within a category from the score calculation. Perfectly written student code will always have a meaningless penalty.
- async set_option(options)[source]¶
Set a command-line option to be used when Runtime is next restarted.
Note
Command-line switches are not supported at this time.
- property button_params: list[runtime.buffer.Parameter]¶
Gamepad button parameters.
runtime.service.device
¶
Smart device management.
- exception runtime.service.device.DeviceError(message, /, **context)[source]¶
Bases:
runtime.exception.RuntimeBaseException
General device error.
- class runtime.service.device.EventObserver(devices=<factory>, context=<factory>)[source]¶
Bases:
runtime.service.device.SmartDeviceObserver
Detect Smart Devices using Linux’s udev.
- Parameters
devices (asyncio.queues.Queue) – A queue of batches of detected devices. The devices are batched to reduce expensive calls to
list_ports.comports()
.
- class runtime.service.device.PollingObserver(patterns=frozenset({'/dev/ttyACM*'}), interval=1, ports=<factory>)[source]¶
Bases:
runtime.service.device.SmartDeviceObserver
Detect Smart Devices by polling the filesystem.
This observer exists for portability on systems without udev.
- class runtime.service.device.SmartDeviceClient(reader, writer, buffer=<factory>, requests=<factory>, read_queue=<factory>, write_queue=<factory>, logger=<factory>)[source]¶
Bases:
runtime.service.device.SmartDevice
A Smart Device implementation from the upstream end.
- async discover(buffers, /, *, interval=1)[source]¶
Identify information about a newly connected device.
This method periodically pings the device to get a subscription response, which contains the current subscription and the UID. Once the UID is known, the device allocates a buffer.
- Parameters
buffers (runtime.buffer.BufferStore) – The buffer manager that will allocate the buffer.
interval (float) – The delay in seconds between pings.
- async read(params=None)[source]¶
Read some parameters from the device.
- Parameters
params (Optional[Collection[str]]) – The names of a collection of parameters to read. If not provided, this client reads all parameters.
- async subscribe(params=None, interval=None)[source]¶
Receive periodic updates for zero or more parameters.
- Parameters
- Raises
OverflowError – If interval cannot fit in an unsigned 16-bit integer.
- class runtime.service.device.SmartDeviceManager(buffers, observer=<factory>, devices=<factory>, poll_interval=0.04, discovery_timeout=10, logger=<factory>)[source]¶
Bases:
runtime.remote.Handler
Manage the lifecycle and operations of Smart Devices.
- Parameters
observer (runtime.service.device.SmartDeviceObserver) – An observer for detecting hotplugged Smart Devices.
buffers (runtime.buffer.BufferStore) – A buffer manager for opening/closing shared memory.
devices (dict[int, runtime.service.device.SmartDeviceClient]) – Map device UIDs to device instances.
Note
Although integer UIDs are used internally, UIDs are transported over the network as strings because the serialization protocol may not support 96-bit integers.
- async disable(uids=None)[source]¶
Disable one or more devices.
- Parameters
uids (Optional[Union[str, list[str]]]) – The UIDs of devices to disable. See
SmartDeviceManager.ping()
for an explanation of this argument’s type.
- async heartbeat(uid, heartbeat_id=None, timeout=1, block=True)[source]¶
Send heartbeat requests to a device.
- Parameters
uid (str) – The UID of the device to send the request to.
The remaining arguments are passed to
SmartDevice.heartbeat()
.
- async open_serial_devices(**options)[source]¶
Open serial ports and schedule their execution concurrently.
- Parameters
**options – Keyword arguments passed to
serial_asyncio.open_serial_connection()
.
- async open_virtual_devices(vsd_addr)[source]¶
Establish connections to Virtual Smart Devices forever.
- Parameters
vsd_addr (str) – The address to listen on.
- async read(uid, params=None)[source]¶
Read some parameters.
The parameter values are not returned from this method, since the Smart Device protocol is asynchronous. Instead, the updated parameters will be copied into the corresponding buffer.
- Parameters
uid (str) – The UID of the device to read parameters from.
The remaining arguments are passed to
SmartDevice.read()
.
- async run_device(reader, writer, port=None)[source]¶
Create and register a new Smart Device and block until the connection closes.
- Parameters
reader (asyncio.streams.StreamReader) – Stream reader.
writer (asyncio.streams.StreamWriter) – Stream writer.
port (Optional[pathlib.Path]) – The COM port path, if this is a serial connection. If not provided, this method assumes this device is virtual.
runtime.service.executor
¶
Student code execution.
- exception runtime.service.executor.ExecutionError(message, /, **context)[source]¶
Bases:
runtime.exception.RuntimeBaseException
General execution error.
- class runtime.service.executor.AsyncExecutor(loop=None, requests=None, max_actions=128, requests_size=128, running_actions=<factory>, configure_loop=<function AsyncExecutor.<lambda>>, logger=<factory>)[source]¶
Bases:
runtime.service.executor.Executor
,runtime.api.Actions
An executor that executes coroutine functions.
- Parameters
loop (Optional[asyncio.events.AbstractEventLoop]) – The event loop running the coroutine functions as tasks.
requests (Optional[asyncio.queues.Queue]) – An async queue of execution requests.
max_actions (int) – The maximum number of concurrently running tasks.
requests_size (int) – The size of the requests queue.
running_actions (dict[typing.Callable[..., typing.Awaitable[NoneType]], _asyncio.Task]) – Maps coroutine functions to their running task instances. For resource contention reasons, only one task instance may exist at a time per coroutine function. Once a task completes, its entry is removed from this mapping.
debug –
asyncio
debug flag.executor –
asyncio
executor for dispatching synchronous tasks.
- class runtime.service.executor.Dispatcher(buffers, student_code_name='studentcode', timeouts=<factory>, names=<factory>, sync_exec=<factory>, async_exec=<factory>, client=None, logger=<factory>)[source]¶
Bases:
runtime.remote.Handler
An RPC handler to forward execution requests to the executors.
- Parameters
timeouts (Mapping[Pattern[str], float]) – Maps function name patterns to a timeout duration (in seconds).
student_code – Student code module.
sync_exec (runtime.service.executor.SyncExecutor) – An synchronous executor for executing the
*_setup
and*_main
functions.async_exec (runtime.service.executor.AsyncExecutor) – An asynchronous executor for executing actions.
buffers (runtime.buffer.BufferStore) – Buffer manager.
- prepare_student_code_run(requests, enable_gamepads=True)[source]¶
Prepare to run student code.
Reload the student code module, then enqueue execution requests for the module’s functions.
- Parameters
requests (list[dict[str, typing.Any]]) – A list of keyword arguments to
ExecutionRequest
. However, thefunc
argument should be a string naming a function in the student code module. Also, iftimeout
is not present, this method matches each function name against patterns intimeouts
to find the timeout.
- class runtime.service.executor.ExecutionRequest(func=<function ExecutionRequest.<lambda>>, args=(), timeout=1, periodic=False, loop=None, future=None)[source]¶
Bases:
NamedTuple
A request for an
Executor
to execute a callable.- Parameters
func (Callable[[...], Optional[Awaitable[None]]]) – The callable. May or may be a coroutine function.
args (Sequence[Any]) – Positonal arguments to pass to
func
.timeout (float) – If the request is not periodic, the timeout is the maximum number of seconds the callable should run for. If the request is periodic, the timeout is the interval between invocations.
periodic (bool) – Whether the callable should be invoked once or repeatedly at a fixed rate.
- class runtime.service.executor.Executor[source]¶
Bases:
abc.ABC
Schedule and execute callables with timeouts.
- abstract execute_forever()[source]¶
Execute callables indefinitely (blocking) until
stop()
is called.
- abstract schedule(request)[source]¶
Schedule a callable for execution.
- Parameters
request (runtime.service.executor.ExecutionRequest) – The execution request.
- Raises
ExecutionError – If the callable was unable to be scheduled.
Note
This method should be thread-safe but is allowed to block. The order in which callables are registered may or may not be meaningful. They may be executed in the order in which they were registered, or they may execute concurrently.
- stop()[source]¶
Cancel all execution, then unblock
execute_forever()
.
- class runtime.service.executor.SyncExecutor(requests=<factory>, logger=<factory>)[source]¶
Bases:
runtime.service.executor.Executor
An executor that executes synchronous functions, using alarms for timeouts.
A synchronous executor may only run in the main thread because the main thread executes signal handlers. Synchronous handlers rely on the
SIGALRM
handler to raise an exception that will interrupt code that reaches a timeout.- Parameters
requests (queue.Queue[runtime.service.executor.ExecutionRequest]) – A synchronous queue of execution requests.
- execute(request)[source]¶
Execute a regular execution request.
- Parameters
request (runtime.service.executor.ExecutionRequest) – An execution request.