api: implement canonical setup_stdio method

The `api.API` provides a `setup-stdio` method, that is meant to
be used by clients to replace their stdio with the supplied fds
from the server. Provide a canonical `api.setup_stdio` method
that will do exactly that.
This commit is contained in:
Christian Kellner 2020-07-22 16:23:34 +02:00 committed by Tom Gundersen
parent 9edc2b0362
commit 58e9211d71

View file

@ -3,6 +3,7 @@ import asyncio
import io import io
import json import json
import os import os
import sys
import tempfile import tempfile
import threading import threading
from .util import jsoncomm from .util import jsoncomm
@ -131,3 +132,16 @@ class API(BaseAPI):
if self._output_pipe: if self._output_pipe:
os.close(self._output_pipe) os.close(self._output_pipe)
self._output_pipe = None self._output_pipe = None
def setup_stdio(path="/run/osbuild/api/osbuild"):
"""Replace standard i/o with the ones provided by the API"""
with jsoncomm.Socket.new_client(path) as client:
req = {"method": "setup-stdio"}
client.send(req)
msg, fds, _ = client.recv()
for sio in ["stdin", "stdout", "stderr"]:
target = getattr(sys, sio)
source = fds[msg[sio]]
os.dup2(source, target.fileno())
fds.close()