Matthias Nott
2026-02-21 68b89251bd42af5eea293b9302b78df0ed87a86f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import asyncio
import json
import os
from typing import AsyncGenerator
OPS_CLI = os.environ.get("OPS_CLI", "/opt/infrastructure/ops")
OFFSITE_PYTHON = os.environ.get("OFFSITE_PYTHON", "/opt/data/π/bin/python3")
OFFSITE_SCRIPT = os.environ.get("OFFSITE_SCRIPT", "/opt/data/scripts/offsite.py")
_DEFAULT_TIMEOUT = 300
_BACKUP_TIMEOUT = 3600
async def run_ops(args: list[str], timeout: int = _DEFAULT_TIMEOUT) -> dict:
    """
    Run the ops CLI with the given arguments and capture output.
    Returns {"success": bool, "output": str, "error": str}.
    """
    try:
        proc = await asyncio.create_subprocess_exec(
            OPS_CLI,
            *args,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        try:
            stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
        except asyncio.TimeoutError:
            proc.kill()
            await proc.communicate()
            return {
                "success": False,
                "output": "",
                "error": f"Command timed out after {timeout}s",
            }
        return {
            "success": proc.returncode == 0,
            "output": stdout.decode("utf-8", errors="replace"),
            "error": stderr.decode("utf-8", errors="replace"),
        }
    except FileNotFoundError:
        return {
            "success": False,
            "output": "",
            "error": f"ops CLI not found at {OPS_CLI}",
        }
    except Exception as exc:
        return {
            "success": False,
            "output": "",
            "error": str(exc),
        }
async def run_ops_json(args: list[str], timeout: int = _DEFAULT_TIMEOUT) -> dict:
    """
    Run the ops CLI with --json appended and return the parsed JSON output.
    Returns {"success": bool, "data": ..., "error": str}.
    """
    result = await run_ops(args + ["--json"], timeout=timeout)
    if not result["success"]:
        return {"success": False, "data": None, "error": result["error"] or result["output"]}
    try:
        data = json.loads(result["output"])
        return {"success": True, "data": data, "error": ""}
    except json.JSONDecodeError as exc:
        return {
            "success": False,
            "data": None,
            "error": f"Failed to parse JSON output: {exc}\nRaw output: {result['output'][:500]}",
        }
async def stream_ops(args: list[str], timeout: int = _DEFAULT_TIMEOUT) -> AsyncGenerator[str, None]:
    """
    Async generator that yields lines of stdout from the ops CLI.
    Also yields stderr lines prefixed with '[stderr] '.
    """
    try:
        proc = await asyncio.create_subprocess_exec(
            OPS_CLI,
            *args,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
    except FileNotFoundError:
        yield f"[error] ops CLI not found at {OPS_CLI}"
        return
    except Exception as exc:
        yield f"[error] Failed to start process: {exc}"
        return
    async def _read_stream(stream: asyncio.StreamReader, prefix: str = "") -> AsyncGenerator[str, None]:
        while True:
            try:
                line = await asyncio.wait_for(stream.readline(), timeout=timeout)
            except asyncio.TimeoutError:
                yield f"{prefix}[timeout] Command exceeded {timeout}s"
                break
            if not line:
                break
            yield prefix + line.decode("utf-8", errors="replace").rstrip("\n")
    # Interleave stdout and stderr
    stdout_gen = _read_stream(proc.stdout)
    stderr_gen = _read_stream(proc.stderr, prefix="[stderr] ")
    stdout_done = False
    stderr_done = False
    stdout_iter = stdout_gen.__aiter__()
    stderr_iter = stderr_gen.__aiter__()
    pending_stdout: asyncio.Task | None = None
    pending_stderr: asyncio.Task | None = None
    async def _next(it):
        try:
            return await it.__anext__()
        except StopAsyncIteration:
            return None
    pending_stdout = asyncio.create_task(_next(stdout_iter))
    pending_stderr = asyncio.create_task(_next(stderr_iter))
    while not (stdout_done and stderr_done):
        done, _ = await asyncio.wait(
            [t for t in [pending_stdout, pending_stderr] if t is not None],
            return_when=asyncio.FIRST_COMPLETED,
        )
        for task in done:
            val = task.result()
            if task is pending_stdout:
                if val is None:
                    stdout_done = True
                    pending_stdout = None
                else:
                    yield val
                    pending_stdout = asyncio.create_task(_next(stdout_iter))
            elif task is pending_stderr:
                if val is None:
                    stderr_done = True
                    pending_stderr = None
                else:
                    yield val
                    pending_stderr = asyncio.create_task(_next(stderr_iter))
    await proc.wait()
async def run_command(
    args: list[str], timeout: int = _DEFAULT_TIMEOUT
) -> dict:
    """
    Generic command runner (non-ops). Accepts a full argv list.
    Returns {"success": bool, "output": str, "error": str}.
    """
    try:
        proc = await asyncio.create_subprocess_exec(
            *args,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        try:
            stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
        except asyncio.TimeoutError:
            proc.kill()
            await proc.communicate()
            return {
                "success": False,
                "output": "",
                "error": f"Command timed out after {timeout}s",
            }
        return {
            "success": proc.returncode == 0,
            "output": stdout.decode("utf-8", errors="replace"),
            "error": stderr.decode("utf-8", errors="replace"),
        }
    except FileNotFoundError as exc:
        return {"success": False, "output": "", "error": f"Executable not found: {exc}"}
    except Exception as exc:
        return {"success": False, "output": "", "error": str(exc)}
async def stream_command(
    args: list[str], timeout: int = _DEFAULT_TIMEOUT
) -> AsyncGenerator[str, None]:
    """
    Async generator that yields lines of stdout for an arbitrary command.
    """
    try:
        proc = await asyncio.create_subprocess_exec(
            *args,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
    except FileNotFoundError as exc:
        yield f"[error] Executable not found: {exc}"
        return
    except Exception as exc:
        yield f"[error] {exc}"
        return
    while True:
        try:
            line = await asyncio.wait_for(proc.stdout.readline(), timeout=timeout)
        except asyncio.TimeoutError:
            yield f"[timeout] Command exceeded {timeout}s"
            proc.kill()
            break
        if not line:
            break
        yield line.decode("utf-8", errors="replace").rstrip("\n")
    # Flush stderr as trailing info
    stderr_data = await proc.stderr.read()
    if stderr_data:
        for ln in stderr_data.decode("utf-8", errors="replace").splitlines():
            yield f"[stderr] {ln}"
    await proc.wait()