medic-cli 0.1.1__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 (47) hide show
  1. medic_cli-0.1.1/LICENSE +21 -0
  2. medic_cli-0.1.1/PKG-INFO +175 -0
  3. medic_cli-0.1.1/README.md +134 -0
  4. medic_cli-0.1.1/medic/__init__.py +41 -0
  5. medic_cli-0.1.1/medic/__main__.py +8 -0
  6. medic_cli-0.1.1/medic/checks/__init__.py +30 -0
  7. medic_cli-0.1.1/medic/checks/dns.py +60 -0
  8. medic_cli-0.1.1/medic/checks/exec.py +90 -0
  9. medic_cli-0.1.1/medic/checks/http.py +181 -0
  10. medic_cli-0.1.1/medic/checks/ping.py +226 -0
  11. medic_cli-0.1.1/medic/checks/ssh.py +246 -0
  12. medic_cli-0.1.1/medic/checks/system.py +469 -0
  13. medic_cli-0.1.1/medic/checks/tcp.py +184 -0
  14. medic_cli-0.1.1/medic/checks/tls.py +255 -0
  15. medic_cli-0.1.1/medic/cli.py +572 -0
  16. medic_cli-0.1.1/medic/completion.py +46 -0
  17. medic_cli-0.1.1/medic/config.py +199 -0
  18. medic_cli-0.1.1/medic/core/__init__.py +18 -0
  19. medic_cli-0.1.1/medic/core/base.py +48 -0
  20. medic_cli-0.1.1/medic/core/enums.py +85 -0
  21. medic_cli-0.1.1/medic/core/models.py +116 -0
  22. medic_cli-0.1.1/medic/core/runner.py +212 -0
  23. medic_cli-0.1.1/medic/formatters/__init__.py +48 -0
  24. medic_cli-0.1.1/medic/formatters/base.py +14 -0
  25. medic_cli-0.1.1/medic/formatters/json_formatter.py +26 -0
  26. medic_cli-0.1.1/medic/formatters/junit_formatter.py +52 -0
  27. medic_cli-0.1.1/medic/formatters/rich_formatter.py +187 -0
  28. medic_cli-0.1.1/medic/formatters/text_formatter.py +60 -0
  29. medic_cli-0.1.1/medic/py.typed +0 -0
  30. medic_cli-0.1.1/medic_cli.egg-info/PKG-INFO +175 -0
  31. medic_cli-0.1.1/medic_cli.egg-info/SOURCES.txt +45 -0
  32. medic_cli-0.1.1/medic_cli.egg-info/dependency_links.txt +1 -0
  33. medic_cli-0.1.1/medic_cli.egg-info/entry_points.txt +2 -0
  34. medic_cli-0.1.1/medic_cli.egg-info/requires.txt +17 -0
  35. medic_cli-0.1.1/medic_cli.egg-info/top_level.txt +1 -0
  36. medic_cli-0.1.1/pyproject.toml +86 -0
  37. medic_cli-0.1.1/setup.cfg +4 -0
  38. medic_cli-0.1.1/tests/test_cli.py +67 -0
  39. medic_cli-0.1.1/tests/test_features.py +144 -0
  40. medic_cli-0.1.1/tests/test_http.py +72 -0
  41. medic_cli-0.1.1/tests/test_models.py +93 -0
  42. medic_cli-0.1.1/tests/test_ping.py +86 -0
  43. medic_cli-0.1.1/tests/test_runner.py +102 -0
  44. medic_cli-0.1.1/tests/test_ssh.py +50 -0
  45. medic_cli-0.1.1/tests/test_system.py +101 -0
  46. medic_cli-0.1.1/tests/test_tcp.py +65 -0
  47. medic_cli-0.1.1/tests/test_tls.py +66 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ali
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,175 @@
1
+ Metadata-Version: 2.4
2
+ Name: medic-cli
3
+ Version: 0.1.1
4
+ Summary: Health-check CLI for pipeline checkpoints, CI, and watch-mode monitoring
5
+ Author: Ali
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Rogsiel/medic
8
+ Project-URL: Issues, https://github.com/Rogsiel/medic/issues
9
+ Keywords: healthcheck,monitoring,cli,ci,devops,diagnostics
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: System :: Monitoring
21
+ Classifier: Topic :: System :: Networking :: Monitoring
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: rich>=12.0.0
27
+ Requires-Dist: psutil>=5.9.0
28
+ Requires-Dist: requests>=2.28.0
29
+ Requires-Dist: cryptography>=38.0.0
30
+ Requires-Dist: argcomplete>=3.0.0
31
+ Requires-Dist: tomli>=2.0.0; python_version < "3.11"
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
34
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
35
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
36
+ Requires-Dist: ruff>=0.5.0; extra == "dev"
37
+ Requires-Dist: types-requests; extra == "dev"
38
+ Requires-Dist: types-psutil; extra == "dev"
39
+ Requires-Dist: build; extra == "dev"
40
+ Dynamic: license-file
41
+
42
+ # 🩺 medic
43
+
44
+ [![CI](https://github.com/Rogsiel/medic/actions/workflows/ci.yml/badge.svg)](https://github.com/Rogsiel/medic/actions/workflows/ci.yml)
45
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
46
+
47
+ A small health-check CLI. Use it as a **checkpoint in a pipeline** (exit code + JUnit), as a
48
+ **one-off diagnostic**, or as a **live terminal monitor** (`--watch`). No server, no daemon.
49
+
50
+ medic reports problems; it does not fix them.
51
+
52
+ ![medic running a staged check suite: one failure, a skipped dependent check, and a remediation hint](https://raw.githubusercontent.com/Rogsiel/medic/main/docs/screenshot.svg)
53
+
54
+ ## Checks
55
+
56
+ | Type | What it verifies |
57
+ |---|---|
58
+ | `system` | CPU, load, memory, swap, disk per mount, uptime |
59
+ | `ping` | ICMP reachability, packet loss, RTT (uses the system `ping`) |
60
+ | `tcp` | Port reachability, connect latency, optional banner |
61
+ | `http` | Status code, latency, body substring, TLS verification |
62
+ | `tls` | Certificate expiry (days left), issuer, SANs, protocol |
63
+ | `ssh` | Daemon reachability, protocol/banner, optional key auth |
64
+ | `dns` | Name resolution, optional expected addresses |
65
+ | `exec` | Run a command; pass on expected exit code / output |
66
+
67
+ ## Install
68
+
69
+ ```bash
70
+ pipx install git+https://github.com/Rogsiel/medic.git
71
+ # or from a clone
72
+ pip install .
73
+ ```
74
+
75
+ Requires Python 3.10+. Enable shell completion (bash, zsh, fish) with:
76
+
77
+ ```bash
78
+ medic --install-completion
79
+ ```
80
+
81
+ ## Quick start
82
+
83
+ ```bash
84
+ medic # local system checks only (no network)
85
+ medic --all # + internet reachability (ping, HTTP, TLS)
86
+ medic --tcp db:5432 --http https://api.example.com/health --http-match ok
87
+ medic --tls example.com --tls-warn-days 30 --tls-crit-days 7
88
+ medic --dns example.com --exec "pg_isready -h db"
89
+ medic --system --disk / --disk /var --cpu-threshold 70,90 --ram-threshold 80,95
90
+ ```
91
+
92
+ Run `medic --help` for every flag.
93
+
94
+ ## Pipelines and CI
95
+
96
+ Exit codes: `0` healthy, `1` a check failed (or warned, with `--fail-on warning`), `2` bad config.
97
+
98
+ Declare checks in TOML. Checks with a higher `stage` are **skipped if any lower stage fails**, which
99
+ gives you checkpoint semantics:
100
+
101
+ ```toml
102
+ # medic.toml
103
+ [settings]
104
+ timeout = 6
105
+ fail_on = "failure" # or "warning"
106
+
107
+ [[check]]
108
+ type = "tcp"
109
+ target = "db:5432"
110
+ stage = 0
111
+
112
+ [[check]]
113
+ type = "http"
114
+ name = "API"
115
+ url = "https://api.example.com/health"
116
+ expect_status = [200]
117
+ match = "ok"
118
+ stage = 1
119
+ ```
120
+
121
+ ```bash
122
+ medic --config medic.toml --format junit > medic.xml
123
+ ```
124
+
125
+ Check keys by type:
126
+
127
+ | Type | Keys |
128
+ |---|---|
129
+ | `system` | `disks`, `cpu`, `ram`, `disk_threshold` (each `[warn, crit]`) |
130
+ | `ping` | `host`, `count` |
131
+ | `tcp` | `target` (`host:port`) or `host` + `port` |
132
+ | `http` | `url`, `method`, `expect_status`, `match`, `verify_ssl`, `headers` |
133
+ | `tls` | `target` or `host` + `port`, `warn_days`, `crit_days` |
134
+ | `ssh` | `target`, `user`, `key`, `auth` |
135
+ | `dns` | `host`, `expect` |
136
+ | `exec` | `command`, `expect_exit`, `match`, `shell`, `cwd` |
137
+
138
+ All checks also accept `name`, `stage`, `timeout`, `enabled`. Explicit CLI flags override `[settings]`.
139
+ Unknown types or keys are rejected.
140
+
141
+ Every check is bounded by its timeout (+2s grace). A hung check is reported as failed instead of
142
+ blocking the run. `--stop-on-failure` runs sequentially and stops at the first failure.
143
+
144
+ GitHub Actions example:
145
+
146
+ ```yaml
147
+ - run: pipx install git+https://github.com/Rogsiel/medic.git
148
+ - run: medic --config medic.toml --format junit > medic.xml
149
+ ```
150
+
151
+ ## Watch mode
152
+
153
+ ```bash
154
+ medic --config medic.toml --watch 5
155
+ ```
156
+
157
+ Re-runs every 5 seconds and redraws the report. Status transitions (e.g. `passed -> failed`) are
158
+ logged to stderr as `[change] ...`. Ctrl-C exits with the last run's exit code.
159
+
160
+ ## Output formats
161
+
162
+ `--format rich` (default), `text`, `compact`, `json`, `junit`.
163
+
164
+ ## Development
165
+
166
+ ```bash
167
+ pip install -e '.[dev]'
168
+ pytest
169
+ ruff check .
170
+ mypy medic
171
+ ```
172
+
173
+ ## License
174
+
175
+ MIT
@@ -0,0 +1,134 @@
1
+ # 🩺 medic
2
+
3
+ [![CI](https://github.com/Rogsiel/medic/actions/workflows/ci.yml/badge.svg)](https://github.com/Rogsiel/medic/actions/workflows/ci.yml)
4
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
5
+
6
+ A small health-check CLI. Use it as a **checkpoint in a pipeline** (exit code + JUnit), as a
7
+ **one-off diagnostic**, or as a **live terminal monitor** (`--watch`). No server, no daemon.
8
+
9
+ medic reports problems; it does not fix them.
10
+
11
+ ![medic running a staged check suite: one failure, a skipped dependent check, and a remediation hint](https://raw.githubusercontent.com/Rogsiel/medic/main/docs/screenshot.svg)
12
+
13
+ ## Checks
14
+
15
+ | Type | What it verifies |
16
+ |---|---|
17
+ | `system` | CPU, load, memory, swap, disk per mount, uptime |
18
+ | `ping` | ICMP reachability, packet loss, RTT (uses the system `ping`) |
19
+ | `tcp` | Port reachability, connect latency, optional banner |
20
+ | `http` | Status code, latency, body substring, TLS verification |
21
+ | `tls` | Certificate expiry (days left), issuer, SANs, protocol |
22
+ | `ssh` | Daemon reachability, protocol/banner, optional key auth |
23
+ | `dns` | Name resolution, optional expected addresses |
24
+ | `exec` | Run a command; pass on expected exit code / output |
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pipx install git+https://github.com/Rogsiel/medic.git
30
+ # or from a clone
31
+ pip install .
32
+ ```
33
+
34
+ Requires Python 3.10+. Enable shell completion (bash, zsh, fish) with:
35
+
36
+ ```bash
37
+ medic --install-completion
38
+ ```
39
+
40
+ ## Quick start
41
+
42
+ ```bash
43
+ medic # local system checks only (no network)
44
+ medic --all # + internet reachability (ping, HTTP, TLS)
45
+ medic --tcp db:5432 --http https://api.example.com/health --http-match ok
46
+ medic --tls example.com --tls-warn-days 30 --tls-crit-days 7
47
+ medic --dns example.com --exec "pg_isready -h db"
48
+ medic --system --disk / --disk /var --cpu-threshold 70,90 --ram-threshold 80,95
49
+ ```
50
+
51
+ Run `medic --help` for every flag.
52
+
53
+ ## Pipelines and CI
54
+
55
+ Exit codes: `0` healthy, `1` a check failed (or warned, with `--fail-on warning`), `2` bad config.
56
+
57
+ Declare checks in TOML. Checks with a higher `stage` are **skipped if any lower stage fails**, which
58
+ gives you checkpoint semantics:
59
+
60
+ ```toml
61
+ # medic.toml
62
+ [settings]
63
+ timeout = 6
64
+ fail_on = "failure" # or "warning"
65
+
66
+ [[check]]
67
+ type = "tcp"
68
+ target = "db:5432"
69
+ stage = 0
70
+
71
+ [[check]]
72
+ type = "http"
73
+ name = "API"
74
+ url = "https://api.example.com/health"
75
+ expect_status = [200]
76
+ match = "ok"
77
+ stage = 1
78
+ ```
79
+
80
+ ```bash
81
+ medic --config medic.toml --format junit > medic.xml
82
+ ```
83
+
84
+ Check keys by type:
85
+
86
+ | Type | Keys |
87
+ |---|---|
88
+ | `system` | `disks`, `cpu`, `ram`, `disk_threshold` (each `[warn, crit]`) |
89
+ | `ping` | `host`, `count` |
90
+ | `tcp` | `target` (`host:port`) or `host` + `port` |
91
+ | `http` | `url`, `method`, `expect_status`, `match`, `verify_ssl`, `headers` |
92
+ | `tls` | `target` or `host` + `port`, `warn_days`, `crit_days` |
93
+ | `ssh` | `target`, `user`, `key`, `auth` |
94
+ | `dns` | `host`, `expect` |
95
+ | `exec` | `command`, `expect_exit`, `match`, `shell`, `cwd` |
96
+
97
+ All checks also accept `name`, `stage`, `timeout`, `enabled`. Explicit CLI flags override `[settings]`.
98
+ Unknown types or keys are rejected.
99
+
100
+ Every check is bounded by its timeout (+2s grace). A hung check is reported as failed instead of
101
+ blocking the run. `--stop-on-failure` runs sequentially and stops at the first failure.
102
+
103
+ GitHub Actions example:
104
+
105
+ ```yaml
106
+ - run: pipx install git+https://github.com/Rogsiel/medic.git
107
+ - run: medic --config medic.toml --format junit > medic.xml
108
+ ```
109
+
110
+ ## Watch mode
111
+
112
+ ```bash
113
+ medic --config medic.toml --watch 5
114
+ ```
115
+
116
+ Re-runs every 5 seconds and redraws the report. Status transitions (e.g. `passed -> failed`) are
117
+ logged to stderr as `[change] ...`. Ctrl-C exits with the last run's exit code.
118
+
119
+ ## Output formats
120
+
121
+ `--format rich` (default), `text`, `compact`, `json`, `junit`.
122
+
123
+ ## Development
124
+
125
+ ```bash
126
+ pip install -e '.[dev]'
127
+ pytest
128
+ ruff check .
129
+ mypy medic
130
+ ```
131
+
132
+ ## License
133
+
134
+ MIT
@@ -0,0 +1,41 @@
1
+ """medic: Fast, type-safe CLI health check & diagnostic tool."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("medic-cli")
7
+ except PackageNotFoundError: # running from a source tree without install metadata
8
+ __version__ = "0+unknown"
9
+
10
+ from .checks.http import HTTPCheck
11
+ from .checks.ping import PingCheck
12
+ from .checks.ssh import SSHCheck
13
+ from .checks.system import CPUCheck, DiskCheck, MemoryCheck, SwapCheck, SystemCheckGroup, UptimeCheck
14
+ from .checks.tcp import TCPCheck
15
+ from .checks.tls import TLSCheck
16
+ from .core.base import BaseCheck
17
+ from .core.enums import CheckCategory, CheckStatus, OutputFormat
18
+ from .core.models import CheckResult, MedicReport
19
+ from .core.runner import MedicRunner
20
+
21
+ __all__ = [
22
+ "__version__",
23
+ "CheckCategory",
24
+ "CheckStatus",
25
+ "OutputFormat",
26
+ "CheckResult",
27
+ "MedicReport",
28
+ "MedicRunner",
29
+ "BaseCheck",
30
+ "CPUCheck",
31
+ "MemoryCheck",
32
+ "DiskCheck",
33
+ "SwapCheck",
34
+ "UptimeCheck",
35
+ "SystemCheckGroup",
36
+ "PingCheck",
37
+ "TCPCheck",
38
+ "HTTPCheck",
39
+ "TLSCheck",
40
+ "SSHCheck",
41
+ ]
@@ -0,0 +1,8 @@
1
+ """Direct module execution entry point for medic."""
2
+
3
+ import sys
4
+
5
+ from medic.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
@@ -0,0 +1,30 @@
1
+ """Health check modules for medic."""
2
+
3
+ from .http import HTTPCheck
4
+ from .ping import PingCheck
5
+ from .ssh import SSHCheck
6
+ from .system import (
7
+ CPUCheck,
8
+ DiskCheck,
9
+ MemoryCheck,
10
+ SwapCheck,
11
+ SystemCheckGroup,
12
+ UptimeCheck,
13
+ )
14
+ from .tcp import TCPCheck, parse_host_port
15
+ from .tls import TLSCheck
16
+
17
+ __all__ = [
18
+ "CPUCheck",
19
+ "MemoryCheck",
20
+ "SwapCheck",
21
+ "DiskCheck",
22
+ "UptimeCheck",
23
+ "SystemCheckGroup",
24
+ "PingCheck",
25
+ "TCPCheck",
26
+ "parse_host_port",
27
+ "HTTPCheck",
28
+ "TLSCheck",
29
+ "SSHCheck",
30
+ ]
@@ -0,0 +1,60 @@
1
+ """DNS resolution check."""
2
+
3
+ import socket
4
+ import time
5
+ from typing import List, Optional, Sequence
6
+
7
+ from medic.core.base import BaseCheck
8
+ from medic.core.enums import CheckCategory, CheckStatus
9
+ from medic.core.models import CheckResult
10
+
11
+
12
+ class DNSCheck(BaseCheck):
13
+ """Resolves a hostname via the system resolver, optionally requiring specific addresses."""
14
+
15
+ category = CheckCategory.DNS
16
+
17
+ def __init__(
18
+ self,
19
+ host: str,
20
+ name: Optional[str] = None,
21
+ expect: Optional[Sequence[str]] = None,
22
+ warn_latency_ms: float = 500.0,
23
+ timeout: float = 5.0,
24
+ enabled: bool = True,
25
+ ) -> None:
26
+ super().__init__(name=name or f"DNS {host}", timeout=timeout, enabled=enabled)
27
+ self.host = host.strip()
28
+ self.expect = list(expect) if expect else []
29
+ self.warn_latency_ms = warn_latency_ms
30
+
31
+ def run(self) -> CheckResult:
32
+ start = time.perf_counter()
33
+ try:
34
+ infos = socket.getaddrinfo(self.host, None, proto=socket.IPPROTO_TCP)
35
+ except socket.gaierror as exc:
36
+ return self._result(CheckStatus.FAILED, f"Resolution failed: {exc.strerror or exc}", start, [])
37
+
38
+ addrs: List[str] = sorted({str(i[4][0]) for i in infos})
39
+ missing = [a for a in self.expect if a not in addrs]
40
+ if missing:
41
+ return self._result(
42
+ CheckStatus.FAILED, f"Missing expected address(es): {', '.join(missing)}", start, addrs
43
+ )
44
+ elapsed = (time.perf_counter() - start) * 1000.0
45
+ status = CheckStatus.WARNING if elapsed > self.warn_latency_ms else CheckStatus.PASSED
46
+ return self._result(status, f"Resolved to {', '.join(addrs)}", start, addrs)
47
+
48
+ def _result(self, status: CheckStatus, message: str, start: float, addrs: List[str]) -> CheckResult:
49
+ return CheckResult(
50
+ name=self.name,
51
+ category=self.category,
52
+ status=status,
53
+ message=message,
54
+ target=self.host,
55
+ latency_ms=(time.perf_counter() - start) * 1000.0,
56
+ details={"addresses": addrs},
57
+ remediation="Check resolver configuration (/etc/resolv.conf) and the DNS record."
58
+ if status == CheckStatus.FAILED
59
+ else None,
60
+ )
@@ -0,0 +1,90 @@
1
+ """Run an arbitrary command and judge it by exit code and output."""
2
+
3
+ import shlex
4
+ import subprocess
5
+ import time
6
+ from typing import List, Optional, Sequence, Union
7
+
8
+ from medic.core.base import BaseCheck
9
+ from medic.core.enums import CheckCategory, CheckStatus
10
+ from medic.core.models import CheckResult
11
+
12
+ _OUTPUT_TAIL = 500
13
+
14
+
15
+ class ExecCheck(BaseCheck):
16
+ """Passes when a command exits with the expected code (and optional output match).
17
+
18
+ The command is run without a shell unless ``shell=True``.
19
+ """
20
+
21
+ category = CheckCategory.EXEC
22
+
23
+ def __init__(
24
+ self,
25
+ command: Union[str, Sequence[str]],
26
+ name: Optional[str] = None,
27
+ expect_exit: int = 0,
28
+ contains_text: Optional[str] = None,
29
+ shell: bool = False,
30
+ cwd: Optional[str] = None,
31
+ timeout: float = 10.0,
32
+ enabled: bool = True,
33
+ ) -> None:
34
+ self.argv: Union[str, List[str]]
35
+ if isinstance(command, str):
36
+ self.argv = command if shell else shlex.split(command)
37
+ else:
38
+ self.argv = list(command)
39
+ display = command if isinstance(command, str) else shlex.join(command)
40
+ super().__init__(name=name or f"Exec {display}", timeout=timeout, enabled=enabled)
41
+ self.display = display
42
+ self.expect_exit = expect_exit
43
+ self.contains_text = contains_text
44
+ self.shell = shell
45
+ self.cwd = cwd
46
+
47
+ def run(self) -> CheckResult:
48
+ start = time.perf_counter()
49
+ try:
50
+ proc = subprocess.run(
51
+ self.argv,
52
+ shell=self.shell,
53
+ cwd=self.cwd,
54
+ capture_output=True,
55
+ text=True,
56
+ timeout=self.timeout,
57
+ )
58
+ except subprocess.TimeoutExpired:
59
+ return self._result(CheckStatus.FAILED, f"Command timed out after {self.timeout:.1f}s", start)
60
+ except (OSError, ValueError) as exc:
61
+ return self._result(CheckStatus.FAILED, f"Could not run command: {exc}", start)
62
+
63
+ out = (proc.stdout or "").strip()
64
+ err = (proc.stderr or "").strip()
65
+ details = {
66
+ "command": self.display,
67
+ "exit_code": proc.returncode,
68
+ "stdout": out[-_OUTPUT_TAIL:],
69
+ "stderr": err[-_OUTPUT_TAIL:],
70
+ }
71
+ if proc.returncode != self.expect_exit:
72
+ tail = (err or out).splitlines()[-1:] or [""]
73
+ msg = f"Exit code {proc.returncode} (expected {self.expect_exit})"
74
+ if tail[0]:
75
+ msg += f": {tail[0][:200]}"
76
+ return self._result(CheckStatus.FAILED, msg, start, details)
77
+ if self.contains_text is not None and self.contains_text not in out:
78
+ return self._result(CheckStatus.FAILED, f"Output does not contain {self.contains_text!r}", start, details)
79
+ return self._result(CheckStatus.PASSED, f"Exit code {proc.returncode}", start, details)
80
+
81
+ def _result(self, status: CheckStatus, message: str, start: float, details: Optional[dict] = None) -> CheckResult:
82
+ return CheckResult(
83
+ name=self.name,
84
+ category=self.category,
85
+ status=status,
86
+ message=message,
87
+ target=self.display,
88
+ latency_ms=(time.perf_counter() - start) * 1000.0,
89
+ details=details or {},
90
+ )