From 03c5cfb37e5dc9b67425cd865e12b803ca53965d Mon Sep 17 00:00:00 2001 From: Christian Kellner Date: Wed, 22 Jul 2020 17:02:17 +0200 Subject: [PATCH] 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. --- osbuild/buildroot.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/osbuild/buildroot.py b/osbuild/buildroot.py index decf9906..35a839c1 100644 --- a/osbuild/buildroot.py +++ b/osbuild/buildroot.py @@ -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.