-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader.py
More file actions
52 lines (42 loc) · 1.79 KB
/
Copy pathreader.py
File metadata and controls
52 lines (42 loc) · 1.79 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
import subprocess
import sys
import os
from typing import Optional, List
class JournalReader:
def __init__(self):
self._check_availability()
def _check_availability(self):
if not os.path.exists('/bin/systemctl') and not os.path.exists('/usr/bin/systemctl'):
raise RuntimeError("systemd is not available on this system")
def _is_journalctl_available(self) -> bool:
for path in ['/bin/journalctl', '/usr/bin/journalctl', '/usr/sbin/journalctl']:
if os.path.exists(path):
return True
result = subprocess.run(['which', 'journalctl'], capture_output=True)
return result.returncode == 0
def read_logs(self, boot: int = 0, service: Optional[str] = None) -> List[str]:
if not self._is_journalctl_available():
raise RuntimeError("journalctl is not available on this system")
cmd = ['journalctl', '-b', '-o', 'short-iso', '--no-pager']
if boot < 0:
cmd[1] = f"-b{boot}"
if service:
service_name = service if service.endswith('.service') else f"{service}.service"
cmd.extend(['-u', service_name])
cmd.extend(['-p', '0..3'])
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=30
)
if result.returncode != 0:
if 'no entries' in result.stderr.lower():
return []
raise RuntimeError(f"journalctl error: {result.stderr}")
return result.stdout.splitlines()
except subprocess.TimeoutExpired:
raise RuntimeError("journalctl timed out")
except Exception as e:
raise RuntimeError(f"Failed to execute journalctl: {str(e)}")