buildroot: ability to register api endpoints

Add a new `register_api` method that is meant to be used by clients
to register API end point providers, i.e. instances of `api.BaseAPI`.
When the context of the `BuildRoot` is enter, all providers are
activated, i.e. their context is entered. In case `regsiter_api` is
called with an already active context, the provider will immediately
be activated. In both cases their lifetime is thus bound to the
context of the `BuildRoot`. This also means that they are cleaned-up
with the `BuildRoot`, i.e. when its context is exited.
This commit is contained in:
Christian Kellner 2020-07-22 17:02:17 +02:00 committed by Tom Gundersen
parent 38e714f229
commit 03c5cfb37e

View file

@ -40,6 +40,7 @@ class BuildRoot(contextlib.AbstractContextManager):
self._vardir = var
self._libdir = libdir
self._runner = runner
self._apis = []
self.api = None
self.dev = None
self.var = None
@ -92,6 +93,10 @@ class BuildRoot(contextlib.AbstractContextManager):
self._mknod(self.dev, "tty", 0o666, 5, 0)
self._mknod(self.dev, "zero", 0o666, 1, 5)
# Prepare all registered API endpoints
for api in self._apis:
self._exitstack.enter_context(api)
self._exitstack = self._exitstack.pop_all()
return self
@ -100,6 +105,17 @@ class BuildRoot(contextlib.AbstractContextManager):
self._exitstack.close()
self._exitstack = None
def register_api(self, api: "BaseAPI"):
"""Register an API endpoint.
The context of the API endpoint will be bound to the context of
this `BuildRoot`.
"""
self._apis.append(api)
if self._exitstack:
self._exitstack.enter_context(api)
def run(self, argv, binds=None, readonly_binds=None):
"""Runs a command in the buildroot.