Files
linux-connector/docs/plans/linux-connector/03-program-design.md
T

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):

  1. cli.main() detects no arguments (or connect sub-command).
  2. inventory.ssh_config.SshConfigParser parses ~/.ssh/config.
  3. inventory.custom_loader merges tags/groups from ~/.config/linux-connector/hosts.yaml.
  4. network.prober.SocketProber starts fast background worker threads to check TCP port 22 reachability.
  5. tui.selector.InteractiveHostSelector captures terminal raw mode (ANSI) and handles arrow keys and fuzzy input (or delegates to fzf if detected).
  6. User hits Enter on selected host.
  7. Terminal raw mode is cleanly released.
  8. Python builds /usr/bin/ssh parameter vector and calls os.execvp("ssh", args).

exec (Parallel command runner):

  1. cli.main() parses exec -g k8s "uptime".
  2. inventory.resolver.InventoryResolver finds all hosts tagged k8s.
  3. runner.executor.ConcurrentCommandRunner dispatches worker threads via ThreadPoolExecutor.
  4. runner.streamer.Streamer tags incoming lines with colored host labels and flushes to stdout.
  5. runner.summary.print_summary_table() displays execution results, failed hosts, and durations.
  6. Returns exit code 0 if all succeeded, 1 if any failed.

4. Test Plan & Assertions

  • test_ssh_config.py: Verifies parsing of multi-stanza ~/.ssh/config files (handles wildcards, comments, indented options, ProxyJump, and Include directives).
  • 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)

  1. Complex ~/.ssh/config with dynamic tokens: Some SSH configurations use %h, %p, or Match exec directives.
    • Mitigation: The parser handles standard Host, HostName, User, Port, IdentityFile, ProxyJump. For edge-case directives, the final handover uses native ssh <HostAlias>, letting native OpenSSH evaluate dynamic Match expressions at runtime.
  2. Terminal Raw Mode cleanup on unexpected signals: If a user presses Ctrl+\ or the process is killed with SIGTERM during 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 for SIGINT and SIGTERM.
  3. Multi-host sudo commands prompting for password:
    • Mitigation: By default, multi-host commands require passwordless sudo (NOPASSWD) or an active SSH session key. Add an explicit --ask-sudo-pass flag that securely reads a password once and feeds it via stdin (sudo -S -p '').