8.2 KiB
8.2 KiB
Gate 3 — Program Design: linux-connector
1. Directory & File Layout
linux-connector/
├── bin/
│ └── linux-connector # Executable launcher (#!/usr/bin/env python3)
├── linux_connector/
│ ├── __init__.py # Version constant (__version__ = "1.0.0")
│ ├── __main__.py # Entrypoint for `python3 -m linux_connector`
│ ├── cli.py # Argument parsing and command routing
│ ├── config.py # Config loader (~/.config/linux-connector/config.json)
│ ├── models.py # HostEntry, HostGroup, ExecResult dataclasses
│ ├── inventory/
│ │ ├── __init__.py
│ │ ├── ssh_config.py # OpenSSH config file parser
│ │ ├── custom_loader.py # YAML/JSON inventory loader
│ │ └── resolver.py # Host & group query resolver
│ ├── tui/
│ │ ├── __init__.py
│ │ ├── selector.py # Pure ANSI terminal interactive menu
│ │ ├── fuzzy.py # Lightweight in-memory fuzzy search matcher
│ │ └── fzf_backend.py # Optional delegation to external `fzf`
│ ├── runner/
│ │ ├── __init__.py
│ │ ├── executor.py # Multi-host concurrent command dispatcher
│ │ ├── streamer.py # Real-time prefixed line printer
│ │ └── summary.py # Execution summary table formatter
│ └── network/
│ ├── __init__.py
│ ├── prober.py # Non-blocking TCP port 22 socket latency probe
│ └── tunnel.py # SSH port-forwarding orchestrator
│ └── completion.py # Dynamic host/group completion resolver & generator
├── completions/
│ ├── bash/
│ │ └── linux-connector # Native Bash tab completion script
│ └── zsh/
│ └── _linux-connector # Native Zsh tab completion function
├── packaging/
│ ├── build_packages.py # Standalone .deb, .rpm and .tar.gz generator
│ ├── install.sh # Tarball installer script
│ ├── deb/
│ └── rpm/
├── docs/
│ ├── user-guide.md # End-user operator & interactive guide
│ ├── admin-guide.md # Fleet inventory & automation admin guide
│ ├── developer-guide.md # Architecture, parser & TUI developer guide
│ └── plans/
│ └── linux-connector/ # Software Factory planning artifacts
├── man/
│ └── linux-connector.1 # Complete Section 1 UNIX man page
├── tests/
│ ├── __init__.py
│ ├── test_cli.py
│ ├── test_ssh_config.py
│ ├── test_resolver.py
│ ├── test_fuzzy.py
│ ├── test_executor.py
│ ├── test_prober.py
│ └── fixtures/
│ ├── mock_ssh_config
│ └── mock_inventory.json
└── .gitea/
└── workflows/
└── release.yml # Gitea Actions CI/CD pipeline
2. Key Type Signatures & Interfaces (No Bodies)
# models.py
from typing import Dict, List, Optional, Any
from dataclasses import dataclass
@dataclass
class HostEntry:
name: str
hostname: str
user: Optional[str] = None
port: int = 22
identity_file: Optional[str] = None
proxy_jump: Optional[str] = None
groups: List[str] = None
tags: List[str] = None
description: Optional[str] = None
latency_ms: Optional[float] = None
is_reachable: Optional[bool] = None
@dataclass
class ExecResult:
host: str
exit_code: int
duration_sec: float
stdout: str
stderr: str
is_timeout: bool = False
error_message: Optional[str] = None
# inventory/ssh_config.py
class SshConfigParser:
def __init__(self, config_paths: Optional[List[str]] = None): ...
def parse(self) -> List[HostEntry]: ...
# inventory/resolver.py
class InventoryResolver:
def __init__(self, hosts: List[HostEntry]): ...
def resolve_targets(
self,
target_patterns: Optional[List[str]] = None,
group_names: Optional[List[str]] = None,
tag_filters: Optional[List[str]] = None,
) -> List[HostEntry]: ...
# network/prober.py
class SocketProber:
def __init__(self, timeout_sec: float = 1.0): ...
def probe_host(self, host: HostEntry) -> HostEntry: ...
def probe_all_concurrent(self, hosts: List[HostEntry], max_workers: int = 20) -> List[HostEntry]: ...
# runner/executor.py
class ConcurrentCommandRunner:
def __init__(self, concurrency: int = 10, timeout_sec: int = 60): ...
def execute_fleet(
self,
hosts: List[HostEntry],
command: str,
live_stream: bool = True,
sudo: bool = False,
) -> List[ExecResult]: ...
# tui/selector.py
class InteractiveHostSelector:
def __init__(self, hosts: List[HostEntry]): ...
def select_host(self) -> Optional[HostEntry]: ...
3. Call Stack Trace
connect (Interactive mode):
cli.main()detects no arguments (orconnectsub-command).inventory.ssh_config.SshConfigParserparses~/.ssh/config.inventory.custom_loadermerges tags/groups from~/.config/linux-connector/hosts.yaml.network.prober.SocketProberstarts fast background worker threads to check TCP port 22 reachability.tui.selector.InteractiveHostSelectorcaptures terminal raw mode (ANSI) and handles arrow keys and fuzzy input (or delegates tofzfif detected).- User hits
Enteron selected host. - Terminal raw mode is cleanly released.
- Python builds
/usr/bin/sshparameter vector and callsos.execvp("ssh", args).
exec (Parallel command runner):
cli.main()parsesexec -g k8s "uptime".inventory.resolver.InventoryResolverfinds all hosts taggedk8s.runner.executor.ConcurrentCommandRunnerdispatches worker threads viaThreadPoolExecutor.runner.streamer.Streamertags incoming lines with colored host labels and flushes to stdout.runner.summary.print_summary_table()displays execution results, failed hosts, and durations.- Returns exit code
0if all succeeded,1if any failed.
4. Test Plan & Assertions
test_ssh_config.py: Verifies parsing of multi-stanza~/.ssh/configfiles (handles wildcards, comments, indented options,ProxyJump, andIncludedirectives).test_resolver.py: Verifies resolution by exact name, wildcard pattern (k8s-*), group, or comma-separated lists.test_fuzzy.py: Verifies scoring algorithm filters matching hosts correctly on partial/subsequence typing.test_executor.py: Uses a local mock SSH echo command to verify concurrent thread execution, line interleaving safety, and timeout handling.test_prober.py: Verifies non-blocking TCP socket timeout handling against unreachable IP addresses.
5. Least Confident Decisions (Adversarial Check)
- Complex
~/.ssh/configwith dynamic tokens: Some SSH configurations use%h,%p, orMatch execdirectives.- Mitigation: The parser handles standard
Host,HostName,User,Port,IdentityFile,ProxyJump. For edge-case directives, the final handover uses nativessh <HostAlias>, letting native OpenSSH evaluate dynamic Match expressions at runtime.
- Mitigation: The parser handles standard
- Terminal Raw Mode cleanup on unexpected signals: If a user presses
Ctrl+\or the process is killed withSIGTERMduring interactive menu navigation, terminal echo could be left disabled.- Mitigation: Wrap all TUI raw mode blocks in strict
try ... finally: termios.tcsetattr(...)blocks and install signal handlers forSIGINTandSIGTERM.
- Mitigation: Wrap all TUI raw mode blocks in strict
- Multi-host
sudocommands prompting for password:- Mitigation: By default, multi-host commands require passwordless sudo (
NOPASSWD) or an active SSH session key. Add an explicit--ask-sudo-passflag that securely reads a password once and feeds it via stdin (sudo -S -p '').
- Mitigation: By default, multi-host commands require passwordless sudo (