Source code for fleetmesh_node.commands.base

"""Common helpers and base structures for meshnode CLI command providers."""
from __future__ import annotations

import argparse
import contextlib
import json
import os
import sys
import time
from typing import Any, Callable, Mapping, NoReturn, Optional, Sequence
from fleetmesh_node.interfaces import HealthStatusDict, NodeStatusDict
from fleetmesh_node import app as app_mod, storage
from fleetmesh_node.app import socket as control
from fleetmesh_core.wire import validate
from fleetmesh_core.identity.did import node_of_did
from fleetmesh_node.storage import grants as grants_mod
from fleetmesh_core.crypto.bech32 import bech32_decode, bech32_encode, bech32_polymod  # noqa: F401  (command modules import them from here)

TIERS: tuple[str, ...] = ('probation', 'member', 'trusted', 'anchor')

# Exit codes. Every command returns an int; meshnode.main exits with it.
OK = 0
# Something the operator asked for could not be done: a missing argument, a
# peer this node does not know, a daemon that is not running, a reply the
# daemon refused. Two rather than one so that it reads as "the request was
# wrong or could not be met" in the same register as argparse's own usage
# errors; one is reserved for commands whose job is to answer a yes/no
# question (`check`, `enclave verify`, `fips probe`) and said no.
FAILED = 2


[docs]def fail(msg: str, code: int = FAILED) -> NoReturn: """Say why on stderr and stop with `code`. The one way a command gives up.""" print(msg, file=sys.stderr) raise SystemExit(code)
[docs]def emit(a: argparse.Namespace, payload: Any, human: Callable[[Any], None] | None = None, indent: int | None = 2) -> int: """Print `payload` as JSON under --json, otherwise hand it to `human`. The JSON side is the contract scripts read, so it is produced here and nowhere else: `json.dumps(payload, indent=indent)` on one line of stdout per call. A command whose human rendering is long may pass no `human`, test `a.json` itself and `return emit(a, payload)` from the JSON branch. """ if getattr(a, 'json', False): print(json.dumps(payload, indent=indent)) elif human is not None: human(payload) return OK
[docs]def load_json_arg(value: str, what: str = 'argument', on_error: Callable[[str], Any] | None = None) -> Any: """A JSON argument given inline or as `@path` to a file holding it. A value that is not JSON fails the command naming `what`, unless `on_error` is given, in which case it decides what the raw text means. """ if value.startswith('@'): with open(value[1:], encoding='utf-8') as _fh: raw = _fh.read() else: raw = value try: return json.loads(raw) except ValueError as e: if on_error is not None: return on_error(raw) fail('%s is not JSON: %s' % (what, e))
[docs]def load_doc(path: str) -> Any: with open(path, encoding='utf-8') as _fh: text = _fh.read() if path.endswith(('.yaml', '.yml')): try: import yaml except ImportError: fail('reading %s needs pyyaml; give the manifest as JSON instead' % path) return yaml.safe_load(text) return json.loads(text)
[docs]def render_table(headers: Sequence[str], rows: Sequence[Sequence[Any]]) -> None: str_rows = [[str(c) for c in r] for r in rows] widths = [max(len(h), *(len(r[i]) for r in str_rows)) if str_rows else len(h) for i, h in enumerate(headers)] line = ' '.join(h.ljust(w) for h, w in zip(headers, widths)) print(line.rstrip()) for r in str_rows: print(' '.join(c.ljust(w) for c, w in zip(r, widths)).rstrip())
[docs]def format_when(epoch: int, window: int = 3600) -> str: return time.strftime('%Y-%m-%d %H:%M', time.gmtime(epoch * window))
[docs]def short_pk(pk: str | None) -> str: return (pk or '')[:16]
[docs]def get_grants_store(directory: str) -> grants_mod.GrantStore: return grants_mod.GrantStore(os.path.join(directory, 'grants.sqlite'))
[docs]def resolve_peer_arg(directory: str, arg: str) -> str: """A peer, from a pubkey, a DID, an npub, or an unambiguous prefix of a known one.""" arg = arg.strip() if arg.lower().startswith('did:'): try: return node_of_did(arg.lower()) except ValueError as e: fail(str(e)) if arg.lower().startswith('npub1'): raw = bech32_decode('npub', arg.lower()) if raw is not None and len(raw) == 32: return raw.hex() fail('%r is not a valid npub' % arg) if validate.hex64(arg.lower()): return arg.lower() known = set() try: known |= {g['peer'] for g in get_grants_store(directory).list()} except storage.store_errors(): pass try: cfg = app_mod.load_config(directory) known |= {p['pubkey'] for p in cfg.get('peers', []) if isinstance(p, dict) and 'pubkey' in p} known |= {pk for pk in (cfg.get('trust') or {}) if validate.hex64(pk)} except (OSError, ValueError): pass hits = sorted(pk for pk in known if pk.startswith(arg.lower())) if len(hits) == 1: return hits[0] if not hits: fail('%r is not a pubkey, a did:nostr, an npub, or a prefix of a peer this node knows' % arg) fail('%r matches %d peers: %s' % (arg, len(hits), ', '.join(h[:16] for h in hits)))
[docs]def resolve_peer_or_raw(a: argparse.Namespace, arg: str) -> str: """resolve_peer_arg when the command has a node directory to ask, else the argument as given. For transport commands, which also run without a node.""" directory = getattr(a, 'dir', None) if directory and os.path.exists(directory): return resolve_peer_arg(directory, arg) return arg
_DAEMON_CALLER: Optional[Callable[..., Any]] = None
[docs]def set_daemon_caller(caller: Optional[Callable[..., Any]]) -> None: """Set custom daemon caller implementation for testing without monkeypatching.""" global _DAEMON_CALLER _DAEMON_CALLER = caller
[docs]def reset_daemon_caller() -> None: """Clear custom daemon caller implementation.""" global _DAEMON_CALLER _DAEMON_CALLER = None
[docs]@contextlib.contextmanager def override_daemon(caller: Callable[..., Any]) -> Any: """Context manager to cleanly override daemon calls for tests.""" global _DAEMON_CALLER prev = _DAEMON_CALLER _DAEMON_CALLER = caller try: yield finally: _DAEMON_CALLER = prev
[docs]def ask_daemon(directory: str, cmd: str, **args: Any) -> Any: """One call over the control socket, or exit with the daemon's complaint. Can be cleanly intercepted in tests via `override_daemon(fake)` or `set_daemon_caller(fake)`. """ if _DAEMON_CALLER is not None: return _DAEMON_CALLER(directory, cmd, **args) try: return control.call(directory, cmd, **args) except control.ControlError as e: fail('%s' % e)
def _ask(directory: str, cmd: str, **args: Any) -> Any: return ask_daemon(directory, cmd, **args)
[docs]def try_ask(directory: str, cmd: str, **args: Any) -> Any: """One call over the control socket, or None when the node is not there or declined. For best-effort fan-out, where one silent node must not stop the command.""" if not control.running(directory): return None try: return control.call(directory, cmd, **args) except control.ControlError: return None
def _live(a: argparse.Namespace, cmd: str, args: Mapping[str, Any] | None = None, timeout: float = 10) -> Any: """Ask the running node, or fall back to what it last wrote.""" if control.running(a.dir): try: return control.call(a.dir, cmd, timeout=timeout, **(args or {})) except control.ControlError: pass return None
[docs]def read_status_file(directory: str) -> NodeStatusDict: path = os.path.join(directory, 'status.json') if not os.path.exists(path): fail('no status.json in %s; is the node running?' % directory) with open(path, encoding='utf-8') as _fh: return json.load(_fh)
[docs]def status_health(directory: str) -> HealthStatusDict: """The health block of the last status.json, or {} when it has none.""" return read_status_file(directory).get('health') or {}
[docs]def extract_trouble(health: HealthStatusDict | Mapping[str, Any] | None) -> list[str]: h = health or {} out = list(h.get('subsystem_trouble') or []) if h.get('config_error'): out.append('config.json rejected, last good one in force: %s' % h['config_error']) for k in ('handler_failures', 'tick_failures'): if h.get(k): out.append('%s: %d%s' % (k.replace('_', ' '), h[k], (' (last: %s)' % h['last_tick_error']) if k == 'tick_failures' and h.get('last_tick_error') else '')) if h.get('rejected'): out.append('messages rejected at the door: %d' % sum(h['rejected'].values())) if h.get('subsystem_trouble') is not None: return out down = [u for u, r in (h.get('relays') or {}).items() if not r.get('connected')] if down: out.append('relay subscription down: %s' % ', '.join(down)) if h.get('sessions_refused'): out.append('sync sessions refused: %d' % h['sessions_refused']) if h.get('receipts_refused'): out.append('receipts refused over a grant disagreement: %d - every window this peering ' 'closes will be active silence until it is resolved' % len(h['receipts_refused'])) return out
# The short names the command modules were written against. They are defined # once, here; nothing else re-exports them (meshnode.py used to, and a test # reaching through that copy is what kept a sys.modules hack alive in _ask). _load_doc = load_doc _bech32 = bech32_encode _bech32_decode = bech32_decode _bech32_polymod = bech32_polymod _table = render_table _when = format_when _short = short_pk _grants = get_grants_store _peer = resolve_peer_arg _status_file = read_status_file _trouble = extract_trouble EXPERIMENTAL_NOTE = ('Experimental in the alpha: present and tested, but not supported, ' 'and it may change or go away.')
[docs]def add_command(sub: argparse._SubParsersAction, name: str, fn: Any, help: str, peer: bool = False, js: bool = False, experimental: bool = False) -> argparse.ArgumentParser: """A subcommand taking DIR. `experimental` marks it in `meshnode --help` and says what that means in its own --help (ALPHA.md lists what is experimental).""" if experimental: p = sub.add_parser(name, help='(experimental) ' + help, description='%s. %s' % (help[0].upper() + help[1:], EXPERIMENTAL_NOTE)) else: p = sub.add_parser(name, help=help) p.add_argument('dir') if peer: p.add_argument('peer', help='pubkey, did:nostr, or a prefix of a peer this node knows') if js: p.add_argument('--json', action='store_true', help='print the structure, for scripts') p.set_defaults(fn=fn) return p