Source code for fleetmesh_node.commands.core

"""Core node lifecycle, health, identity, and operator diagnostics."""
from __future__ import annotations

import argparse
import json
import os
import signal
import stat
import time
from typing import Any, Mapping, MutableMapping, Optional, TypedDict, cast

from fleetmesh_core.identity import identity
from fleetmesh_node import app as app_mod, keystore, storage
from fleetmesh_node.app import control as control_verbs, enrol as enrol_mod, groups as groups_mod, socket as control
from fleetmesh_core.wire import validate
from fleetmesh_node import release as release_mod
from fleetmesh_node.interfaces import VisibilityState


[docs]class EnrolCli(control_verbs.EnrolResult): """What `meshnode enrol` prints: the daemon's reply, or the file-based one.""" live: bool # True: the running node did it over the control socket
[docs]class WhoamiDescriptorSummary(TypedDict, total=False): id: str pow_bits: int expires: Optional[int] protocol: Optional[str] implements: list[str]
[docs]class FaceDict(TypedDict, total=False): host: str port: int
[docs]class EndpointDict(TypedDict, total=False): transport: str address: str ticket: str priority: int
WhoamiReport = TypedDict('WhoamiReport', { 'did': str, 'pubkey': str, 'npub': str, 'agreement': str, 'transport': str, 'config_error': Optional[str], 'descriptor': Optional[WhoamiDescriptorSummary], 'running': bool, 'class': Optional[str], 'name': Optional[str], 'operator': Optional[str], 'relays': list[str], 'face': FaceDict, 'endpoints': list[EndpointDict], }, total=False) from .base import ( _ask, _bech32, _live, _load_doc, _short, _status_file, _table, _trouble, _when, add_command, emit, fail, status_health, )
[docs]def cmd_init(a: argparse.Namespace) -> int: cfg: MutableMapping[str, Any] if a.manifest: cfg = dict(app_mod.config_from_manifests(_load_doc(a.manifest), [_load_doc(p) for p in a.peering or []])) else: # No --operator is fresh hardware: the descriptor goes out with no # operator tag and `meshnode enrol` joins a fleet later (plan D18/D19). cfg = dict(app_mod.defaults()) cfg.update({'class': a.node_class, 'operator': a.operator or None}) cfg['relays'] = list(a.relay or cfg.get('relays') or []) if a.endpoint: cfg['endpoints'] = [] for e in a.endpoint: scheme, _, rest = e.partition('=') addr, _, pref = rest.rpartition(':') if rest.count(':') > 1 and rest.rsplit(':', 1)[1].isdigit() else (rest, '', '50') cfg['endpoints'].append({'transport': scheme, 'address': addr, 'priority': int(pref or 50)}) if a.face_port is not None: cfg['face'] = {'host': a.face_host, 'port': a.face_port} if a.pow_bits is not None: cfg['pow_bits'] = a.pow_bits cfg['name'] = a.name or os.path.basename(os.path.abspath(a.dir)) problems = app_mod.validate_config(cfg) if problems: fail('refusing to write a config the node could not run on:\n ' + '\n '.join(problems)) had_keys = os.path.exists(os.path.join(a.dir, keystore.FILE)) if had_keys and os.path.exists(os.path.join(a.dir, 'config.json')): # A node already. init is what a deploy runs on every pass, and a pass # that changes nothing must say so rather than re-mine and republish # a descriptor the relays already hold. ks = keystore.Keystore.load(a.dir) return emit(a, {'action': 'init', 'changed': False, 'did': ks.did, 'pubkey': ks.node_pk, 'config': os.path.join(a.dir, 'config.json')}, lambda _: print('already a node: %s (%s); config.json left as it is' % (ks.did, a.dir))) app_mod.save_config(a.dir, cfg) ks = keystore.Keystore.load_or_generate(a.dir) told: dict[str, tuple[bool, str]] = {} node = app_mod.NodeApp(a.dir, cfg) node.face.start() try: desc = node.build_descriptor() if cfg['relays']: from fleetmesh_node.protocols.nostr import client as relay told = dict(relay.publish_all(cfg['relays'], desc)) finally: node.face.stop() # No relay took it: none configured, none reachable, or - a node that is # its own relay - its face is not serving until `meshnode run`. Leave it # pending, so the first start publishes it instead of believing it had. unpublished = node.public_descriptor() is not None and not any(okay for okay, _ in told.values()) if unpublished: with open(os.path.join(a.dir, app_mod.NodeApp.PENDING_FILE), 'w', encoding='utf-8') as f: f.write(desc['id'] + '\n') nonce = [t for t in desc['tags'] if t[0] == 'nonce'] def human(_: Any) -> None: print('keys %s' % os.path.join(a.dir, keystore.FILE)) print('did %s' % ks.did) print('agreement %s' % ks.multikeys()['agreement']) print('transport %s' % ks.multikeys()['transport']) print('descriptor %s (%d tags, pow %s)' % (desc['id'], len(desc['tags']), nonce[0][2] if nonce else 'none')) if told: for url, (okay, note) in told.items(): print(' %-8s %s %s' % ('sent' if okay else 'FAILED', url, note)) else: print(' no relays configured; the descriptor is not published yet') if unpublished and told: print(' no relay accepted it yet; the first `meshnode run` publishes it') print('config %s' % os.path.join(a.dir, 'config.json')) return emit(a, {'action': 'init', 'changed': True, 'did': ks.did, 'pubkey': ks.node_pk, 'descriptor': desc['id'], 'pow': nonce[0][2] if nonce else None, 'published': {u: {'ok': okay, 'note': note} for u, (okay, note) in told.items()}, 'config': os.path.join(a.dir, 'config.json')}, human)
[docs]def cmd_run(a: argparse.Namespace) -> int: if not os.path.isfile(os.path.join(a.dir, 'config.json')): fail('%s has no config.json; run `meshnode init` first' % a.dir) if control.running(a.dir): try: control.call(a.dir, 'health', timeout=5) except control.ControlError: pass # a stale socket from a node that died; the server replaces it else: fail('a node is already running in %s' % a.dir) try: node = app_mod.NodeApp(a.dir).start() except (app_mod.ConfigError, PermissionError, ValueError) as e: fail(str(e)) print('meshnode %s' % node.ks.did) print(' relay face %s' % node.face.url) print(' relays %s' % (', '.join(node.relays) or '(none)')) print(' peers %d configured' % len(node.cfg.get('peers', []))) print(' control %s' % node.control.path) stop = lambda *_: node.stop() signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) try: node.run() finally: node.stop() return 0
[docs]def cmd_status(a: argparse.Namespace) -> int: st = _live(a, 'status') or _status_file(a.dir) if a.json: return emit(a, st) age = int(time.time()) - int(st.get('at', 0)) print('%s class %s written %ds ago%s' % (st.get('did'), st.get('class'), age, ' (STALE: is the node running?)' if age > 300 else '')) rel = st.get('release') or {} if rel: print('%s %s (%s%s)' % (rel.get('name'), rel.get('version'), rel.get('source'), ', ' + rel['commit'][:12] if rel.get('commit') else '')) print('relay face %s relays %s' % (st.get('face'), ', '.join(st.get('relays') or []) or '(none)')) print('descriptor %s events stored %s' % (_short(st.get('descriptor')) + '…', st.get('events_stored'))) rows = [(g['peer'], g['direction'], g['tier'], g['status']) for g in st.get('grants', [])] if rows: print('\ngrants') _table(('peer', 'direction', 'tier', 'status'), rows) if st.get('pending_grants'): print('\nwaiting for the boundary') _table(('peer', 'tier', 'from window'), [(p['peer'], p['tier'], '%s (%s UTC)' % (p['from_epoch'], _when(p['from_epoch']))) for p in st['pending_grants']]) ev = st.get('evaluations') or [] if ev: print('\nlast windows priced') _table(('peer', 'window', 'closed', 'severity', 'state'), [(e['peer'], e['epoch'], _when(e['epoch'] + 1), e['severity'], e['state']) for e in ev[-6:]]) rp = st.get('repriced') or [] if rp: # A window read again because the subject's receipt for it arrived # after the grace had run. Shown because an operator who sees a # severity change with no new traffic has nowhere else to look. print('\nrepriced after a late receipt') _table(('peer', 'window', 'was', 'now', 'remedy'), [(r['peer'], r['epoch'], r['was'], r['severity'], 'cancelled' if r['remedy_cancelled'] else 'stands') for r in rp]) print('\nreports published %s findings pending %s sessions refused %s' % (st.get('reports_published'), st.get('pending_findings'), st.get('refused_sessions'))) if st.get('last_tick'): print('last tick: ' + '; '.join(' '.join(_short(x) if validate.hex64(x) else x for x in d) for d in st['last_tick'])) trouble = _trouble(st.get('health')) print('\n' + ('\n'.join('!! ' + t for t in trouble) if trouble else 'no trouble reported')) return 0
[docs]def cmd_health(a: argparse.Namespace) -> int: h = _live(a, 'health') live = h is not None if h is None: h = status_health(a.dir) if a.json: return emit(a, h) print('from %s' % ('the running node' if live else 'status.json (the node is not answering)')) for url, r in (h.get('relays') or {}).items(): print('relay %s: %s, reconnects %s%s%s' % ( url, 'up' if r.get('connected') else 'DOWN', r.get('reconnects'), (', last event %ds ago' % (int(time.time()) - r['last_event_at'])) if r.get('last_event_at') else ', no event yet', (', last error: %s' % r['last_error']) if r.get('last_error') else '')) print('inbox %s unfinished envelopes %s sessions open %s refused %s awaiting ack %s' % ( h.get('inbox'), h.get('unfinished_envelopes'), h.get('sessions_open'), h.get('sessions_refused'), len(h.get('awaiting_ack') or []))) if h.get('unacknowledged'): # The publish said OK and the peer, who has spoken since, never said # it arrived. This is the relay dropping the stored path, and it is # the one fault the transport could not see until it asked. print('stored messages never acknowledged by a peer that has spoken since:') for u in h['unacknowledged']: print(' %s %s sent %s UTC, peer heard %s UTC, via %s' % ( u['peer'], u['type'].rpartition('/')[2], time.strftime('%m-%d %H:%M', time.gmtime(u['at'])), time.strftime('%m-%d %H:%M', time.gmtime(u['heard_at'])) if u.get('heard_at') else '?', ', '.join(u.get('relays') or []) or 'no relay')) if h.get('throttled'): print('throttled, so quiet is expected until the window turns:') for t in h['throttled']: print(' %s %s: %s, until %s UTC' % ( t['peer'][:16], t.get('shard', ''), t.get('why', ''), time.strftime('%H:%M', time.gmtime(t['until'])) if t.get('until') else '?')) if h.get('receipts_refused'): print('receipts refused because the two ends disagree about which grant is current:') for r in h['receipts_refused']: print(' %s window %s named %s, this node would take %s' % ( r['peer'], r['window'], r['named'], ' or '.join(r['acceptable']) or '(none)')) for label, key in (('dropped by the transport', 'dropped'), ('rejected at the door', 'rejected'), ('rejected by the budget', 'budget_rejected')): if h.get(key): print('%s:' % label) for k, v in sorted(h[key].items(), key=lambda kv: -kv[1]): print(' %6d %s' % (v, k)) print('handler failures %s tick failures %s%s' % ( h.get('handler_failures'), h.get('tick_failures'), (' last: %s' % h['last_tick_error']) if h.get('last_tick_error') else '')) if h.get('config_error'): print('config.json REJECTED, last good one in force: %s' % h['config_error']) trouble = _trouble(h) print('\n' + ('\n'.join('!! ' + t for t in trouble) if trouble else 'no trouble reported')) return 0
[docs]def cmd_whoami(a: argparse.Namespace) -> int: try: ks = keystore.Keystore.load(a.dir) except (OSError, ValueError, PermissionError) as e: fail('cannot read the keys: %s' % e) cfg, cfg_error = None, None try: cfg = app_mod.load_config(a.dir) except (OSError, ValueError) as e: cfg_error = str(e) who: WhoamiReport = {'did': ks.did, 'pubkey': ks.node_pk, 'npub': _bech32('npub', bytes.fromhex(ks.node_pk)), 'agreement': ks.multikeys()['agreement'], 'transport': ks.multikeys()['transport'], 'config_error': cfg_error, 'descriptor': None, 'running': control.running(a.dir)} if cfg: who.update({'class': cfg.get('class'), 'name': cfg.get('name'), 'operator': cfg.get('operator'), 'relays': cfg.get('relays') or [], 'face': cfg.get('face', {}), 'endpoints': cfg.get('endpoints') or []}) dpath = os.path.join(a.dir, app_mod.NodeApp.DESCRIPTOR_FILE) if os.path.exists(dpath): with open(dpath, encoding='utf-8') as _fh: d = json.load(_fh) desc: WhoamiDescriptorSummary = { 'id': d['id'], 'pow_bits': identity.pow_bits(d['id']), 'expires': next((int(t[1]) for t in d['tags'] if t[0] == 'expiration'), None), 'protocol': next((t[1] for t in d['tags'] if t[0] == 'protocol'), None), 'implements': [t[1] for t in d['tags'] if t[0] == 'c' and len(t) > 1]} who['descriptor'] = desc if a.json: return emit(a, who) if cfg_error: print('config unreadable: %s' % cfg_error) print('did %s' % who['did']) print('pubkey %s' % who['pubkey']) print('npub %s' % who['npub']) print('agreement %s' % who['agreement']) print('transport %s' % who['transport']) if cfg: print('class %s name %s operator %s' % (cfg.get('class'), cfg.get('name'), _short(cfg.get('operator')) + '…')) print('relays %s' % (', '.join(cfg.get('relays') or []) or '(none)')) print('face ws://%s:%s' % (cfg.get('face', {}).get('host'), cfg.get('face', {}).get('port'))) print('endpoints %s' % (', '.join('%s=%s' % (e['transport'], e['address']) for e in cfg.get('endpoints') or []) or '(none: reachable over the nostr transport only)')) shown: WhoamiDescriptorSummary | None = who['descriptor'] if shown: print('descriptor %s pow %d bits expires %s protocol %s' % (shown['id'], shown['pow_bits'], time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(shown['expires'])) if shown['expires'] else '?', (shown['protocol'] or '')[:8] + '…')) print('implements %s' % ', '.join('/'.join(c.rstrip('/').rsplit('/', 2)[-2:]) if '/' in c else c for c in shown['implements'])) else: print('descriptor none yet (mined on the first run)') print('running %s' % ('yes' if who['running'] else 'no')) return 0
[docs]def cmd_check(a: argparse.Namespace) -> int: """Everything that would stop `run`, named at once. Exits 1 when it cannot.""" problems, notes = [], [] if not os.path.isdir(a.dir): fail('%s is not a directory' % a.dir) kpath = os.path.join(a.dir, keystore.FILE) if not os.path.exists(kpath): problems.append('no %s (run `meshnode init`)' % keystore.FILE) else: mode = stat.S_IMODE(os.stat(kpath).st_mode) if mode & 0o077: problems.append('%s is mode %o; it must be 0600' % (keystore.FILE, mode)) else: try: keystore.Keystore.load(a.dir) notes.append('keys load') except (ValueError, PermissionError, OSError) as e: problems.append('keys do not load: %s' % e) cpath = os.path.join(a.dir, 'config.json') if not os.path.exists(cpath): problems.append('no config.json (run `meshnode init`)') else: try: cfg = app_mod.load_config(a.dir) notes.append('config.json is valid: class %s, %d relay(s), %d peer(s), %d shard(s) claimed' % (cfg['class'], len(cfg['relays']), len(cfg.get('peers', [])), len(cfg.get('coverage', [])))) if not cfg['relays']: notes.append('no relays: the descriptor is not published and no peer can reach this node') except app_mod.ConfigError as e: problems.extend(str(e).replace('config.json: ', '').split('; ')) except ValueError as e: problems.append('config.json is not JSON: %s' % e) dpath = os.path.join(a.dir, app_mod.NodeApp.DESCRIPTOR_FILE) if os.path.exists(dpath): try: with open(dpath, encoding='utf-8') as _fh: d = json.load(_fh) proto = next((t for t in d['tags'] if t[0] == 'protocol'), None) from fleetmesh_node.protocols.nostr import descriptor as _d if proto and proto[2] != _d.DIGEST: notes.append('descriptor.json declares digest %s…, this code is %s…: it will be re-mined on the next run' % (proto[2][:8], _d.DIGEST[:8])) else: notes.append('descriptor.json matches this code\'s digest') except (ValueError, KeyError, IndexError) as e: problems.append('descriptor.json is unreadable: %s' % e) # Soundness asked of the dialect rather than run as a PRAGMA here: # `quick_check` is SQLite's, and a file-integrity check is a file-backed # idea. A server backend answers for its own soundness. for db in ('events.sqlite', 'grants.sqlite', 'accounts.sqlite'): p = os.path.join(a.dir, db) if os.path.exists(p): try: st = storage.SqliteStore(p, readonly=True) try: bad = st.integrity_check() finally: st.close() if bad: problems.append('%s: %s' % (db, bad)) except Exception as e: problems.append('%s does not open: %s' % (db, e)) notes.append('a node is %srunning here' % ('' if control.running(a.dir) else 'not ')) if a.json: emit(a, {'ok': not problems, 'problems': problems, 'notes': notes}) return 1 if problems else 0 for n in notes: print(' ' + n) for p in problems: print('!! ' + p) print('\n%s' % ('this directory can run' if not problems else '%d problem(s)' % len(problems))) return 1 if problems else 0
[docs]def cmd_enrol(a: argparse.Namespace) -> int: """Join a fleet with an fmenrol1 token minted for THIS node (plan D18/D19). With the node running the daemon does it (verify, config, descriptor, heartbeat go out at once); otherwise the same decision runs here against the files, and the next `run` mines the descriptor with the new operator. `meshnode whoami` shows the pubkey the operator mints for.""" token = a.token.strip() out: EnrolCli if control.running(a.dir): reply: control_verbs.EnrolResult = _ask(a.dir, 'enrol', token=token, force=bool(a.force)) out = EnrolCli(live=True, **reply) else: try: ks = keystore.Keystore.load(a.dir) app_mod.load_config(a.dir) # validated as the node would see it path = os.path.join(a.dir, 'config.json') with open(path, encoding='utf-8') as _fh: raw: MutableMapping[str, Any] = json.load(_fh) except (OSError, ValueError, PermissionError) as e: fail('cannot read the node: %s' % e) try: ledger = groups_mod.GroupLedger(os.path.join(a.dir, groups_mod.FILE)) res = enrol_mod.enrol_config(raw, token, ks.node_pk, int(time.time()), bool(a.force), ledger=ledger) except enrol_mod.EnrolRefused as e: fail('refused %s%s' % (e.code, (': ' + e.detail) if e.detail else '')) if res['changed']: app_mod.save_config(a.dir, raw) ledger.save() out = EnrolCli(live=False, descriptor=None, heartbeat=None, relays={}, **res) if a.json: return emit(a, out) if not out['changed']: print('already enrolled under %s (grant %s…); nothing to do' % (out['operator'], out['token_id'][:16])) return 0 print('enrolled under %s fleet %s' % (out['operator'], out['fleet'])) print('grant %s (a kind 30833 naming it undoes this)' % out['token_id']) if out.get('previous_operator'): print('left %s%s' % (out['previous_operator'], ' (forced)' if out.get('forced') else '')) if out['live']: print('descriptor %s… heartbeat %s relays %s' % ( str(out.get('descriptor'))[:16], (str(out.get('heartbeat'))[:16] + '…') if out.get('heartbeat') else '(none)', ', '.join('%s %s' % (u, 'ok' if r[0] else r[1]) for u, r in (out.get('relays') or {}).items()) or '(none)')) else: print('config.json written; the node was not running, so the next `meshnode run` publishes the new descriptor') return 0
[docs]def cmd_network(a: argparse.Namespace) -> int: """Ask an `approved` private network to admit this node (plan D26/H4). The running node fetches the current definition from the relays it knows, refuses locally if the policy is not `approved` or the roster already names this node, then publishes a sealed join-request to the definition's own relays. The ask is tracked: `meshnode status` shows it pending until a definition naming the node appears, or a join-decline arrives.""" if a.action != 'join': fail('unknown action %r (only `join`)' % a.action) if not control.running(a.dir): fail('the node must be running to join a network: it fetches the definition and publishes the request') reply = _ask(a.dir, 'network.join', network=a.network, note=(a.note or '')) if a.json: return emit(a, reply) if reply.get('refused'): fail('refused %s' % reply['refused']) print('asked %s to admit this node' % reply.get('network')) print(' request %s status %s' % (reply.get('id'), reply.get('status'))) for url, res in (reply.get('published') or {}).items(): print(' %s %s%s' % (url, 'ok' if res[0] else 'FAILED', (' - ' + str(res[1])) if res[1] else '')) return 0
def _visibility_resolved(cfg_vis: Any, tags: Any) -> VisibilityState: """The resolved visibility from a raw block and a descriptor's tags.""" from fleetmesh_node.config import VisibilityConfig from fleetmesh_node.planes.identity import visibility vis = VisibilityConfig.from_dict(cfg_vis) if isinstance(cfg_vis, dict) else VisibilityConfig() protocols: dict[str, str] = {} capabilities: dict[str, str] = {} for t in tags or (): if isinstance(t, list) and t and t[0] == 'c' and len(t) > 1: unit = str(t[1]) (protocols if unit.startswith('https://') else capabilities)[unit] = visibility.resolve( vis.default, vis.overrides, unit) return {'default': vis.default, 'overrides': dict(vis.overrides), 'public': visibility.has_public_presence(vis.default, vis.overrides), 'protocols': protocols, 'capabilities': capabilities} def _visibility_from_files(directory: str) -> VisibilityState: """Resolved visibility from config.json and (if present) descriptor.json.""" try: cfg = dict(app_mod.load_config(directory)) except (OSError, ValueError): cfg = {} tags: Any = [] path = os.path.join(directory, 'descriptor.json') if os.path.exists(path): try: with open(path, encoding='utf-8') as _fh: tags = json.load(_fh).get('tags') or [] except (ValueError, OSError): tags = [] return _visibility_resolved(cfg.get('visibility'), tags)
[docs]def cmd_visibility(a: argparse.Namespace) -> int: """Show, or set, this node's public/private default and its per-unit overrides (plan D2). With no arguments it reads: a running node's `status`, else config.json and the descriptor it last mined. `--default` sets the node default, `--set ID=public|private` adds one override (repeatable) and `--clear ID` removes one. Setting reaches a running node over its socket - which rebuilds and republishes at once, or retracts the public descriptor when the node goes fully private - and writes config.json when no node is up, so the next `run` publishes the new descriptor. """ override_args: dict[str, str | None] = {} for item in (a.set or []): unit, sep, value = str(item).partition('=') if not unit or not sep or value not in ('public', 'private'): fail('--set takes <protocol or app URI>=public|private, got %r' % item) override_args[unit] = value for unit in (a.clear or []): override_args[str(unit)] = None changing = a.default is not None or bool(override_args) if changing: if control.running(a.dir): state: VisibilityState = _ask(a.dir, 'set-visibility', default=a.default, overrides=override_args) else: state = _set_visibility_offline(a.dir, a.default, override_args) else: live = _live(a, 'status') vis = live.get('visibility') if isinstance(live, Mapping) else None state = cast(VisibilityState, dict(vis)) if isinstance(vis, Mapping) else _visibility_from_files(a.dir) if a.json: return emit(a, state) _render_visibility(state) return 0
def _set_visibility_offline(directory: str, default: Any, override_args: Mapping[str, Any]) -> VisibilityState: """Apply a visibility change to config.json with no node running.""" from fleetmesh_node.config import VisibilityConfig from fleetmesh_node.app.config import save_config cfg = dict(app_mod.load_config(directory)) try: resolved = VisibilityConfig.merge(cfg.get('visibility'), default, override_args) except ValueError as e: fail(str(e)) cfg['visibility'] = {'default': resolved.default, 'overrides': dict(resolved.overrides)} save_config(directory, {k: v for k, v in cfg.items() if not str(k).startswith('_')}) state = _visibility_from_files(directory) state['waits'] = 'the node was not running; config.json is written and the next `meshnode run` publishes it' return state def _render_visibility(state: VisibilityState) -> None: default = state.get('default') print('visibility: default %s%s' % ( default, '' if state.get('public') else ' (fully private: no public descriptor)')) for unit, value in sorted((state.get('overrides') or {}).items()): print(' override %s %s' % (value, unit)) for unit, value in sorted((state.get('protocols') or {}).items()): print(' %-11s %s' % ('protocol', '%s %s' % (value, unit))) for unit, value in sorted((state.get('capabilities') or {}).items()): print(' %-11s %s' % ('capability', '%s %s' % (value, unit))) waits = state.get('waits') if waits: print(waits)
[docs]def cmd_tick(a: argparse.Namespace) -> int: did = _ask(a.dir, 'tick', timeout=120) def human(did: list) -> None: if not did: print('nothing to do') return for d in did: print(' ' + ' '.join(str(x)[:16] + '…' if validate.hex64(str(x)) else str(x) for x in d)) return emit(a, did, human)
[docs]def cmd_api(a: argparse.Namespace) -> int: """The control socket described by itself.""" if control.running(a.dir): try: v = control.call(a.dir, 'version', timeout=10) cmds = control.call(a.dir, 'commands', timeout=10) live = True except control.ControlError: v, cmds, live = None, None, False else: v, cmds, live = None, None, False if v is None: v = {'protocol': control.PROTOCOL, 'fleetmesh': app_mod.descriptor.VERSION, 'digest': app_mod.descriptor.DIGEST, 'release': release_mod.running().as_dict(), 'commands': list(app_mod.CONTROL)} cmds = [dict(name=n, **spec) for n, spec in app_mod.CONTROL.items()] if a.json: return emit(a, {'version': v, 'commands': cmds, 'live': live}) print('%s over %s (%s)' % (v['protocol'], control.socket_path(a.dir), 'from the running node' if live else 'no node running; from the table it would dispatch on')) print('%s@%s' % (v['fleetmesh'], v['digest'][:16] + '…')) rel = v.get('release') or {} if rel: print('%s %s (%s%s)' % (rel.get('name'), rel.get('version'), rel.get('source'), ', ' + rel['commit'][:12] if rel.get('commit') else '')) print('request {"cmd": name, "args": {...}} reply {"ok": true, "protocol": ..., "result": ...} | {"ok": false, "protocol": ..., "error": ...}') print() _table(('command', 'args', 'answers'), [(c['name'], ' '.join('%s%s' % (k, '' if v_ == 'required' else '?') for k, v_ in c['args'].items()) or '-', c['does']) for c in cmds]) return 0
from ..config.parameter import Parameter from .adapter import add_parameter_argument PARAM_INIT_CLASS = Parameter(key='node_class', cli_name='--class', name='node_class', description='node class', type=str, default='edge', choices=('leaf', 'edge', 'anchor')) PARAM_INIT_OPERATOR = Parameter(key='operator', name='operator', description='operator pubkey, hex', type=str, default='') PARAM_INIT_RELAY = Parameter(key='relay', name='relay', description='control-plane relay, repeatable', type=list, default=None) PARAM_INIT_ENDPOINT = Parameter(key='endpoint', name='endpoint', description='scheme=address[:preference], repeatable', type=list, default=None) PARAM_INIT_FACE_HOST = Parameter(key='face_host', cli_name='--face-host', name='face_host', description='relay face host', type=str, default='127.0.0.1') PARAM_INIT_FACE_PORT = Parameter(key='face_port', cli_name='--face-port', name='face_port', description='relay face port', type=int, default=None) PARAM_INIT_POW_BITS = Parameter(key='pow_bits', cli_name='--pow-bits', name='pow_bits', description='PoW difficulty bits', type=int, default=None) PARAM_INIT_NAME = Parameter(key='name', name='name', description='node name', type=str, default='') PARAM_INIT_MANIFEST = Parameter(key='manifest', name='manifest', description='a MeshNode manifest (yaml or json)', type=str, default='') PARAM_INIT_PEERING = Parameter(key='peering', name='peering', description='a Peering manifest, repeatable', type=list, default=None)
[docs]class CoreCommandProvider: """Registers core lifecycle, health, identity, and operator commands."""
[docs] @classmethod def register(cls, sub: argparse._SubParsersAction) -> None: i = add_command(sub, 'init', cmd_init, 'generate keys, write config, mine and publish the descriptor', js=True) add_parameter_argument(i, PARAM_INIT_CLASS) add_parameter_argument(i, PARAM_INIT_OPERATOR) add_parameter_argument(i, PARAM_INIT_RELAY) add_parameter_argument(i, PARAM_INIT_ENDPOINT) add_parameter_argument(i, PARAM_INIT_FACE_HOST) add_parameter_argument(i, PARAM_INIT_FACE_PORT) add_parameter_argument(i, PARAM_INIT_POW_BITS) add_parameter_argument(i, PARAM_INIT_NAME) add_parameter_argument(i, PARAM_INIT_MANIFEST) add_parameter_argument(i, PARAM_INIT_PEERING) add_command(sub, 'run', cmd_run, 'start the node and tick until SIGTERM') add_command(sub, 'status', cmd_status, 'what the running node last wrote, and its trouble', js=True) add_command(sub, 'health', cmd_health, 'every error plane: relays, drops, rejections, failures', js=True) add_command(sub, 'whoami', cmd_whoami, "the node's identity: DID, npub, keys, descriptor", js=True) e = add_command(sub, 'enrol', cmd_enrol, 'join a fleet with an fmenrol1 token minted for this node\'s pubkey', js=True) e.add_argument('token', help='the fmenrol1… token the operator minted for this node (`whoami` shows the pubkey)') e.add_argument('--force', action='store_true', help='move to a different operator (otherwise refused already_enrolled)') n = add_command(sub, 'network', cmd_network, 'ask an approved private network to admit this node', js=True) n.add_argument('action', choices=('join',), help='join an approved network') n.add_argument('network', help='network id <creator hex>:<slug>') n.add_argument('--note', default=None, help='a note to the controller, at most 280 characters') v = add_command(sub, 'visibility', cmd_visibility, 'show or set the node default public/private and per-app or per-protocol overrides', js=True) v.add_argument('--default', choices=('public', 'private'), default=None, help='the node default') v.add_argument('--set', action='append', default=None, metavar='URI=public|private', help='one override: a protocol or app URI=public|private; repeatable') v.add_argument('--clear', action='append', default=None, metavar='URI', help='clear one override; repeatable') add_command(sub, 'check', cmd_check, 'is this directory a node that can run? exits 1 if not', js=True) add_command(sub, 'tick', cmd_tick, 'one tick now, and what it did (needs the node running)', js=True) add_command(sub, 'api', cmd_api, 'the control socket described by itself: protocol, commands, arguments, replies', js=True)