-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevbox_tui.py
More file actions
executable file
·570 lines (467 loc) · 20.3 KB
/
devbox_tui.py
File metadata and controls
executable file
·570 lines (467 loc) · 20.3 KB
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
#!/usr/bin/env python3
"""
devbox TUI — interactive terminal interface for devbox.
Run from the project root: python3 devbox_tui.py
"""
import os
import signal
import sys
import subprocess
# ── path setup ────────────────────────────────────────────────────────────────
_root = os.path.dirname(os.path.abspath(__file__))
sys.path[0:0] = [os.path.join(_root, 'lib')]
os.chdir(_root) # devbox.ini and devbox.py live here
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal, Vertical
from textual.screen import ModalScreen
from textual.widgets import Button, DataTable, Footer, Header, Input, Label
from textual.widgets import ListItem, ListView, RichLog, Static
from textual import on, work
from rich.text import Text
# ── safe config import ────────────────────────────────────────────────────────
# Fake argv so devbox_config skips the "image must exist" check on import.
_saved_argv = sys.argv[:]
sys.argv = ['devbox.py', 'image', 'create']
_cfg = None
_cfg_error: str = ''
try:
import devbox_config as _cfg
except SystemExit as _e:
_cfg_error = f'Configuration failed (exit {_e.code}) — edit devbox.ini and restart'
except Exception as _e:
_cfg_error = str(_e)
finally:
sys.argv = _saved_argv
# ── data helpers ──────────────────────────────────────────────────────────────
def _has_cfg() -> bool:
return _cfg is not None
def _node_rows() -> list[tuple[str, str, str, str]]:
"""Fresh (vmid, hostname, ip/mask, node) rows from the Proxmox API."""
if not _has_cfg():
return []
try:
rows = []
for vm in _cfg.prox.cluster.resources.get(type='vm'):
vid = int(vm.get('vmid'))
if _cfg.dev_id <= vid < (_cfg.dev_id + 10) and vid != _cfg.dev_id:
rows.append((
str(vid),
vm.get('name', ''),
f"{_cfg.vmip(vid)}/{_cfg.network_mask}",
vm.get('node', ''),
))
return sorted(rows, key=lambda r: int(r[0]))
except Exception:
return []
def _node_list() -> list[tuple[int, str, str]]:
"""Fresh (vmid, hostname, ip/mask) list for the node picker modal."""
if not _has_cfg():
return []
try:
result = []
for vm in _cfg.prox.cluster.resources.get(type='vm'):
vid = int(vm.get('vmid'))
if _cfg.dev_id <= vid < (_cfg.dev_id + 10) and vid != _cfg.dev_id:
result.append((vid, vm.get('name', ''), f"{_cfg.vmip(vid)}/{_cfg.network_mask}"))
return sorted(result)
except Exception:
return []
def _image_info() -> tuple[str, str]:
"""Return (description, storage_line) for the image panel."""
if not _has_cfg():
return ('', '')
try:
name = _cfg.devbox_img()
if not name:
return ('no image — run Image › Create', '')
tpl = _cfg.prox.nodes(_cfg.node).qemu(_cfg.dev_id).config.get()
desc = tpl.get('description', '')
return (desc, f"{name} ({_cfg.storage_type})")
except Exception:
return ('', '')
# ── modals ────────────────────────────────────────────────────────────────────
class NodePickerModal(ModalScreen):
"""Select an existing node by hostname."""
DEFAULT_CSS = """
NodePickerModal { align: center middle; }
#picker-box {
width: 54; max-height: 24;
border: thick $primary;
background: $surface;
padding: 1 2;
}
#picker-title { text-style: bold; margin-bottom: 1; }
ListView {
height: auto; max-height: 14;
border: solid $primary-darken-2;
}
#picker-cancel { margin-top: 1; width: 100%; }
"""
def __init__(self, title: str, nodes: list[tuple[int, str, str]]) -> None:
super().__init__()
# Avoid self._nodes: Textual's Widget uses _nodes internally to track
# child widgets, so naming our data attribute the same clobbers it and
# causes Textual to try to register our tuples as widgets.
self._modal_title = title
self._node_data = nodes
def compose(self) -> ComposeResult:
with Vertical(id="picker-box"):
yield Label(self._modal_title, id="picker-title")
if self._node_data:
yield ListView(
*[
ListItem(Label(f" {name} {ip}"), id=f"n-{vid}")
for vid, name, ip in self._node_data
],
id="node-list",
)
else:
yield Label("[dim]No nodes found[/dim]")
yield Button("Cancel", id="picker-cancel", variant="default")
@on(ListView.Selected)
def selected(self, event: ListView.Selected) -> None:
vid = int(event.item.id.split("-", 1)[1])
name = next(n for v, n, _ in self._node_data if v == vid)
self.dismiss(name)
@on(Button.Pressed, "#picker-cancel")
def cancel(self) -> None:
self.dismiss(None)
class CreateNodeModal(ModalScreen):
"""Enter a hostname for a new node."""
DEFAULT_CSS = """
CreateNodeModal { align: center middle; }
#create-box {
width: 54;
border: thick $success;
background: $surface;
padding: 1 2;
}
#create-title { text-style: bold; margin-bottom: 1; }
#create-input { margin-bottom: 1; }
#create-row { layout: horizontal; height: 3; }
#create-ok { width: 1fr; margin-right: 1; }
#create-cancel { width: 1fr; }
"""
def compose(self) -> ComposeResult:
with Vertical(id="create-box"):
yield Label("Create node — enter hostname:", id="create-title")
yield Input(placeholder="hostname", id="create-input")
with Horizontal(id="create-row"):
yield Button("Create", id="create-ok", variant="success")
yield Button("Cancel", id="create-cancel", variant="default")
def _submit(self) -> None:
val = self.query_one("#create-input", Input).value.strip()
self.dismiss(val or None)
@on(Button.Pressed, "#create-ok")
def ok(self) -> None: self._submit()
@on(Button.Pressed, "#create-cancel")
def cancel(self) -> None: self.dismiss(None)
@on(Input.Submitted)
def submitted(self) -> None: self._submit()
# ── main application ──────────────────────────────────────────────────────────
class DevboxTUI(App):
TITLE = "devbox"
SUB_TITLE = "Proxmox DevBox Manager"
CSS = """
/* ── global ── */
Screen { layout: vertical; }
/* ── main content row ── */
#main { layout: horizontal; height: 1fr; }
/* ── sidebar ── */
#sidebar {
width: 20;
height: 100%;
border-right: solid $primary-darken-2;
background: $panel;
padding: 0 1;
overflow-y: auto;
}
.sec {
text-style: bold;
color: $primary;
padding: 1 0 0 0;
height: 2;
}
.sep { color: $primary-darken-2; height: 1; }
Button { width: 100%; height: 3; margin: 0; }
/* ── right pane ── */
#right { width: 1fr; height: 100%; layout: vertical; }
/* ── top split: node table + image info ── */
#top-panels { layout: horizontal; height: 40%; }
#nodes-panel {
width: 2fr;
border: solid $primary-darken-2;
}
#nodes-panel-title {
background: $primary-darken-2;
color: $text;
padding: 0 1;
height: 1;
text-style: bold;
}
DataTable { height: 1fr; }
#image-panel {
width: 1fr;
border: solid $accent-darken-2;
}
#image-panel-title {
background: $accent-darken-2;
color: $text;
padding: 0 1;
height: 1;
text-style: bold;
}
#image-desc { padding: 1 1 0 1; }
#image-store { padding: 0 1; color: $text-muted; }
/* ── log panel ── */
#log-panel { border: solid $surface-lighten-2; height: 1fr; }
#log-panel-title {
background: $surface-lighten-1;
color: $text;
padding: 0 1;
height: 1;
text-style: bold;
}
RichLog { height: 1fr; padding: 0 1; }
/* ── status bar ── */
#statusbar {
height: 1;
background: $primary-darken-3;
padding: 0 1;
color: $text-muted;
}
"""
BINDINGS = [
Binding("r", "refresh", "Refresh"),
Binding("ctrl+l", "clear_log", "Clear log"),
Binding("q", "quit", "Quit"),
]
# ── layout ────────────────────────────────────────────────────────────────
def compose(self) -> ComposeResult:
yield Header()
with Horizontal(id="main"):
# sidebar
with Vertical(id="sidebar"):
yield Label("── Image ──", classes="sec")
yield Button("Create", id="img-create", variant="success")
yield Button("Info", id="img-info")
yield Button("Destroy", id="img-destroy", variant="error")
yield Label("── Nodes ──", classes="sec")
yield Button("Create", id="nd-create", variant="success")
yield Button("Info", id="nd-info")
yield Button("SSH", id="nd-ssh")
yield Button("Terminal", id="nd-terminal")
yield Button("Reboot", id="nd-reboot")
yield Button("Destroy", id="nd-destroy", variant="error")
yield Label("──────────", classes="sep")
yield Button("⟳ Refresh", id="btn-refresh", variant="primary")
# right pane
with Vertical(id="right"):
with Horizontal(id="top-panels"):
# node table
with Vertical(id="nodes-panel"):
yield Label(" Cluster Nodes", id="nodes-panel-title")
yield DataTable(id="nodes-table", cursor_type="row")
# image info
with Vertical(id="image-panel"):
yield Label(" Image", id="image-panel-title")
yield Label("", id="image-desc")
yield Label("", id="image-store")
# log
with Vertical(id="log-panel"):
yield Label(" Log", id="log-panel-title")
yield RichLog(id="log", highlight=True, markup=True, wrap=True)
yield Static("", id="statusbar")
yield Footer()
# ── lifecycle ─────────────────────────────────────────────────────────────
def on_mount(self) -> None:
t = self.query_one("#nodes-table", DataTable)
t.add_columns("VMID", "Hostname", "IP / Mask", "Node")
if not _has_cfg():
self._log(f"[bold red]Config error:[/] {_cfg_error}")
self._status("Config error — fix devbox.ini and restart", err=True)
else:
self._refresh_all()
# ── UI helpers ────────────────────────────────────────────────────────────
def _log(self, msg) -> None:
self.query_one("#log", RichLog).write(msg)
def _status(self, msg: str, err: bool = False) -> None:
colour = "red" if err else "green"
self.query_one("#statusbar", Static).update(f"[{colour}]{msg}[/]")
# ── actions ───────────────────────────────────────────────────────────────
def action_refresh(self) -> None:
if _has_cfg():
self._refresh_all()
def action_clear_log(self) -> None:
self.query_one("#log", RichLog).clear()
# ── background refresh ────────────────────────────────────────────────────
def _refresh_all(self) -> None:
self._refresh_table()
self._refresh_image()
@work(thread=True)
def _refresh_table(self) -> None:
self.call_from_thread(self._status, "Refreshing…")
rows = _node_rows()
def _apply():
t = self.query_one("#nodes-table", DataTable)
t.clear()
for row in rows:
t.add_row(*row)
n = len(rows)
self._status(f"Ready — {n} node{'s' if n != 1 else ''}")
self.call_from_thread(_apply)
@work(thread=True)
def _refresh_image(self) -> None:
desc, store = _image_info()
def _apply():
self.query_one("#image-desc", Label).update(desc or "[dim]no image[/dim]")
self.query_one("#image-store", Label).update(store or "")
self.call_from_thread(_apply)
# ── subprocess runner (non-interactive) ───────────────────────────────────
@work(thread=True)
def _run(self, args: list[str]) -> None:
"""Run devbox CLI as a subprocess and stream coloured output to the log."""
label = "devbox " + " ".join(args)
self.call_from_thread(self._log, f"\n[bold cyan]$ {label}[/]")
self.call_from_thread(self._status, f"Running: {label}")
cmd = [sys.executable, os.path.join(_root, 'devbox.py')] + args
env = {**os.environ, 'FORCE_COLOR': '1'}
try:
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
env=env,
cwd=_root,
)
# BUG FIX: never call query_one() from a worker thread.
# Use call_from_thread(self._log, ...) so the write happens on the
# main thread where widget access is safe.
for raw in proc.stdout:
self.call_from_thread(self._log, Text.from_ansi(raw.rstrip()))
proc.wait()
ok = proc.returncode == 0
self.call_from_thread(
self._status,
f"Done: {label}" if ok else f"Failed (rc={proc.returncode}): {label}",
not ok,
)
except Exception as e:
self.call_from_thread(self._log, f"[red]Error launching process: {e}[/]")
self.call_from_thread(self._status, "Process error", True)
# refresh status panels after any state-changing operation
if len(args) > 1 and args[1] in ('create', 'destroy'):
self.call_from_thread(self._refresh_all)
# ── interactive runner (SSH / terminal — suspends TUI) ────────────────────
@work(thread=True)
def _run_interactive(self, args: list[str]) -> None:
"""Suspend the TUI, hand the terminal back, then resume.
Handles abrupt SSH disconnects gracefully: the terminal is always
restored (Textual's suspend() context guarantees this even on
exception), and any error is surfaced in the log panel.
"""
cmd = [sys.executable, os.path.join(_root, 'devbox.py')] + args
label = " ".join(args)
try:
with self.suspend():
result = subprocess.run(cmd, cwd=_root)
rc = result.returncode
if rc == 0:
self.call_from_thread(self._log, f"[green]Session ended:[/] {label}")
else:
self.call_from_thread(
self._log,
f"[yellow]Session ended (rc={rc}):[/] {label} "
f"[dim](connection lost or remote exit)[/dim]",
)
except Exception as exc:
# Terminal is restored by suspend()'s __exit__ before we get here.
self.call_from_thread(
self._log, f"[red]Interactive session error ({label}):[/] {exc}"
)
self.call_from_thread(self._status, "Session error — terminal restored", True)
# ── button handlers ───────────────────────────────────────────────────────
# Simple commands: sync handler calls _run directly.
# Modal commands: sync handler starts a @work async flow so that
# push_screen_wait has the required worker context (Textual 0.53+).
@on(Button.Pressed, "#img-create")
def h_img_create(self) -> None:
self._run(['image', 'create'])
@on(Button.Pressed, "#img-info")
def h_img_info(self) -> None:
self._run(['image', 'info'])
@on(Button.Pressed, "#img-destroy")
def h_img_destroy(self) -> None:
self._run(['image', 'destroy'])
@on(Button.Pressed, "#nd-info")
def h_nd_info(self) -> None:
self._run(['nodes', 'info'])
# ── modal flows (each @on handler kicks off a @work async flow) ───────────
@on(Button.Pressed, "#nd-create")
def h_nd_create(self) -> None:
self._flow_create()
@work
async def _flow_create(self) -> None:
hostname = await self.push_screen_wait(CreateNodeModal())
if hostname:
self._run(['nodes', 'create', hostname])
@on(Button.Pressed, "#nd-ssh")
def h_nd_ssh(self) -> None:
self._flow_ssh()
@work
async def _flow_ssh(self) -> None:
nodes = _node_list()
if not nodes:
self._log("[yellow]No nodes available[/]")
return
hostname = await self.push_screen_wait(NodePickerModal("SSH to node", nodes))
if hostname:
self._run_interactive(['nodes', 'ssh', hostname])
@on(Button.Pressed, "#nd-terminal")
def h_nd_terminal(self) -> None:
self._flow_terminal()
@work
async def _flow_terminal(self) -> None:
nodes = _node_list()
if not nodes:
self._log("[yellow]No nodes available[/]")
return
hostname = await self.push_screen_wait(NodePickerModal("Open terminal on node", nodes))
if hostname:
self._run_interactive(['nodes', 'terminal', hostname])
@on(Button.Pressed, "#nd-reboot")
def h_nd_reboot(self) -> None:
self._flow_reboot()
@work
async def _flow_reboot(self) -> None:
nodes = _node_list()
if not nodes:
self._log("[yellow]No nodes available[/]")
return
hostname = await self.push_screen_wait(NodePickerModal("Reboot node", nodes))
if hostname:
self._run(['nodes', 'reboot', hostname])
@on(Button.Pressed, "#nd-destroy")
def h_nd_destroy(self) -> None:
self._flow_destroy()
@work
async def _flow_destroy(self) -> None:
nodes = _node_list()
if not nodes:
self._log("[yellow]No nodes available[/]")
return
hostname = await self.push_screen_wait(NodePickerModal("Destroy node", nodes))
if hostname:
self._run(['nodes', 'destroy', hostname])
@on(Button.Pressed, "#btn-refresh")
def h_refresh(self) -> None:
self.action_refresh()
# ── entry point ───────────────────────────────────────────────────────────────
if __name__ == '__main__':
# Ignore SIGHUP so the TUI survives outer SSH disconnects.
# The app can still be quit cleanly with 'q' or Ctrl+C.
signal.signal(signal.SIGHUP, signal.SIG_IGN)
DevboxTUI().run()