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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
|
#!/usr/bin/env python3
"""
umbrella-bot: Matrix bot client for the umbrella server manager.
Connects to the umbrella Unix socket and bridges commands from a Matrix
room to umbrella units. Requires matrix-nio with encryption support.
Dependencies:
pip install matrix-nio[e2e] aiofiles
Setup:
1. Create /etc/umbrella/bot.conf (see bot.conf.example)
2. Run once with --setup to perform initial login and key verification
3. Run normally or via systemd
"""
import asyncio
import json
import os
import re
import signal
import socket
import struct
import sys
import logging
import argparse
from pathlib import Path
from typing import Optional
from nio import (
AsyncClient,
AsyncClientConfig,
LoginResponse,
MatrixRoom,
RoomMessageText,
SyncResponse,
crypto,
)
from nio.store import SqliteStore
# ── Logging ───────────────────────────────────────────────────────────────────
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger("umbrella-bot")
# ── Config ────────────────────────────────────────────────────────────────────
DEFAULT_CONF = "/etc/umbrella/bot.conf"
DEFAULT_STORE = "/etc/umbrella/bot-store"
SOCK_PATH = "/run/umbrella/umbrella.sock"
PROTO_MAX = 65536
HELP_TEXT = """\
Umbrella bot commands:
!status <unit> — Show unit status
!cmd <unit> <command> — Send a console command
!restart <unit> — Restart the unit's systemd service
!update <unit> — Run the update action
!action <unit> <action> — Run a named action
!attach <unit> — Stream live log output to this room
!detach <unit> — Stop streaming log output
!units — List all units
!help — Show this message
"""
# ── Umbrella socket client ────────────────────────────────────────────────────
class UmbrellaClient:
"""
Synchronous umbrella socket client.
We use a plain blocking socket here since commands are short-lived
and we don't need async for the request/response pattern.
For attach (streaming), we use a separate async wrapper.
"""
def __init__(self, sock_path: str = SOCK_PATH):
self.sock_path = sock_path
def _connect(self) -> socket.socket:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(10)
try:
s.connect(self.sock_path)
except FileNotFoundError:
raise RuntimeError(f"Umbrella socket not found: {self.sock_path} "
f"(is umbrelld running?)")
except ConnectionRefusedError:
raise RuntimeError("Umbrella daemon is not running")
return s
def _send(self, s: socket.socket, msg: dict) -> None:
data = json.dumps(msg).encode()
header = struct.pack(">I", len(data))
s.sendall(header + data)
def _recv(self, s: socket.socket) -> dict:
header = b""
while len(header) < 4:
chunk = s.recv(4 - len(header))
if not chunk:
raise RuntimeError("Connection closed by umbrella daemon")
header += chunk
length = struct.unpack(">I", header)[0]
if length > PROTO_MAX:
raise RuntimeError(f"Message too large: {length}")
data = b""
while len(data) < length:
chunk = s.recv(length - len(data))
if not chunk:
raise RuntimeError("Connection closed mid-message")
data += chunk
return json.loads(data.decode())
def command(self, msg: dict) -> dict:
"""Send a command and return the response."""
s = self._connect()
try:
self._send(s, msg)
return self._recv(s)
finally:
s.close()
def list_units(self) -> list:
resp = self.command({"cmd": "list"})
return resp.get("units", [])
def status(self, unit: str) -> dict:
return self.command({"cmd": "status", "unit": unit})
def send_input(self, unit: str, data: str) -> dict:
return self.command({"cmd": "input", "unit": unit,
"data": data + "\n"})
def run_action(self, unit: str, action: str) -> dict:
return self.command({"cmd": "action", "unit": unit, "action": action})
# ── Attach session: streams output from umbrella to a Matrix room ─────────────
class AttachSession:
"""
Maintains a persistent connection to umbrella for a specific unit,
forwarding live output to a Matrix room.
"""
def __init__(self, unit: str, room_id: str,
matrix_client: "AsyncClient",
sock_path: str = SOCK_PATH):
self.unit = unit
self.room_id = room_id
self.matrix_client = matrix_client
self.sock_path = sock_path
self._task: Optional[asyncio.Task] = None
self._sock: Optional[socket.socket] = None
async def start(self):
if self._task and not self._task.done():
return # already running
self._task = asyncio.create_task(self._stream())
async def stop(self):
if self._task:
self._task.cancel()
try:
await self._task
except asyncio.CancelledError:
pass
if self._sock:
try:
self._sock.close()
except Exception:
pass
self._sock = None
async def _stream(self):
loop = asyncio.get_event_loop()
def connect_and_attach():
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(10)
s.connect(self.sock_path)
# Send attach command
msg = json.dumps({"cmd": "attach", "unit": self.unit}).encode()
s.sendall(struct.pack(">I", len(msg)) + msg)
# Read ok response
hdr = b""
while len(hdr) < 4:
hdr += s.recv(4 - len(hdr))
length = struct.unpack(">I", hdr)[0]
resp_data = b""
while len(resp_data) < length:
resp_data += s.recv(length - len(resp_data))
s.settimeout(None) # non-blocking from here
s.setblocking(False)
return s
try:
self._sock = await loop.run_in_executor(None, connect_and_attach)
except Exception as e:
log.error(f"attach: failed to connect for {self.unit}: {e}")
return
buf = b""
log.info(f"attach: streaming {self.unit} to room {self.room_id}")
try:
while True:
# Read available data from socket
try:
chunk = await loop.run_in_executor(
None, lambda: self._recv_one_nonblock()
)
if chunk is None:
await asyncio.sleep(0.05)
continue
if chunk == {}:
break # disconnected
except asyncio.CancelledError:
raise
except Exception as e:
log.error(f"attach: read error for {self.unit}: {e}")
break
if chunk.get("type") == "output":
data = chunk.get("data", "")
history = chunk.get("history", False)
if data and not history:
# Send to Matrix room, wrapped in code block
await self.matrix_client.room_send(
self.room_id,
"m.room.message",
{
"msgtype": "m.text",
"body": f"```\n{data.rstrip()}\n```",
"format": "org.matrix.custom.html",
"formatted_body": f"<pre><code>{data.rstrip()}</code></pre>",
}
)
except asyncio.CancelledError:
pass
finally:
if self._sock:
# Send detach
try:
msg = json.dumps({"cmd": "detach"}).encode()
self._sock.setblocking(True)
self._sock.sendall(struct.pack(">I", len(msg)) + msg)
except Exception:
pass
self._sock.close()
self._sock = None
def _recv_one_nonblock(self) -> Optional[dict]:
"""Try to read one message from the non-blocking socket. Returns None if no data yet."""
try:
hdr = self._sock.recv(4)
if not hdr:
return {} # disconnected
if len(hdr) < 4:
return None
length = struct.unpack(">I", hdr)[0]
data = b""
self._sock.setblocking(True)
while len(data) < length:
chunk = self._sock.recv(length - len(data))
if not chunk:
return {}
data += chunk
self._sock.setblocking(False)
return json.loads(data.decode())
except BlockingIOError:
return None
# ── Power level check ─────────────────────────────────────────────────────────
async def get_user_power_level(client: AsyncClient,
room_id: str, user_id: str) -> int:
"""
Fetch the power level for a user in a room.
Returns 0 if the user is not found or on error.
"""
try:
resp = await client.room_get_state_event(
room_id, "m.room.power_levels", ""
)
if hasattr(resp, "content"):
users = resp.content.get("users", {})
default = resp.content.get("users_default", 0)
return users.get(user_id, default)
except Exception as e:
log.warning(f"Could not get power level for {user_id}: {e}")
return 0
# ── Command dispatch ──────────────────────────────────────────────────────────
async def handle_command(
client: AsyncClient,
umbrella: UmbrellaClient,
attach_sessions: dict,
room: MatrixRoom,
sender: str,
text: str,
config: dict,
) -> Optional[str]:
"""
Parse and dispatch a bot command. Returns a reply string or None.
"""
parts = text.strip().split(None, 3)
if not parts:
return None
cmd = parts[0].lower()
# Check power level
power = await get_user_power_level(client, room.room_id, sender)
if power < 50:
return f"❌ Permission denied. Requires power level ≥ 50 (you have {power})."
try:
if cmd == "!help":
return HELP_TEXT
elif cmd == "!units":
units = umbrella.list_units()
if not units:
return "No units loaded."
lines = ["**Units:**"]
for u in units:
lines.append(f" `{u['name']}` — {u['display']} [{u['state']}]")
return "\n".join(lines)
elif cmd == "!status":
if len(parts) < 2:
return "Usage: `!status <unit>`"
unit = parts[1]
resp = umbrella.status(unit)
if resp.get("type") == "error":
return f"❌ {resp['message']}"
return (
f"**{resp.get('display', unit)}**\n"
f"State: `{resp.get('state', 'unknown')}`"
)
elif cmd == "!cmd":
if len(parts) < 3:
return "Usage: `!cmd <unit> <command>`"
unit = parts[1]
command = " ".join(parts[2:])
resp = umbrella.send_input(unit, command)
if resp.get("type") == "error":
return f"❌ {resp['message']}"
return f"✓ Sent: `{command}`"
elif cmd == "!restart":
if len(parts) < 2:
return "Usage: `!restart <unit>`"
unit = parts[1]
resp = umbrella.run_action(unit, "restart")
if resp.get("type") == "error":
return f"❌ {resp['message']}"
return f"✓ Restart dispatched for `{unit}`"
elif cmd == "!update":
if len(parts) < 2:
return "Usage: `!update <unit>`"
unit = parts[1]
resp = umbrella.run_action(unit, "update")
if resp.get("type") == "error":
return f"❌ {resp['message']}"
return f"✓ Update dispatched for `{unit}`"
elif cmd == "!action":
if len(parts) < 3:
return "Usage: `!action <unit> <action>`"
unit = parts[1]
action = parts[2]
resp = umbrella.run_action(unit, action)
if resp.get("type") == "error":
return f"❌ {resp['message']}"
return f"✓ Action `{action}` dispatched for `{unit}`"
elif cmd == "!attach":
if len(parts) < 2:
return "Usage: `!attach <unit>`"
unit = parts[1]
key = (room.room_id, unit)
if key in attach_sessions:
return f"Already streaming `{unit}` to this room."
session = AttachSession(unit, room.room_id, client)
attach_sessions[key] = session
await session.start()
return f"📡 Streaming `{unit}` output to this room. Use `!detach {unit}` to stop."
elif cmd == "!detach":
if len(parts) < 2:
return "Usage: `!detach <unit>`"
unit = parts[1]
key = (room.room_id, unit)
if key not in attach_sessions:
return f"`{unit}` is not being streamed to this room."
await attach_sessions[key].stop()
del attach_sessions[key]
return f"⏹ Stopped streaming `{unit}`."
except RuntimeError as e:
return f"❌ Umbrella error: {e}"
except Exception as e:
log.exception(f"Command error: {e}")
return f"❌ Internal error: {e}"
return None
# ── Bot core ──────────────────────────────────────────────────────────────────
async def run_bot(config: dict):
store_path = config.get("store_path", DEFAULT_STORE)
os.makedirs(store_path, exist_ok=True)
client_config = AsyncClientConfig(
max_limit_exceeded=0,
max_timeouts=0,
store_sync_tokens=True,
encryption_enabled=True,
)
client = AsyncClient(
homeserver=config["homeserver"],
user=config["user_id"],
device_id=config.get("device_id", "UMBRELLA_BOT"),
store_path=store_path,
config=client_config,
)
umbrella = UmbrellaClient(config.get("socket_path", SOCK_PATH))
attach_sessions = {}
room_id = config["room_id"]
# Login
log.info(f"Logging in as {config['user_id']}...")
resp = await client.login(
password=config["password"],
device_name="umbrella-bot",
)
if not isinstance(resp, LoginResponse):
log.error(f"Login failed: {resp}")
return
log.info(f"Logged in. Device ID: {client.device_id}")
# Load encryption keys
if client.should_upload_keys:
await client.keys_upload()
await client.keys_query()
# Message callback
async def on_message(room: MatrixRoom, event: RoomMessageText):
# Only handle messages in our configured room
if room.room_id != room_id:
return
# Ignore our own messages
if event.sender == config["user_id"]:
return
# Only handle messages that start with !
body = event.body.strip()
if not body.startswith("!"):
return
log.info(f"Command from {event.sender}: {body}")
reply = await handle_command(
client, umbrella, attach_sessions,
room, event.sender, body, config
)
if reply:
await client.room_send(
room_id,
"m.room.message",
{
"msgtype": "m.text",
"body": reply,
"format": "org.matrix.custom.html",
"formatted_body": reply.replace("\n", "<br>"),
}
)
client.add_event_callback(on_message, RoomMessageText)
# Graceful shutdown
loop = asyncio.get_event_loop()
stop_event = asyncio.Event()
def _signal_handler():
log.info("Shutting down...")
stop_event.set()
loop.add_signal_handler(signal.SIGTERM, _signal_handler)
loop.add_signal_handler(signal.SIGINT, _signal_handler)
log.info(f"Syncing, watching room {room_id}")
# Initial sync
await client.sync(timeout=10000)
await client.keys_query()
# Main sync loop
async def sync_loop():
while not stop_event.is_set():
resp = await client.sync(timeout=30000, full_state=False)
if isinstance(resp, SyncResponse):
# Upload any new keys
if client.should_upload_keys:
await client.keys_upload()
sync_task = asyncio.create_task(sync_loop())
await stop_event.wait()
sync_task.cancel()
try:
await sync_task
except asyncio.CancelledError:
pass
# Stop all attach sessions
for session in attach_sessions.values():
await session.stop()
await client.close()
log.info("Bot stopped.")
# ── Setup mode ────────────────────────────────────────────────────────────────
async def run_setup(config: dict):
"""
First-run setup: login, generate device keys, print device ID.
Run this once before starting the bot normally.
"""
store_path = config.get("store_path", DEFAULT_STORE)
os.makedirs(store_path, exist_ok=True)
client = AsyncClient(
homeserver=config["homeserver"],
user=config["user_id"],
device_id=config.get("device_id", "UMBRELLA_BOT"),
store_path=store_path,
config=AsyncClientConfig(encryption_enabled=True),
)
print(f"Logging in as {config['user_id']}...")
resp = await client.login(
password=config["password"],
device_name="umbrella-bot",
)
if not isinstance(resp, LoginResponse):
print(f"Login failed: {resp}")
return
print(f"Logged in successfully.")
print(f"Device ID: {client.device_id}")
print(f"Add this to your bot.conf: device_id = {client.device_id}")
if client.should_upload_keys:
await client.keys_upload()
print("Encryption keys uploaded.")
print("\nSetup complete. You can now run the bot normally.")
print("Note: you may need to verify this device from another session")
print("if your room requires verified devices.")
await client.close()
# ── Config loading ────────────────────────────────────────────────────────────
def load_config(path: str) -> dict:
config = {}
with open(path) as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" not in line:
continue
key, _, value = line.partition("=")
config[key.strip()] = value.strip()
required = ["homeserver", "user_id", "password", "room_id"]
for key in required:
if key not in config:
raise ValueError(f"Missing required config key: {key}")
return config
# ── Entry point ───────────────────────────────────────────────────────────────
def main():
parser = argparse.ArgumentParser(description="Umbrella Matrix bot")
parser.add_argument("-c", "--config", default=DEFAULT_CONF,
help=f"Config file (default: {DEFAULT_CONF})")
parser.add_argument("--setup", action="store_true",
help="Run first-time setup and exit")
args = parser.parse_args()
try:
config = load_config(args.config)
except FileNotFoundError:
print(f"Config file not found: {args.config}")
print(f"Create it based on bot.conf.example")
sys.exit(1)
except ValueError as e:
print(f"Config error: {e}")
sys.exit(1)
if args.setup:
asyncio.run(run_setup(config))
else:
asyncio.run(run_bot(config))
if __name__ == "__main__":
main()
|