medic-cli 0.1.1__py3-none-any.whl

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.
medic/cli.py ADDED
@@ -0,0 +1,572 @@
1
+ """Command Line Interface for medic health check & diagnostic tool."""
2
+
3
+ import argparse
4
+ import sys
5
+ import time
6
+ from typing import Any, Dict, List, Optional, Sequence
7
+
8
+ import argcomplete
9
+ from rich.console import Console
10
+
11
+ from medic import __version__, completion
12
+ from medic.checks.dns import DNSCheck
13
+ from medic.checks.exec import ExecCheck
14
+ from medic.checks.http import HTTPCheck
15
+ from medic.checks.ping import PingCheck
16
+ from medic.checks.ssh import SSHCheck
17
+ from medic.checks.system import (
18
+ SystemCheckGroup,
19
+ )
20
+ from medic.checks.tcp import TCPCheck
21
+ from medic.checks.tls import TLSCheck
22
+ from medic.config import ConfigError, load_config
23
+ from medic.core.base import BaseCheck
24
+ from medic.core.enums import CheckStatus, OutputFormat
25
+ from medic.core.models import MedicReport
26
+ from medic.core.runner import MedicRunner
27
+ from medic.formatters import get_formatter
28
+
29
+
30
+ def parse_threshold(val_str: str, default: tuple[float, float]) -> tuple[float, float]:
31
+ """Parse comma-separated threshold string like '80,95'."""
32
+ try:
33
+ parts = [float(p.strip()) for p in val_str.split(",")]
34
+ if len(parts) == 1:
35
+ return parts[0], default[1]
36
+ return parts[0], parts[1]
37
+ except Exception:
38
+ return default
39
+
40
+
41
+ def parse_status_codes(val_str: str) -> List[int]:
42
+ """Parse comma-separated status codes or ranges like '200,201,200-299'."""
43
+ codes: List[int] = []
44
+ for part in val_str.split(","):
45
+ part = part.strip()
46
+ if "-" in part:
47
+ try:
48
+ start, end = part.split("-", 1)
49
+ codes.extend(range(int(start), int(end) + 1))
50
+ except ValueError:
51
+ pass
52
+ else:
53
+ try:
54
+ codes.append(int(part))
55
+ except ValueError:
56
+ pass
57
+ return codes if codes else [200, 201, 204, 301, 302, 307, 308]
58
+
59
+
60
+ def build_parser() -> argparse.ArgumentParser:
61
+ """Create the argument parser with all CLI flags."""
62
+ parser = argparse.ArgumentParser(
63
+ prog="medic",
64
+ description="🩺 medic: Fast, type-safe CLI health check & diagnostic tool",
65
+ formatter_class=argparse.RawDescriptionHelpFormatter,
66
+ epilog="""
67
+ Examples:
68
+ medic # Run default system & connectivity checkup
69
+ medic --all # Run full default checkup suite
70
+ medic --system # Check CPU, RAM, Swap, Root Disk, and Uptime
71
+ medic --ping 1.1.1.1 8.8.8.8 google.com # Ping test multiple hosts
72
+ medic --tcp localhost:5432 redis:6379 # Test TCP ports connectivity
73
+ medic --http https://github.com # Check HTTP endpoint availability
74
+ medic --tls google.com github.com:443 # Verify SSL/TLS cert expiration & SANs
75
+ medic --ssh 192.168.1.50:22 # Check SSH daemon & handshake
76
+ medic --system --ping 1.1.1.1 --format json # Output results as JSON
77
+ medic --config medic.toml # Run checks declared in a TOML file (supports stages)
78
+ medic --exec "pg_isready -h db" --dns example.com
79
+ medic --system --watch 5 # Live monitor, refresh every 5s
80
+ medic --config medic.toml --format junit --fail-on warning # CI mode
81
+ """,
82
+ )
83
+
84
+ parser.add_argument("-V", "--version", action="version", version=f"medic {__version__}")
85
+
86
+ comp_group = parser.add_argument_group("Shell Completion")
87
+ comp_group.add_argument(
88
+ "--install-completion",
89
+ action="store_true",
90
+ help="Install tab-completion for your current shell (no rc file edits needed)",
91
+ )
92
+ comp_group.add_argument(
93
+ "--completion",
94
+ dest="print_completion",
95
+ choices=completion.SHELLS,
96
+ metavar="SHELL",
97
+ help="Print the completion script for bash, zsh or fish",
98
+ )
99
+ # Check Targets
100
+ targets_group = parser.add_argument_group("Check Targets & Flags")
101
+ targets_group.add_argument(
102
+ "-a",
103
+ "--all",
104
+ action="store_true",
105
+ help="Run comprehensive default check suite (system, default gateway/DNS, internet reachability)",
106
+ )
107
+ targets_group.add_argument(
108
+ "-s",
109
+ "--system",
110
+ action="store_true",
111
+ help="Run system resources checks (CPU, Memory, Swap, Disk, Uptime)",
112
+ )
113
+ targets_group.add_argument(
114
+ "--disk",
115
+ action="append",
116
+ dest="disks",
117
+ metavar="PATH",
118
+ help="Specific disk mount/path to check (can be specified multiple times, e.g. --disk / --disk /var)",
119
+ )
120
+ targets_group.add_argument(
121
+ "--cpu-threshold",
122
+ default="80,95",
123
+ metavar="WARN,CRIT",
124
+ help="CPU warning and critical thresholds in percent (default: 80,95)",
125
+ )
126
+ targets_group.add_argument(
127
+ "--ram-threshold",
128
+ default="85,95",
129
+ metavar="WARN,CRIT",
130
+ help="RAM warning and critical thresholds in percent (default: 85,95)",
131
+ )
132
+ targets_group.add_argument(
133
+ "--disk-threshold",
134
+ default="85,92",
135
+ metavar="WARN,CRIT",
136
+ help="Disk warning and critical thresholds in percent (default: 85,92)",
137
+ )
138
+ targets_group.add_argument(
139
+ "--ping",
140
+ nargs="+",
141
+ metavar="HOST",
142
+ help="Host(s) or IP(s) to ping with ICMP (e.g. --ping 1.1.1.1 google.com)",
143
+ )
144
+ targets_group.add_argument(
145
+ "--ping-count",
146
+ type=int,
147
+ default=3,
148
+ metavar="N",
149
+ help="Number of ICMP ping packets to transmit (default: 3)",
150
+ )
151
+ targets_group.add_argument(
152
+ "--tcp",
153
+ nargs="+",
154
+ metavar="HOST:PORT",
155
+ help="TCP host:port target(s) to test (e.g. --tcp localhost:5432 1.1.1.1:53)",
156
+ )
157
+ targets_group.add_argument(
158
+ "--http",
159
+ nargs="+",
160
+ metavar="URL",
161
+ help="HTTP/HTTPS URL(s) to check (e.g. --http https://github.com http://localhost:8000)",
162
+ )
163
+ targets_group.add_argument(
164
+ "--http-method",
165
+ default="GET",
166
+ metavar="METHOD",
167
+ help="HTTP method to use (GET, HEAD, POST; default: GET)",
168
+ )
169
+ targets_group.add_argument(
170
+ "--http-status",
171
+ default="200,201,204,301,302,307,308",
172
+ metavar="CODES",
173
+ help="Expected HTTP status codes or ranges (e.g. 200, 200-299; default: 2xx/3xx)",
174
+ )
175
+ targets_group.add_argument(
176
+ "--http-match",
177
+ metavar="TEXT",
178
+ help="Verify response body contains expected substring",
179
+ )
180
+ targets_group.add_argument(
181
+ "--no-verify-ssl",
182
+ action="store_true",
183
+ help="Disable SSL/TLS certificate verification for HTTP checks",
184
+ )
185
+ targets_group.add_argument(
186
+ "--tls",
187
+ nargs="+",
188
+ metavar="HOST[:PORT]",
189
+ help="TLS/SSL certificate check targets (default port 443; e.g. --tls google.com:443)",
190
+ )
191
+ targets_group.add_argument(
192
+ "--tls-warn-days",
193
+ type=int,
194
+ default=30,
195
+ metavar="DAYS",
196
+ help="Days before cert expiration to trigger warning (default: 30)",
197
+ )
198
+ targets_group.add_argument(
199
+ "--tls-crit-days",
200
+ type=int,
201
+ default=7,
202
+ metavar="DAYS",
203
+ help="Days before cert expiration to trigger critical failure (default: 7)",
204
+ )
205
+ targets_group.add_argument(
206
+ "--ssh",
207
+ nargs="+",
208
+ metavar="HOST[:PORT]",
209
+ help="SSH target(s) to check service & banner (e.g. --ssh localhost:22 192.168.1.10)",
210
+ )
211
+ targets_group.add_argument(
212
+ "--ssh-user",
213
+ metavar="USER",
214
+ help="SSH username for authentication check",
215
+ )
216
+ targets_group.add_argument(
217
+ "--ssh-key",
218
+ metavar="KEY_FILE",
219
+ help="SSH private key path for authentication check",
220
+ )
221
+ targets_group.add_argument(
222
+ "--ssh-auth",
223
+ action="store_true",
224
+ help="Test full SSH authentication using local OpenSSH client",
225
+ )
226
+ targets_group.add_argument(
227
+ "--dns",
228
+ nargs="+",
229
+ metavar="HOST",
230
+ help="Hostname(s) to resolve via the system resolver",
231
+ )
232
+ targets_group.add_argument(
233
+ "--exec",
234
+ action="append",
235
+ dest="exec_cmds",
236
+ metavar="CMD",
237
+ help="Command to run (no shell); passes on exit code 0. Repeatable, e.g. --exec 'pg_isready -h db'",
238
+ )
239
+ targets_group.add_argument(
240
+ "-c",
241
+ "--config",
242
+ metavar="FILE",
243
+ help="TOML file declaring checks, stages and settings (CLI flags override [settings])",
244
+ )
245
+
246
+ # Runner & Concurrency
247
+ runner_group = parser.add_argument_group("Execution & Performance")
248
+ runner_group.add_argument(
249
+ "--timeout",
250
+ type=float,
251
+ default=None,
252
+ metavar="SEC",
253
+ help="Per-check timeout in seconds (default: 6.0)",
254
+ )
255
+ runner_group.add_argument(
256
+ "-j",
257
+ "--concurrency",
258
+ type=int,
259
+ default=None,
260
+ metavar="N",
261
+ help="Number of concurrent worker threads (default: 8)",
262
+ )
263
+ runner_group.add_argument(
264
+ "--no-parallel",
265
+ action="store_true",
266
+ help="Run checks sequentially instead of parallel threads",
267
+ )
268
+ runner_group.add_argument(
269
+ "--stop-on-failure",
270
+ action="store_true",
271
+ help="Stop running remaining checks on first failure (runs sequentially)",
272
+ )
273
+ runner_group.add_argument(
274
+ "--fail-on",
275
+ choices=["failure", "warning"],
276
+ default=None,
277
+ help="Exit non-zero on failures only (default) or also on warnings",
278
+ )
279
+ runner_group.add_argument(
280
+ "-w",
281
+ "--watch",
282
+ nargs="?",
283
+ type=float,
284
+ const=5.0,
285
+ default=None,
286
+ metavar="SEC",
287
+ help="Re-run continuously every SEC seconds (default 5) until Ctrl-C",
288
+ )
289
+
290
+ # Output Formatting
291
+ out_group = parser.add_argument_group("Output Formatting")
292
+ out_group.add_argument(
293
+ "-f",
294
+ "--format",
295
+ choices=["rich", "json", "text", "compact", "junit"],
296
+ default="rich",
297
+ help="Output format (default: rich)",
298
+ )
299
+ out_group.add_argument(
300
+ "-v",
301
+ "--verbose",
302
+ action="store_true",
303
+ help="Show detailed diagnostic breakdowns and metrics",
304
+ )
305
+ out_group.add_argument(
306
+ "-q",
307
+ "--quiet",
308
+ action="store_true",
309
+ help="Quiet mode: minimize console output, rely on exit code",
310
+ )
311
+ out_group.add_argument(
312
+ "--no-color",
313
+ action="store_true",
314
+ help="Disable colored output",
315
+ )
316
+ out_group.add_argument(
317
+ "--no-remediation",
318
+ action="store_true",
319
+ help="Hide remediation hints panel",
320
+ )
321
+
322
+ return parser
323
+
324
+
325
+ def build_checks_from_args(args: argparse.Namespace, default_suite: bool = True) -> List[BaseCheck]:
326
+ """Assemble list of check instances based on CLI flags."""
327
+ if args.timeout is None:
328
+ args.timeout = 6.0
329
+ checks: List[BaseCheck] = []
330
+
331
+ cpu_warn, cpu_crit = parse_threshold(args.cpu_threshold, (80.0, 95.0))
332
+ ram_warn, ram_crit = parse_threshold(args.ram_threshold, (85.0, 95.0))
333
+ disk_warn, disk_crit = parse_threshold(args.disk_threshold, (85.0, 92.0))
334
+
335
+ disks = args.disks or ["/"]
336
+
337
+ has_specific_check = any(
338
+ [
339
+ args.system,
340
+ args.disks,
341
+ args.ping,
342
+ args.tcp,
343
+ args.http,
344
+ args.tls,
345
+ args.ssh,
346
+ args.dns,
347
+ args.exec_cmds,
348
+ ]
349
+ )
350
+
351
+ # --all adds internet reachability on top of the local suite. With no flags
352
+ # at all, run only local system checks so the default never needs network.
353
+ if args.all or (default_suite and not has_specific_check):
354
+ checks.append(
355
+ SystemCheckGroup(
356
+ disk_paths=disks,
357
+ cpu_warn=cpu_warn,
358
+ cpu_crit=cpu_crit,
359
+ ram_warn=ram_warn,
360
+ ram_crit=ram_crit,
361
+ disk_warn=disk_warn,
362
+ disk_crit=disk_crit,
363
+ timeout=args.timeout,
364
+ )
365
+ )
366
+ if args.all:
367
+ checks.append(PingCheck(host="1.1.1.1", name="Ping (Cloudflare DNS 1.1.1.1)", count=args.ping_count, timeout_sec=args.timeout))
368
+ checks.append(PingCheck(host="8.8.8.8", name="Ping (Google DNS 8.8.8.8)", count=args.ping_count, timeout_sec=args.timeout))
369
+ checks.append(HTTPCheck(url="https://cloudflare.com", name="HTTP (Cloudflare)", timeout=args.timeout))
370
+ checks.append(TLSCheck(host="cloudflare.com", port=443, name="TLS Cert (cloudflare.com)", warn_days=args.tls_warn_days, crit_days=args.tls_crit_days, timeout=args.timeout))
371
+ return checks
372
+
373
+ # Specific system checks
374
+ if args.system or args.disks:
375
+ checks.append(
376
+ SystemCheckGroup(
377
+ disk_paths=disks,
378
+ cpu_warn=cpu_warn,
379
+ cpu_crit=cpu_crit,
380
+ ram_warn=ram_warn,
381
+ ram_crit=ram_crit,
382
+ disk_warn=disk_warn,
383
+ disk_crit=disk_crit,
384
+ timeout=args.timeout,
385
+ )
386
+ )
387
+
388
+ # Ping checks
389
+ if args.ping:
390
+ for host in args.ping:
391
+ checks.append(
392
+ PingCheck(
393
+ host=host,
394
+ count=args.ping_count,
395
+ timeout_sec=args.timeout,
396
+ )
397
+ )
398
+
399
+ # TCP checks
400
+ if args.tcp:
401
+ for target in args.tcp:
402
+ checks.append(
403
+ TCPCheck.from_target(
404
+ target=target,
405
+ timeout=args.timeout,
406
+ )
407
+ )
408
+
409
+ # HTTP checks
410
+ if args.http:
411
+ expected_status = parse_status_codes(args.http_status)
412
+ for url in args.http:
413
+ checks.append(
414
+ HTTPCheck(
415
+ url=url,
416
+ method=args.http_method,
417
+ expected_status=expected_status,
418
+ verify_ssl=not args.no_verify_ssl,
419
+ contains_text=args.http_match,
420
+ timeout=args.timeout,
421
+ )
422
+ )
423
+
424
+ # TLS checks
425
+ if args.tls:
426
+ for target in args.tls:
427
+ checks.append(
428
+ TLSCheck.from_target(
429
+ target=target,
430
+ warn_days=args.tls_warn_days,
431
+ crit_days=args.tls_crit_days,
432
+ timeout=args.timeout,
433
+ )
434
+ )
435
+
436
+ # SSH checks
437
+ if args.ssh:
438
+ for target in args.ssh:
439
+ checks.append(
440
+ SSHCheck.from_target(
441
+ target=target,
442
+ username=args.ssh_user,
443
+ key_path=args.ssh_key,
444
+ check_auth=args.ssh_auth,
445
+ timeout=args.timeout,
446
+ )
447
+ )
448
+
449
+ if args.dns:
450
+ for host in args.dns:
451
+ checks.append(DNSCheck(host=host, timeout=args.timeout))
452
+
453
+ if args.exec_cmds:
454
+ for cmd in args.exec_cmds:
455
+ checks.append(ExecCheck(command=cmd, timeout=args.timeout))
456
+
457
+ return checks
458
+
459
+
460
+ def _status_changes(prev: Dict[str, CheckStatus], report: MedicReport) -> List[str]:
461
+ """Describe per-check status transitions since the previous watch iteration."""
462
+ lines = []
463
+ for r in report.results:
464
+ key = f"{r.name}|{r.target}"
465
+ old = prev.get(key)
466
+ if old is not None and old != r.status:
467
+ lines.append(f"{r.name}: {old.value} -> {r.status.value} ({r.message})")
468
+ return lines
469
+
470
+
471
+ def _watch(runner: MedicRunner, args: argparse.Namespace, fail_on: str) -> int:
472
+ """Re-run the checks on an interval, rendering each report; Ctrl-C exits."""
473
+ interval = max(args.watch, 0.5)
474
+ fmt = OutputFormat(args.format)
475
+ console = Console(no_color=args.no_color)
476
+ live_screen = fmt == OutputFormat.RICH and console.is_terminal and not args.quiet
477
+ formatter = get_formatter(
478
+ fmt=fmt,
479
+ console=console,
480
+ verbose=args.verbose,
481
+ show_remediation=not args.no_remediation,
482
+ no_color=args.no_color,
483
+ )
484
+ prev: Dict[str, CheckStatus] = {}
485
+ code = 0
486
+ try:
487
+ while True:
488
+ report = runner.run()
489
+ code = report.exit_code_for(fail_on)
490
+ if live_screen:
491
+ console.clear()
492
+ if not args.quiet:
493
+ formatter.render(report)
494
+ for line in _status_changes(prev, report):
495
+ print(f"[change] {line}", file=sys.stderr)
496
+ prev = {f"{r.name}|{r.target}": r.status for r in report.results}
497
+ if live_screen:
498
+ console.print(f"[dim]Refreshing every {interval:g}s - Ctrl-C to quit[/dim]")
499
+ time.sleep(interval)
500
+ except KeyboardInterrupt:
501
+ return code
502
+
503
+
504
+ def main(argv: Optional[Sequence[str]] = None) -> int:
505
+ """Main CLI entry point."""
506
+ parser = build_parser()
507
+ argcomplete.autocomplete(parser)
508
+ args = parser.parse_args(argv)
509
+
510
+ if args.print_completion:
511
+ print(completion.script_for(args.print_completion))
512
+ return 0
513
+ if args.install_completion:
514
+ shell = completion.detect_shell()
515
+ if shell is None:
516
+ print("medic: cannot detect shell from $SHELL; use --completion {bash,zsh,fish}", file=sys.stderr)
517
+ return 2
518
+ path, note = completion.install(shell)
519
+ print(f"Installed {shell} completion: {path}")
520
+ print(note or "Open a new shell (or run `exec $SHELL`) to activate.")
521
+ return 0
522
+
523
+ settings: Dict[str, Any] = {}
524
+ config_checks: List[BaseCheck] = []
525
+ if args.config:
526
+ try:
527
+ settings, config_checks = load_config(args.config, args.timeout)
528
+ except ConfigError as exc:
529
+ print(f"medic: config error: {exc}", file=sys.stderr)
530
+ return 2
531
+
532
+ # Precedence: explicit CLI flag > config [settings] > built-in default.
533
+ if args.timeout is None:
534
+ args.timeout = float(settings.get("timeout", 6.0))
535
+ concurrency = args.concurrency if args.concurrency is not None else int(settings.get("concurrency", 8))
536
+ fail_on = args.fail_on or settings.get("fail_on", "failure")
537
+ stop_on_failure = args.stop_on_failure or bool(settings.get("stop_on_failure", False))
538
+ parallel = not args.no_parallel and bool(settings.get("parallel", True))
539
+
540
+ checks = config_checks + build_checks_from_args(args, default_suite=not args.config)
541
+ if not checks:
542
+ if not args.quiet:
543
+ print("No checks configured to run.", file=sys.stderr)
544
+ return 1
545
+
546
+ runner = MedicRunner(
547
+ checks=checks,
548
+ parallel=parallel,
549
+ max_workers=concurrency,
550
+ stop_on_failure=stop_on_failure,
551
+ )
552
+
553
+ if args.watch is not None:
554
+ return _watch(runner, args, fail_on)
555
+
556
+ report: MedicReport = runner.run()
557
+
558
+ if not args.quiet:
559
+ fmt = OutputFormat(args.format)
560
+ formatter = get_formatter(
561
+ fmt=fmt,
562
+ verbose=args.verbose,
563
+ show_remediation=not args.no_remediation,
564
+ no_color=args.no_color,
565
+ )
566
+ formatter.render(report)
567
+
568
+ return report.exit_code_for(fail_on)
569
+
570
+
571
+ if __name__ == "__main__":
572
+ sys.exit(main())
medic/completion.py ADDED
@@ -0,0 +1,46 @@
1
+ """Shell completion script generation and installation."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Optional, Tuple
6
+
7
+ import argcomplete
8
+
9
+ SHELLS = ("bash", "zsh", "fish")
10
+
11
+
12
+ def detect_shell() -> Optional[str]:
13
+ """Best-effort login shell detection from $SHELL."""
14
+ name = os.path.basename(os.environ.get("SHELL", ""))
15
+ return name if name in SHELLS else None
16
+
17
+
18
+ def script_for(shell: str) -> str:
19
+ return argcomplete.shellcode(["medic"], shell=shell)
20
+
21
+
22
+ def target_path(shell: str) -> Path:
23
+ """Directory/file the shell autoloads completions from, with no rc edits needed."""
24
+ home = Path.home()
25
+ if shell == "zsh":
26
+ # oh-my-zsh puts custom/completions on fpath; otherwise use the XDG-ish dir.
27
+ omz = Path(os.environ.get("ZSH", home / ".oh-my-zsh"))
28
+ if omz.is_dir():
29
+ return omz / "custom" / "completions" / "_medic"
30
+ return home / ".local" / "share" / "zsh" / "site-functions" / "_medic"
31
+ if shell == "fish":
32
+ return home / ".config" / "fish" / "completions" / "medic.fish"
33
+ # bash-completion lazily loads this directory on first <TAB> for `medic`.
34
+ data = Path(os.environ.get("XDG_DATA_HOME", home / ".local" / "share"))
35
+ return data / "bash-completion" / "completions" / "medic"
36
+
37
+
38
+ def install(shell: str) -> Tuple[Path, str]:
39
+ """Write the completion file; returns (path, note about any remaining step)."""
40
+ path = target_path(shell)
41
+ path.parent.mkdir(parents=True, exist_ok=True)
42
+ path.write_text(script_for(shell), encoding="utf-8")
43
+ note = ""
44
+ if shell == "zsh" and "oh-my-zsh" not in str(path):
45
+ note = f"Ensure {path.parent} is on your fpath (before compinit) in ~/.zshrc."
46
+ return path, note