From 58e9211d719b2441471781feb3cd400a323e9759 Mon Sep 17 00:00:00 2001 From: Christian Kellner Date: Wed, 22 Jul 2020 16:23:34 +0200 Subject: [PATCH] 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. --- osbuild/api.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/osbuild/api.py b/osbuild/api.py index be29e8e9..99e43ab3 100644 --- a/osbuild/api.py +++ b/osbuild/api.py @@ -3,6 +3,7 @@ import asyncio import io import json import os +import sys import tempfile import threading from .util import jsoncomm @@ -131,3 +132,16 @@ class API(BaseAPI): if self._output_pipe: os.close(self._output_pipe) 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()