"""The `cluster` subcommand: a local multi-node testnet on one machine.
Owns the command body and its place in the operator's parser, like every other
module under fleetmesh_node/commands. The body used to sit at the bottom of
fleetmesh_node/testnet/cluster.py; the cluster engine now knows nothing about argparse or how
its status is printed.
"""
from __future__ import annotations
import argparse
import json
import os
from typing import Any, TypedDict
from fleetmesh_node.config.parameter import Parameter
from fleetmesh_node.testnet import LocalCluster
from .adapter import CommandDispatcher
from .base import add_command, emit, fail, try_ask
[docs]class ClusterFipsStatus(TypedDict, total=False):
active: bool
listeners: int
[docs]class ClusterNodeSummary(TypedDict, total=False):
index: int
name: str
pubkey: str
peers: list[Any]
event_count: int
face: str
[docs]class ClusterStatusSummary(TypedDict, total=False):
node_count: int
topology: str
cluster_dir: str
running: bool
active_peering_edges: int
relays: list[str]
fips: ClusterFipsStatus
nodes: list[ClusterNodeSummary]
PARAM_NODES = Parameter(
key='nodes', name='nodes', description='number of nodes in the cluster (default: 3)',
type=int, default=3,
)
PARAM_TOPOLOGY = Parameter(
key='topology', name='topology', description='peering topology',
type=str, default='mesh', choices=('mesh', 'star', 'ring', 'line'),
)
PARAM_RELAYS = Parameter(
key='relays', name='relays', description='relay URLs for cluster',
type=list, default=None, nargs='*',
)
PARAM_SHARD = Parameter(
key='shard', name='shard', description='shard name for sync',
type=str, default='bristol',
)
PARAM_FIPS = Parameter(
key='fips', name='fips', description='enable FIPS native datagram transport in cluster',
type=bool, default=False,
)
def _meta(cluster_dir: str) -> ClusterMeta:
"""cluster.json, or exit when the directory holds none."""
meta_path = os.path.join(cluster_dir, 'cluster.json')
if not os.path.exists(meta_path):
fail(f"No cluster.json in {cluster_dir}.")
with open(meta_path, encoding='utf-8') as _fh:
return json.load(_fh)
def _render_cluster_summary(status: ClusterStatusSummary) -> None:
print("\n=======================================================")
print(f" MeshNode Cluster: {status['node_count']} nodes | Topology: {status['topology'].upper()}")
print(f" Directory: {status['cluster_dir']}")
print(f" Status: {'RUNNING' if status['running'] else 'STOPPED'}")
print(f" Active Peerings: {status['active_peering_edges']}")
if status.get('relays'):
print(f" Shared Relays: {', '.join(status['relays'])}")
if status.get('fips'):
print(f" FIPS Transport: {'ACTIVE' if status['fips'].get('active') else 'INACTIVE'} (listeners: {status['fips'].get('listeners', 0)})")
print("-------------------------------------------------------")
print(f" {'#':<3} {'Name':<10} {'Class':<8} {'Pubkey':<18} {'Peers':<6} {'Events':<7} {'Face'}")
print(" --- ---------- -------- ------------------ ------ ------- -------------------------")
for n in status.get('nodes', []):
pk_short = (n.get('pubkey') or '')[:16] + '…'
peers_cnt = len(n.get('peers', []))
events_cnt = n.get('event_count', 0)
face = n.get('face') or '-'
print(f" {n['index']:<3} {n['name']:<10} {n.get('class', '-'):<8} {pk_short:<18} {peers_cnt:<6} {events_cnt:<7} {face}")
print("=======================================================\n")
def _handle_start(args: argparse.Namespace) -> int:
cluster_dir = getattr(args, 'dir', None) or os.path.abspath('cluster-testnet')
count = int(getattr(args, 'nodes', 3))
topo = getattr(args, 'topology', 'mesh')
relays = getattr(args, 'relays', None) or []
enable_fips = bool(getattr(args, 'fips', False))
cl = LocalCluster(base_dir=cluster_dir, node_count=count, topology=topo, relay_urls=relays, enable_fips=enable_fips)
print(f"Starting {count}-node cluster ({topo}) in {cluster_dir}...")
cl.start()
print(f"Cluster active. Relay: {cl.relay_urls[0] if cl.relay_urls else 'nostr'} | FIPS: {'enabled' if enable_fips else 'disabled'}")
return emit(args, cl.get_status(), _render_cluster_summary)
def _handle_status(args: argparse.Namespace) -> int:
cluster_dir = getattr(args, 'dir', None) or os.path.abspath('cluster-testnet')
if not os.path.exists(cluster_dir):
fail(f"Cluster directory {cluster_dir} does not exist.")
meta = _meta(cluster_dir)
enable_fips = bool(meta.get('enable_fips', False))
cl = LocalCluster(base_dir=cluster_dir, node_count=meta['node_count'], topology=meta['topology'], enable_fips=enable_fips)
return emit(args, cl.get_status(), _render_cluster_summary)
def _handle_stop(args: argparse.Namespace) -> int:
cluster_dir = getattr(args, 'dir', None) or os.path.abspath('cluster-testnet')
if not os.path.exists(cluster_dir):
fail(f"Cluster directory {cluster_dir} does not exist.")
meta_path = os.path.join(cluster_dir, 'cluster.json')
if os.path.exists(meta_path):
meta = _meta(cluster_dir)
# Ask each node to retire; one that is already gone is no error.
for i in range(meta.get('node_count', 3)):
try_ask(os.path.join(cluster_dir, f'node_{i}'), 'retire', reason='cluster stop')
meta['running'] = False
with open(meta_path, 'w', encoding='utf-8') as _fh:
json.dump(meta, _fh, indent=2)
print(f"Cluster in {cluster_dir} stopped.")
return 0
def _handle_sync(args: argparse.Namespace) -> int:
cluster_dir = getattr(args, 'dir', None) or os.path.abspath('cluster-testnet')
meta = _meta(cluster_dir)
shard = getattr(args, 'shard', 'bristol')
print(f"Triggering cluster-wide sync for shard {shard!r}...")
for i in range(meta.get('node_count', 3)):
ndir = os.path.join(cluster_dir, f'node_{i}')
peers = try_ask(ndir, 'peers')
if peers is None:
print(f" node_{i} sync notice: node is not answering")
continue
for p in peers:
if try_ask(ndir, 'pull', peer=p['peer'], shard=shard) is None:
print(f" node_{i} sync notice: pull from {p['peer'][:16]} declined")
print("Sync triggered across cluster.")
return 0
CLUSTER_DISPATCHER = CommandDispatcher('cluster', default_action='status', action_dest='cluster_action')
CLUSTER_DISPATCHER.add_custom('start', _handle_start, parameters=(PARAM_NODES, PARAM_TOPOLOGY, PARAM_RELAYS, PARAM_FIPS))
CLUSTER_DISPATCHER.add_custom('status', _handle_status)
CLUSTER_DISPATCHER.add_custom('stop', _handle_stop)
CLUSTER_DISPATCHER.add_custom('sync', _handle_sync, parameters=(PARAM_SHARD,))
[docs]def cmd_cluster(args: argparse.Namespace) -> int:
return CLUSTER_DISPATCHER.dispatch(args)
[docs]class ClusterCommandProvider:
"""Registers the local testnet cluster command."""
[docs] @classmethod
def register(cls, sub: argparse._SubParsersAction) -> None:
cl = add_command(sub, 'cluster', cmd_cluster, 'manage a local multi-node testnet cluster', js=True)
CLUSTER_DISPATCHER.register_arguments(cl, action_choices=('start', 'status', 'stop', 'sync'), action_dest='cluster_action')