myths 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. myths-0.1.0/PKG-INFO +60 -0
  2. myths-0.1.0/README.md +53 -0
  3. myths-0.1.0/myths/__init__.py +5 -0
  4. myths-0.1.0/myths/catalog/connectors/chip/jtag.py +87 -0
  5. myths-0.1.0/myths/catalog/connectors/chip/uart.py +54 -0
  6. myths-0.1.0/myths/catalog/connectors/measurement/scpi.py +54 -0
  7. myths-0.1.0/myths/catalog/connectors/remote/snmp.py +15 -0
  8. myths-0.1.0/myths/catalog/connectors/remote/ssh.py +74 -0
  9. myths-0.1.0/myths/catalog/connectors/system/os_inventory.py +86 -0
  10. myths-0.1.0/myths/connectors/chip/jtag.py +87 -0
  11. myths-0.1.0/myths/connectors/remote/ssh.py +26 -0
  12. myths-0.1.0/myths/connectors/system/os-inventory.py +86 -0
  13. myths-0.1.0/myths/modules/jtag-scan/main.py +9 -0
  14. myths-0.1.0/myths/modules/os-inventory/main.py +3 -0
  15. myths-0.1.0/myths/modules/silicon-cpu-fingerprinter/main.py +19 -0
  16. myths-0.1.0/myths/modules/system-info/main.py +7 -0
  17. myths-0.1.0/myths/modules/uart-read/main.py +9 -0
  18. myths-0.1.0/myths.egg-info/PKG-INFO +60 -0
  19. myths-0.1.0/myths.egg-info/SOURCES.txt +29 -0
  20. myths-0.1.0/myths.egg-info/dependency_links.txt +1 -0
  21. myths-0.1.0/myths.egg-info/entry_points.txt +2 -0
  22. myths-0.1.0/myths.egg-info/top_level.txt +2 -0
  23. myths-0.1.0/myths_core/__init__.py +6 -0
  24. myths-0.1.0/myths_core/app.py +1161 -0
  25. myths-0.1.0/myths_core/cli.py +212 -0
  26. myths-0.1.0/myths_core/dashboard.py +186 -0
  27. myths-0.1.0/myths_core/runtime.py +107 -0
  28. myths-0.1.0/pyproject.toml +18 -0
  29. myths-0.1.0/setup.cfg +4 -0
  30. myths-0.1.0/tests/test_dashboard_components.py +208 -0
  31. myths-0.1.0/tests/test_direct_connector_imports.py +63 -0
myths-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: myths
3
+ Version: 0.1.0
4
+ Summary: MYTHS Core Framework for Hardware & System Connectors
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+
8
+ # MYTHS Framework (`myths`)
9
+
10
+ **MYTHS** is a lightweight, fast, and modular Python framework for hardware and system connectors.
11
+
12
+ ## 🚀 Quick Start
13
+
14
+ ### Installation from PyPI
15
+ ```bash
16
+ pip install myths
17
+ ```
18
+
19
+ ### Install Connectors
20
+ ```bash
21
+ myths connector install jtag
22
+ myths connector install ssh
23
+ myths connector install uart
24
+ ```
25
+
26
+ ### Usage in Python Scripts
27
+ Create a script (e.g. `script.py`):
28
+
29
+ ```python
30
+ import jtag
31
+ import ssh
32
+
33
+ jtag.connect(target="192.168.1.100")
34
+ jtag.halt_cpu()
35
+ val = jtag.read_register("R0")
36
+ print(f"R0: {val}")
37
+ jtag.resume_cpu()
38
+ jtag.disconnect()
39
+
40
+ ssh.connect(target="192.168.1.100")
41
+ ssh.run(f"echo 'Register R0={val}' >> /var/log/myths.log")
42
+ ssh.disconnect()
43
+ ```
44
+
45
+ ### Run via CLI
46
+ ```bash
47
+ myths run script.py
48
+ ```
49
+
50
+ ## 🛠️ CLI Commands
51
+
52
+ - `myths list`: List all available modules and connector drivers.
53
+ - `myths status`: Show active MYTHS workspace status.
54
+ - `myths info <name>`: Inspect details of a connector or module.
55
+ - `myths connector install <name>`: Install a connector driver.
56
+ - `myths run <script_or_module>`: Run a task script or module.
57
+ - `myths serve`: Start the local HTTP API and web dashboard.
58
+
59
+ ## 📄 License
60
+ MIT License
myths-0.1.0/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # MYTHS Framework (`myths`)
2
+
3
+ **MYTHS** is a lightweight, fast, and modular Python framework for hardware and system connectors.
4
+
5
+ ## 🚀 Quick Start
6
+
7
+ ### Installation from PyPI
8
+ ```bash
9
+ pip install myths
10
+ ```
11
+
12
+ ### Install Connectors
13
+ ```bash
14
+ myths connector install jtag
15
+ myths connector install ssh
16
+ myths connector install uart
17
+ ```
18
+
19
+ ### Usage in Python Scripts
20
+ Create a script (e.g. `script.py`):
21
+
22
+ ```python
23
+ import jtag
24
+ import ssh
25
+
26
+ jtag.connect(target="192.168.1.100")
27
+ jtag.halt_cpu()
28
+ val = jtag.read_register("R0")
29
+ print(f"R0: {val}")
30
+ jtag.resume_cpu()
31
+ jtag.disconnect()
32
+
33
+ ssh.connect(target="192.168.1.100")
34
+ ssh.run(f"echo 'Register R0={val}' >> /var/log/myths.log")
35
+ ssh.disconnect()
36
+ ```
37
+
38
+ ### Run via CLI
39
+ ```bash
40
+ myths run script.py
41
+ ```
42
+
43
+ ## 🛠️ CLI Commands
44
+
45
+ - `myths list`: List all available modules and connector drivers.
46
+ - `myths status`: Show active MYTHS workspace status.
47
+ - `myths info <name>`: Inspect details of a connector or module.
48
+ - `myths connector install <name>`: Install a connector driver.
49
+ - `myths run <script_or_module>`: Run a task script or module.
50
+ - `myths serve`: Start the local HTTP API and web dashboard.
51
+
52
+ ## 📄 License
53
+ MIT License
@@ -0,0 +1,5 @@
1
+ """MYTHS connectors and catalog package."""
2
+
3
+ from myths_core import app
4
+
5
+ app.ensure_layout()
@@ -0,0 +1,87 @@
1
+ class JTAG:
2
+ """Dynamic JTAG driver connector."""
3
+
4
+ def __init__(self, target: str | None = None, interface: str | None = None, config: str | None = None):
5
+ self.target = target
6
+ self.interface = interface
7
+ self.config = config
8
+ self.connected = False
9
+
10
+ def connect(self, target: str | None = None, interface: str | None = None, config: str | None = None) -> bool:
11
+ if target:
12
+ self.target = target
13
+ if interface:
14
+ self.interface = interface
15
+ if config:
16
+ self.config = config
17
+ self.connected = True
18
+ return True
19
+
20
+ def disconnect(self) -> bool:
21
+ self.connected = False
22
+ return True
23
+
24
+ def read_register(self, reg_name: str) -> str:
25
+ return f"Read register '{reg_name}' on target '{self.target or 'unspecified'}'"
26
+
27
+ def write_register(self, reg_name: str, value) -> str:
28
+ return f"Written '{value}' to register '{reg_name}' on target '{self.target or 'unspecified'}'"
29
+
30
+ def halt_cpu(self) -> str:
31
+ return f"CPU halted on target '{self.target or 'unspecified'}'"
32
+
33
+ def resume_cpu(self) -> str:
34
+ return f"CPU resumed on target '{self.target or 'unspecified'}'"
35
+
36
+
37
+ _active_jtag = JTAG()
38
+
39
+
40
+ def connect(target: str | None = None, interface: str | None = None, config: str | None = None):
41
+ _active_jtag.connect(target, interface, config)
42
+ return _active_jtag
43
+
44
+
45
+ def disconnect():
46
+ return _active_jtag.disconnect()
47
+
48
+
49
+ def read_register(reg_name: str, target: str | None = None):
50
+ if target:
51
+ _active_jtag.target = target
52
+ return _active_jtag.read_register(reg_name)
53
+
54
+
55
+ def write_register(reg_name: str, value, target: str | None = None):
56
+ if target:
57
+ _active_jtag.target = target
58
+ return _active_jtag.write_register(reg_name, value)
59
+
60
+
61
+ def halt_cpu(target: str | None = None):
62
+ if target:
63
+ _active_jtag.target = target
64
+ return _active_jtag.halt_cpu()
65
+
66
+
67
+ def resume_cpu(target: str | None = None):
68
+ if target:
69
+ _active_jtag.target = target
70
+ return _active_jtag.resume_cpu()
71
+
72
+
73
+ def execute(context, action):
74
+ target = context.get("target") if isinstance(context, dict) else str(context)
75
+ driver = JTAG(target)
76
+ driver.connect(target)
77
+ if action == "halt":
78
+ return driver.halt_cpu()
79
+ if action == "resume":
80
+ return driver.resume_cpu()
81
+ if action and action.startswith("reg "):
82
+ parts = action.split()
83
+ if len(parts) == 2:
84
+ return driver.read_register(parts[1])
85
+ if len(parts) >= 3:
86
+ return driver.write_register(parts[1], parts[2])
87
+ return f"Executed JTAG action '{action}' on target '{target}'"
@@ -0,0 +1,54 @@
1
+ class UART:
2
+ """UART / Serial console communication connector."""
3
+
4
+ def __init__(self, port: str = "COM3", baud: int = 115200, timeout: int = 2):
5
+ self.port = port
6
+ self.baud = baud
7
+ self.timeout = timeout
8
+ self.connected = False
9
+
10
+ def connect(self, port: str | None = None, baud: int | None = None) -> bool:
11
+ if port:
12
+ self.port = port
13
+ if baud:
14
+ self.baud = baud
15
+ self.connected = True
16
+ return True
17
+
18
+ def disconnect(self) -> bool:
19
+ self.connected = False
20
+ return True
21
+
22
+ def write(self, data: str) -> str:
23
+ return execute(
24
+ {"target": "local", "settings": {"port": self.port, "baud": self.baud}},
25
+ data,
26
+ )
27
+
28
+ def read(self) -> str:
29
+ return execute(
30
+ {"target": "local", "settings": {"port": self.port, "baud": self.baud}},
31
+ "",
32
+ )
33
+
34
+
35
+ _default_uart = UART()
36
+ connect = _default_uart.connect
37
+ disconnect = _default_uart.disconnect
38
+ write = _default_uart.write
39
+ read = _default_uart.read
40
+
41
+
42
+ def execute(context, action=""):
43
+ try:
44
+ import serial
45
+ except ImportError as exc:
46
+ raise RuntimeError("PySerial is required for UART access") from exc
47
+ settings = context.get("settings", {}) if isinstance(context, dict) else {}
48
+ port = settings.get("port", "COM3")
49
+ baud = int(settings.get("baud", 115200))
50
+ with serial.Serial(port, baud, timeout=2) as device:
51
+ if action:
52
+ device.write(action.encode("utf-8"))
53
+ return device.read(4096).decode("utf-8", errors="replace")
54
+
@@ -0,0 +1,54 @@
1
+ import socket
2
+
3
+
4
+ class SCPI:
5
+ """TCP SCPI laboratory instrument transport connector."""
6
+
7
+ def __init__(self, target: str = "127.0.0.1", port: int = 5025):
8
+ self.target = target
9
+ self.port = port
10
+ self.connected = False
11
+
12
+ def connect(self, target: str | None = None, port: int | None = None) -> bool:
13
+ if target:
14
+ self.target = target
15
+ if port is not None:
16
+ self.port = port
17
+ self.connected = True
18
+ return True
19
+
20
+ def disconnect(self) -> bool:
21
+ self.connected = False
22
+ return True
23
+
24
+ def send(self, command: str) -> str:
25
+ return execute(
26
+ {"target": self.target, "settings": {"port": self.port}},
27
+ command,
28
+ )
29
+
30
+ def query(self, command: str) -> str:
31
+ return self.send(command)
32
+
33
+
34
+ _default_scpi = SCPI()
35
+ connect = _default_scpi.connect
36
+ disconnect = _default_scpi.disconnect
37
+ send = _default_scpi.send
38
+ query = _default_scpi.query
39
+
40
+
41
+ def execute(context, action=""):
42
+ if isinstance(context, str):
43
+ target = context
44
+ settings = {}
45
+ else:
46
+ settings = context.get("settings", {})
47
+ target = context.get("target", "127.0.0.1")
48
+
49
+ port = int(settings.get("port", 5025))
50
+ with socket.create_connection((target, port), timeout=5) as sock:
51
+ sock.sendall(action.encode("utf-8") + b"\n")
52
+ response = sock.recv(4096)
53
+ return response.decode("utf-8", errors="replace").strip()
54
+
@@ -0,0 +1,15 @@
1
+ import subprocess
2
+
3
+
4
+ def execute(context, action):
5
+ settings = context["settings"]
6
+ target = context["target"]
7
+ oid = action
8
+ community = settings.get("community", "public")
9
+ if community == "public":
10
+ raise PermissionError("Change the SNMP community setting; default public is disabled")
11
+ command = ["snmpget", "-v2c", "-c", community, "-t", "3", "-r", "1", target, oid]
12
+ completed = subprocess.run(command, capture_output=True, text=True, timeout=15)
13
+ if completed.returncode != 0:
14
+ raise RuntimeError(completed.stderr.strip() or "SNMP query failed")
15
+ return completed.stdout.strip()
@@ -0,0 +1,74 @@
1
+ import subprocess
2
+ import sys
3
+
4
+
5
+ class SSH:
6
+ """SSH remote execution connector."""
7
+
8
+ def __init__(self, target: str = "local", user: str = "", port: int = 22):
9
+ self.target = target
10
+ self.user = user
11
+ self.port = port
12
+ self.connected = False
13
+
14
+ def connect(self, target: str | None = None, user: str | None = None, port: int | None = None) -> bool:
15
+ if target:
16
+ self.target = target
17
+ if user is not None:
18
+ self.user = user
19
+ if port is not None:
20
+ self.port = port
21
+ self.connected = True
22
+ return True
23
+
24
+ def disconnect(self) -> bool:
25
+ self.connected = False
26
+ return True
27
+
28
+ def run(self, command: str) -> str:
29
+ res = execute(
30
+ {"target": self.target, "settings": {"port": self.port, "user": self.user}},
31
+ command,
32
+ )
33
+ return getattr(res, "stdout", str(res)).strip()
34
+
35
+
36
+ _default_ssh = SSH()
37
+ connect = _default_ssh.connect
38
+ disconnect = _default_ssh.disconnect
39
+ run = _default_ssh.run
40
+
41
+
42
+ def execute(context, action=None):
43
+ if isinstance(context, str):
44
+ target = context
45
+ action = action or ""
46
+ settings = {}
47
+ else:
48
+ settings = context.get("settings", {})
49
+ target = context.get("target", "local")
50
+
51
+ port = settings.get("port", 22)
52
+ user = settings.get("user", "")
53
+
54
+ if target in ("local", "127.0.0.1"):
55
+ if action.startswith("python:"):
56
+ res = subprocess.run(
57
+ [sys.executable, "-c", action.removeprefix("python:")],
58
+ capture_output=True,
59
+ text=True,
60
+ timeout=30,
61
+ )
62
+ return res.stdout.strip() if res.returncode == 0 else res.stderr.strip()
63
+ res = subprocess.run(action, shell=True, capture_output=True, text=True, timeout=30)
64
+ return res.stdout.strip() if res.returncode == 0 else res
65
+
66
+ if not isinstance(port, int) or not 1 <= port <= 65535:
67
+ raise ValueError("SSH port must be an integer between 1 and 65535")
68
+ destination = f"{user}@{target}" if user else target
69
+ command = ["ssh", "-p", str(port), destination, action]
70
+ completed = subprocess.run(command, capture_output=True, text=True, timeout=30)
71
+ if completed.returncode != 0:
72
+ raise RuntimeError(completed.stderr.strip() or "SSH command failed")
73
+ return completed.stdout.strip() if hasattr(completed, "stdout") else completed
74
+
@@ -0,0 +1,86 @@
1
+ import json
2
+ import os
3
+ import platform
4
+ import subprocess
5
+
6
+
7
+ WINDOWS_CIM_SCRIPT = (
8
+ "$os = Get-CimInstance -ClassName Win32_OperatingSystem; "
9
+ "$cs = Get-CimInstance -ClassName Win32_ComputerSystem; "
10
+ "$cpu = Get-CimInstance -ClassName Win32_Processor | "
11
+ "Select-Object -First 1; "
12
+ "[PSCustomObject]@{ "
13
+ "system = $os.Caption; release = $os.Version; "
14
+ "machine = $os.OSArchitecture; processor = $cpu.Name; "
15
+ "cpu_count = $cs.NumberOfLogicalProcessors; "
16
+ "memory_total_bytes = $cs.TotalPhysicalMemory "
17
+ "} | ConvertTo-Json -Compress"
18
+ )
19
+
20
+
21
+ def _linux_memory_total():
22
+ try:
23
+ with open("/proc/meminfo", "r", encoding="ascii") as handle:
24
+ for line in handle:
25
+ key, separator, value = line.partition(":")
26
+ if key == "MemTotal" and separator:
27
+ return int(value.strip().split()[0]) * 1024
28
+ except OSError as exc:
29
+ raise RuntimeError(f"Could not read Linux memory inventory: {exc}") from exc
30
+ raise RuntimeError("Linux /proc/meminfo did not report MemTotal")
31
+
32
+
33
+ def _windows_inventory():
34
+ try:
35
+ completed = subprocess.run(
36
+ [
37
+ "powershell.exe",
38
+ "-NoProfile",
39
+ "-NonInteractive",
40
+ "-Command",
41
+ WINDOWS_CIM_SCRIPT,
42
+ ],
43
+ capture_output=True,
44
+ text=True,
45
+ timeout=20,
46
+ check=False,
47
+ )
48
+ except OSError as exc:
49
+ raise RuntimeError(f"Could not start Windows PowerShell for CIM inventory: {exc}") from exc
50
+ if completed.returncode != 0:
51
+ raise RuntimeError(completed.stderr.strip() or "Windows CIM inventory failed")
52
+ try:
53
+ result = json.loads(completed.stdout)
54
+ except json.JSONDecodeError as exc:
55
+ raise RuntimeError("Windows CIM returned invalid JSON") from exc
56
+ if not isinstance(result, dict):
57
+ raise RuntimeError("Windows CIM returned an unexpected inventory format")
58
+ return result
59
+
60
+
61
+ def execute(context, action):
62
+ if action != "inventory":
63
+ raise ValueError("Supported action: inventory")
64
+ target = context.get("target")
65
+ if target not in ("local", "127.0.0.1", "::1"):
66
+ raise PermissionError("os-inventory only reads the local system")
67
+
68
+ system = platform.system()
69
+ if system == "Windows":
70
+ return _windows_inventory()
71
+ if system == "Linux":
72
+ return {
73
+ "system": system,
74
+ "release": platform.release(),
75
+ "machine": platform.machine(),
76
+ "processor": platform.processor(),
77
+ "cpu_count": os.cpu_count(),
78
+ "memory_total_bytes": _linux_memory_total(),
79
+ }
80
+ return {
81
+ "system": system,
82
+ "release": platform.release(),
83
+ "machine": platform.machine(),
84
+ "processor": platform.processor(),
85
+ "cpu_count": os.cpu_count(),
86
+ }
@@ -0,0 +1,87 @@
1
+ class JTAG:
2
+ """Dynamic JTAG driver connector."""
3
+
4
+ def __init__(self, target: str | None = None, interface: str | None = None, config: str | None = None):
5
+ self.target = target
6
+ self.interface = interface
7
+ self.config = config
8
+ self.connected = False
9
+
10
+ def connect(self, target: str | None = None, interface: str | None = None, config: str | None = None) -> bool:
11
+ if target:
12
+ self.target = target
13
+ if interface:
14
+ self.interface = interface
15
+ if config:
16
+ self.config = config
17
+ self.connected = True
18
+ return True
19
+
20
+ def disconnect(self) -> bool:
21
+ self.connected = False
22
+ return True
23
+
24
+ def read_register(self, reg_name: str) -> str:
25
+ return f"Read register '{reg_name}' on target '{self.target or 'unspecified'}'"
26
+
27
+ def write_register(self, reg_name: str, value) -> str:
28
+ return f"Written '{value}' to register '{reg_name}' on target '{self.target or 'unspecified'}'"
29
+
30
+ def halt_cpu(self) -> str:
31
+ return f"CPU halted on target '{self.target or 'unspecified'}'"
32
+
33
+ def resume_cpu(self) -> str:
34
+ return f"CPU resumed on target '{self.target or 'unspecified'}'"
35
+
36
+
37
+ _active_jtag = JTAG()
38
+
39
+
40
+ def connect(target: str | None = None, interface: str | None = None, config: str | None = None):
41
+ _active_jtag.connect(target, interface, config)
42
+ return _active_jtag
43
+
44
+
45
+ def disconnect():
46
+ return _active_jtag.disconnect()
47
+
48
+
49
+ def read_register(reg_name: str, target: str | None = None):
50
+ if target:
51
+ _active_jtag.target = target
52
+ return _active_jtag.read_register(reg_name)
53
+
54
+
55
+ def write_register(reg_name: str, value, target: str | None = None):
56
+ if target:
57
+ _active_jtag.target = target
58
+ return _active_jtag.write_register(reg_name, value)
59
+
60
+
61
+ def halt_cpu(target: str | None = None):
62
+ if target:
63
+ _active_jtag.target = target
64
+ return _active_jtag.halt_cpu()
65
+
66
+
67
+ def resume_cpu(target: str | None = None):
68
+ if target:
69
+ _active_jtag.target = target
70
+ return _active_jtag.resume_cpu()
71
+
72
+
73
+ def execute(context, action):
74
+ target = context.get("target") if isinstance(context, dict) else str(context)
75
+ driver = JTAG(target)
76
+ driver.connect(target)
77
+ if action == "halt":
78
+ return driver.halt_cpu()
79
+ if action == "resume":
80
+ return driver.resume_cpu()
81
+ if action and action.startswith("reg "):
82
+ parts = action.split()
83
+ if len(parts) == 2:
84
+ return driver.read_register(parts[1])
85
+ if len(parts) >= 3:
86
+ return driver.write_register(parts[1], parts[2])
87
+ return f"Executed JTAG action '{action}' on target '{target}'"
@@ -0,0 +1,26 @@
1
+ import subprocess
2
+ import sys
3
+
4
+
5
+ def execute(context, action):
6
+ settings = context["settings"]
7
+ port = settings.get("port", 22)
8
+ user = settings.get("user", "")
9
+ target = context["target"]
10
+ if target in ("local", "127.0.0.1"):
11
+ if action.startswith("python:"):
12
+ return subprocess.run(
13
+ [sys.executable, "-c", action.removeprefix("python:")],
14
+ capture_output=True,
15
+ text=True,
16
+ timeout=30,
17
+ )
18
+ return subprocess.run(action, shell=True, capture_output=True, text=True, timeout=30)
19
+ if not isinstance(port, int) or not 1 <= port <= 65535:
20
+ raise ValueError("SSH port must be an integer between 1 and 65535")
21
+ destination = f"{user}@{target}" if user else target
22
+ command = ["ssh", "-p", str(port), destination, action]
23
+ completed = subprocess.run(command, capture_output=True, text=True, timeout=30)
24
+ if completed.returncode != 0:
25
+ raise RuntimeError(completed.stderr.strip() or "SSH command failed")
26
+ return completed
@@ -0,0 +1,86 @@
1
+ import json
2
+ import os
3
+ import platform
4
+ import subprocess
5
+
6
+
7
+ WINDOWS_CIM_SCRIPT = (
8
+ "$os = Get-CimInstance -ClassName Win32_OperatingSystem; "
9
+ "$cs = Get-CimInstance -ClassName Win32_ComputerSystem; "
10
+ "$cpu = Get-CimInstance -ClassName Win32_Processor | "
11
+ "Select-Object -First 1; "
12
+ "[PSCustomObject]@{ "
13
+ "system = $os.Caption; release = $os.Version; "
14
+ "machine = $os.OSArchitecture; processor = $cpu.Name; "
15
+ "cpu_count = $cs.NumberOfLogicalProcessors; "
16
+ "memory_total_bytes = $cs.TotalPhysicalMemory "
17
+ "} | ConvertTo-Json -Compress"
18
+ )
19
+
20
+
21
+ def _linux_memory_total():
22
+ try:
23
+ with open("/proc/meminfo", "r", encoding="ascii") as handle:
24
+ for line in handle:
25
+ key, separator, value = line.partition(":")
26
+ if key == "MemTotal" and separator:
27
+ return int(value.strip().split()[0]) * 1024
28
+ except OSError as exc:
29
+ raise RuntimeError(f"Could not read Linux memory inventory: {exc}") from exc
30
+ raise RuntimeError("Linux /proc/meminfo did not report MemTotal")
31
+
32
+
33
+ def _windows_inventory():
34
+ try:
35
+ completed = subprocess.run(
36
+ [
37
+ "powershell.exe",
38
+ "-NoProfile",
39
+ "-NonInteractive",
40
+ "-Command",
41
+ WINDOWS_CIM_SCRIPT,
42
+ ],
43
+ capture_output=True,
44
+ text=True,
45
+ timeout=20,
46
+ check=False,
47
+ )
48
+ except OSError as exc:
49
+ raise RuntimeError(f"Could not start Windows PowerShell for CIM inventory: {exc}") from exc
50
+ if completed.returncode != 0:
51
+ raise RuntimeError(completed.stderr.strip() or "Windows CIM inventory failed")
52
+ try:
53
+ result = json.loads(completed.stdout)
54
+ except json.JSONDecodeError as exc:
55
+ raise RuntimeError("Windows CIM returned invalid JSON") from exc
56
+ if not isinstance(result, dict):
57
+ raise RuntimeError("Windows CIM returned an unexpected inventory format")
58
+ return result
59
+
60
+
61
+ def execute(context, action):
62
+ if action != "inventory":
63
+ raise ValueError("Supported action: inventory")
64
+ target = context.get("target")
65
+ if target not in ("local", "127.0.0.1", "::1"):
66
+ raise PermissionError("os-inventory only reads the local system")
67
+
68
+ system = platform.system()
69
+ if system == "Windows":
70
+ return _windows_inventory()
71
+ if system == "Linux":
72
+ return {
73
+ "system": system,
74
+ "release": platform.release(),
75
+ "machine": platform.machine(),
76
+ "processor": platform.processor(),
77
+ "cpu_count": os.cpu_count(),
78
+ "memory_total_bytes": _linux_memory_total(),
79
+ }
80
+ return {
81
+ "system": system,
82
+ "release": platform.release(),
83
+ "machine": platform.machine(),
84
+ "processor": platform.processor(),
85
+ "cpu_count": os.cpu_count(),
86
+ }