sources: port to use api.BaseAPI

Now that `api.BaseAPI` provides the basic scaffolding for API
servers, use that base class and remove the code duplication.
This commit is contained in:
Christian Kellner 2020-07-22 15:39:25 +02:00 committed by Tom Gundersen
parent b86b6a4bf8
commit 3ae056bf0f

View file

@ -1,20 +1,16 @@
import asyncio
import json
import subprocess
import threading
from . import api
from .util import jsoncomm
class SourcesServer:
class SourcesServer(api.BaseAPI):
def __init__(self, socket_address, libdir, options, cache, output):
self.socket_address = socket_address
super().__init__(socket_address)
self.libdir = libdir
self.cache = cache
self.output = output
self.options = options or {}
self.barrier = threading.Barrier(2)
self.event_loop = None
self.thread = None
def _run_source(self, source, checksums):
msg = {
@ -42,35 +38,6 @@ class SourcesServer:
reply = self._run_source(request["source"], request["checksums"])
server.send(reply, destination=addr)
def _run_event_loop(self):
with jsoncomm.Socket.new_server(self.socket_address) as server:
self.barrier.wait()
self.event_loop.add_reader(server, self._dispatch, server)
asyncio.set_event_loop(self.event_loop)
self.event_loop.run_forever()
self.event_loop.remove_reader(server)
def __enter__(self):
# We are not re-entrant, so complain if re-entered.
assert self.event_loop is None
self.event_loop = asyncio.new_event_loop()
self.thread = threading.Thread(target=self._run_event_loop)
self.barrier.reset()
self.thread.start()
self.barrier.wait()
return self
def __exit__(self, *args):
self.event_loop.call_soon_threadsafe(self.event_loop.stop)
self.thread.join()
self.event_loop.close()
self.thread = None
self.event_loop = None
def get(source, checksums, api_path="/run/osbuild/api/sources"):
with jsoncomm.Socket.new_client(api_path) as client: