#!/usr/bin/env python3 """Discover a TrueNAS dataset tree and configure a bidirectional Syncthing root. This manages Syncthing configuration only. Syncthing itself performs file sync. The default mode is read-only; use --apply to make changes. """ from __future__ import annotations import argparse import dataclasses import json import posixpath import shlex import subprocess import sys import urllib.error import urllib.parse import urllib.request from pathlib import Path from typing import Any, Sequence try: import tomllib except ModuleNotFoundError: # pragma: no cover - for Python < 3.11 tomllib = None # type: ignore[assignment] class SyncError(RuntimeError): """A configuration, discovery, or Syncthing API error.""" @dataclasses.dataclass(frozen=True) class Nas: name: str ssh_target: str api_url: str api_key: str device_id: str sync_path: str @dataclasses.dataclass(frozen=True) class Dataset: name: str kind: str mountpoint: str canmount: str mounted: str @dataclasses.dataclass(frozen=True) class Inventory: nas: Nas root_mountpoint: str ordinary: tuple[Dataset, ...] excluded: tuple[Dataset, ...] volumes: tuple[Dataset, ...] other: tuple[Dataset, ...] @dataclasses.dataclass class Plan: inventories: tuple[Inventory, Inventory] folder_id: str folder_label: str excludes: tuple[str, ...] interval: int versioning_max_age_days: int api_states: dict[str, dict[str, Any]] actions: list[str] def load_config(path: str | Path) -> tuple[dict[str, Any], Nas, Nas]: if tomllib is None: raise SyncError("Python 3.11 or newer is required (tomllib is unavailable).") try: with open(path, "rb") as handle: raw = tomllib.load(handle) except (OSError, tomllib.TOMLDecodeError) as exc: raise SyncError(f"Cannot read config {path}: {exc}") from exc general = raw.get("general", {}) root = str(general.get("dataset_root", "stor0")).strip("/") if not root or "//" in root: raise SyncError("general.dataset_root must be a ZFS dataset path, e.g. 'stor0' or 'stor0/sync_test'.") default_id_root = root.replace("/", "-") folder_id = str(general.get("folder_id", f"truenas-{default_id_root}-files")) if not folder_id or any(char.isspace() for char in folder_id): raise SyncError("general.folder_id must be non-empty and contain no whitespace.") folder_label = str(general.get("folder_label", f"{root} files")) interval = int(general.get("rescan_interval_seconds", 60)) if interval < 0: raise SyncError("general.rescan_interval_seconds cannot be negative.") versioning_max_age_days = int(general.get("versioning_max_age_days", 180)) if versioning_max_age_days < 0: raise SyncError("general.versioning_max_age_days cannot be negative (0 means keep versions forever).") excluded = tuple(str(item).strip("/") for item in general.get("exclude", ["containers", "vm_stor"])) if any(not item or "/" in item for item in excluded): raise SyncError("Each general.exclude entry must be a top-level dataset name.") def read_nas(name: str) -> Nas: item = raw.get(name) if not isinstance(item, dict): raise SyncError(f"Missing [{name}] section in config.") needed = ("ssh_target", "api_url", "api_key", "device_id", "sync_path") missing = [key for key in needed if not str(item.get(key, "")).strip()] if missing: raise SyncError(f"[{name}] is missing: {', '.join(missing)}") api_url = str(item["api_url"]).rstrip("/") if not api_url.startswith(("http://", "https://")): raise SyncError(f"[{name}].api_url must start with http:// or https://") sync_path = str(item["sync_path"]) if not sync_path.startswith("/"): raise SyncError(f"[{name}].sync_path must be an absolute path visible to Syncthing.") return Nas( name=name, ssh_target=str(item["ssh_target"]), api_url=api_url, api_key=str(item["api_key"]), device_id=str(item["device_id"]).upper(), sync_path=sync_path.rstrip("/") or "/", ) nas1 = read_nas(str(general.get("nas1_name", "helsinki"))) nas2 = read_nas(str(general.get("nas2_name", "jarvenpaa"))) if nas1.name == nas2.name or _normalize_device_id(nas1.device_id) == _normalize_device_id(nas2.device_id): raise SyncError("The two NAS names and Syncthing device IDs must be different.") return { "root": root, "exclude": excluded, "folder_id": folder_id, "folder_label": folder_label, "rescan_interval_seconds": interval, "versioning_max_age_days": versioning_max_age_days, }, nas1, nas2 def parse_dataset_output(output: str) -> list[Dataset]: datasets: list[Dataset] = [] for line_number, line in enumerate(output.splitlines(), 1): if not line.strip(): continue fields = line.split("\t") if len(fields) != 5: raise SyncError(f"Invalid zfs list output on line {line_number}: expected 5 tab-separated fields.") name, kind, mountpoint, canmount, mounted = fields datasets.append(Dataset(name, kind, mountpoint, canmount, mounted)) return datasets def classify_inventory(nas: Nas, root: str, excludes: Sequence[str], datasets: Sequence[Dataset]) -> Inventory: by_name = {dataset.name: dataset for dataset in datasets} if len(by_name) != len(datasets): raise SyncError(f"{nas.name}: ZFS inventory contains duplicate dataset names.") root_ds = by_name.get(root) if root_ds is None: raise SyncError(f"{nas.name}: ZFS dataset {root!r} was not found.") if root_ds.kind != "filesystem": raise SyncError(f"{nas.name}: {root!r} is {root_ds.kind}, expected a filesystem dataset.") if root_ds.mountpoint in ("-", "none", "legacy") or root_ds.mounted != "yes": raise SyncError(f"{nas.name}: root dataset {root!r} is not mounted at a normal path.") ordinary: list[Dataset] = [] excluded_datasets: list[Dataset] = [] volumes: list[Dataset] = [] other: list[Dataset] = [] for dataset in datasets: if dataset.name != root and not dataset.name.startswith(root + "/"): continue rel = dataset.name[len(root):].lstrip("/") top_level = rel.split("/", 1)[0] if rel else "" if dataset.kind == "volume": volumes.append(dataset) continue if dataset.kind != "filesystem": other.append(dataset) continue if top_level in excludes: excluded_datasets.append(dataset) continue if dataset.canmount == "off": other.append(dataset) continue if dataset.mounted != "yes": raise SyncError( f"{nas.name}: eligible filesystem dataset {dataset.name!r} is not mounted; refusing to omit it silently." ) if not _is_child_path(root_ds.mountpoint, dataset.mountpoint): raise SyncError( f"{nas.name}: eligible dataset {dataset.name!r} is mounted outside the {root!r} tree " f"({dataset.mountpoint!r}); a single sync root would miss it." ) ordinary.append(dataset) return Inventory( nas=nas, root_mountpoint=root_ds.mountpoint, ordinary=tuple(sorted(ordinary, key=lambda ds: ds.name)), excluded=tuple(sorted(excluded_datasets, key=lambda ds: ds.name)), volumes=tuple(sorted(volumes, key=lambda ds: ds.name)), other=tuple(sorted(other, key=lambda ds: ds.name)), ) def _is_child_path(parent: str, child: str) -> bool: parent = posixpath.normpath(parent) child = posixpath.normpath(child) return child == parent or child.startswith(parent.rstrip("/") + "/") def _normalize_device_id(value: str) -> str: return value.replace("-", "").replace(" ", "").upper() def discover(nas: Nas, root: str, excludes: Sequence[str]) -> Inventory: command = "zfs list -H -r -t filesystem,volume -o name,type,mountpoint,canmount,mounted " + shlex.quote(root) try: completed = subprocess.run( ["ssh", "-o", "BatchMode=yes", nas.ssh_target, command], check=True, capture_output=True, text=True, timeout=60, ) except FileNotFoundError as exc: raise SyncError("ssh executable was not found; install OpenSSH client on the controller host.") from exc except subprocess.CalledProcessError as exc: detail = exc.stderr.strip() or exc.stdout.strip() or str(exc) raise SyncError(f"Dataset discovery failed on {nas.name}: {detail}") from exc except subprocess.TimeoutExpired as exc: raise SyncError(f"Dataset discovery timed out on {nas.name}.") from exc return classify_inventory(nas, root, excludes, parse_dataset_output(completed.stdout)) class SyncthingApi: def __init__(self, nas: Nas, timeout: int = 15): self.nas = nas self.timeout = timeout def request(self, method: str, endpoint: str, body: Any | None = None) -> Any: url = self.nas.api_url + endpoint data = None if body is None else json.dumps(body).encode("utf-8") request = urllib.request.Request( url, data=data, method=method, headers={ "X-API-Key": self.nas.api_key, "Content-Type": "application/json", "User-Agent": "truenas-sync-controller/0.1", }, ) try: with urllib.request.urlopen(request, timeout=self.timeout) as response: content = response.read() if not content: return None return json.loads(content.decode("utf-8")) except urllib.error.HTTPError as exc: detail = exc.read().decode("utf-8", errors="replace") raise SyncError(f"Syncthing API on {self.nas.name} returned HTTP {exc.code}: {detail}") from exc except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc: raise SyncError(f"Cannot query Syncthing API on {self.nas.name}: {exc}") from exc def get_state(self, folder_id: str) -> dict[str, Any]: devices = self.request("GET", "/rest/config/devices") folders = self.request("GET", "/rest/config/folders") folder = next((item for item in folders if item.get("id") == folder_id), None) ignores: list[str] = [] if folder is not None: query = urllib.parse.urlencode({"folder": folder_id}) result = self.request("GET", f"/rest/db/ignores?{query}") ignores = result.get("ignore", []) if isinstance(result, dict) else [] return {"devices": devices, "folder": folder, "ignores": ignores} def ensure_folder( self, folder_id: str, label: str, path: str, peer: dict[str, Any], interval: int, versioning_max_age_days: int, ) -> None: state = self.get_state(folder_id) existing = state["folder"] if existing is not None: existing_devices = { _normalize_device_id(device.get("deviceID", "")) for device in existing.get("devices", []) } if existing.get("path") != path or _normalize_device_id(peer["deviceID"]) not in existing_devices: raise SyncError( f"{self.nas.name}: folder ID {folder_id!r} already exists with a different path or peer; " "refusing to modify an existing sync folder." ) return defaults = self.request("GET", "/rest/config/defaults/folder") folder = dict(defaults) folder.update( { "id": folder_id, "label": label, "path": path, "type": "sendreceive", "devices": [peer], "rescanIntervalS": interval, "fsWatcherEnabled": True, "ignorePerms": True, "paused": True, "versioning": { "type": "staggered", "params": {"maxAge": str(versioning_max_age_days * 24 * 60 * 60)}, }, } ) self.request("POST", "/rest/config/folders", folder) def ensure_ignores(self, folder_id: str, patterns: Sequence[str]) -> None: query = urllib.parse.urlencode({"folder": folder_id}) result = self.request("GET", f"/rest/db/ignores?{query}") current = result.get("ignore", []) if isinstance(result, dict) else [] merged = list(dict.fromkeys([*current, *patterns])) if merged != current: self.request("POST", f"/rest/db/ignores?{query}", {"ignore": merged}) def activate_folder(self, folder_id: str) -> None: folder = self.get_state(folder_id)["folder"] if folder is None: raise SyncError(f"{self.nas.name}: folder {folder_id!r} disappeared before activation.") if folder.get("paused"): folder["paused"] = False self.request("PUT", "/rest/config/folders/" + urllib.parse.quote(folder_id, safe=""), folder) def make_plan( inventories: tuple[Inventory, Inventory], general: dict[str, Any], apis: tuple[SyncthingApi, SyncthingApi], ) -> Plan: folder_id = str(general["folder_id"]) folder_label = str(general["folder_label"]) excludes = tuple("/" + name for name in general["exclude"]) interval = int(general["rescan_interval_seconds"]) versioning_max_age_days = int(general["versioning_max_age_days"]) states = {inventory.nas.name: api.get_state(folder_id) for inventory, api in zip(inventories, apis)} actions: list[str] = [] for inventory, peer_inventory in zip(inventories, reversed(inventories)): peer_id = peer_inventory.nas.device_id configured_devices = { _normalize_device_id(device.get("deviceID", "")) for device in states[inventory.nas.name]["devices"] } if _normalize_device_id(peer_id) not in configured_devices: raise SyncError( f"{inventory.nas.name}: Syncthing has not paired the peer device {peer_id}; " "pair the NASes in Syncthing before applying this plan." ) folder = states[inventory.nas.name]["folder"] if folder is None: actions.append( f"Create paused Send & Receive folder {folder_id!r} on {inventory.nas.name} at {inventory.nas.sync_path}." ) else: peer_devices = { _normalize_device_id(device.get("deviceID", "")) for device in folder.get("devices", []) } if folder.get("path") != inventory.nas.sync_path or _normalize_device_id(peer_id) not in peer_devices: raise SyncError( f"{inventory.nas.name}: folder ID {folder_id!r} already exists with a different path or peer; " "refusing to modify it. Choose a new folder_id or inspect the existing folder." ) versioning = folder.get("versioning", {}) configured_max_age = str(versioning.get("params", {}).get("maxAge", "")) expected_max_age = str(versioning_max_age_days * 24 * 60 * 60) if versioning.get("type") != "staggered" or configured_max_age != expected_max_age: raise SyncError( f"{inventory.nas.name}: existing folder {folder_id!r} does not have the configured staggered " f"file versioning retention ({versioning_max_age_days} days). Refusing to change an existing " "folder automatically. Use a new folder_id or configure versioning manually." ) actions.append(f"Reuse existing folder {folder_id!r} on {inventory.nas.name}.") missing_ignores = not set(excludes).issubset(set(states[inventory.nas.name]["ignores"])) if folder is not None and missing_ignores and not folder.get("paused", False): raise SyncError( f"{inventory.nas.name}: the existing folder is active but lacks required exclusions. " "Refusing to alter ignore rules on an active folder because that could propagate deletions; " "take snapshots and pause/inspect it first, or choose a new folder_id." ) if missing_ignores: actions.append(f"Add local ignore patterns on {inventory.nas.name}: {', '.join(excludes)}.") if folder is None or folder.get("paused"): actions.append(f"Activate folder {folder_id!r} on {inventory.nas.name} after both sides are configured.") return Plan(inventories, folder_id, folder_label, excludes, interval, versioning_max_age_days, states, actions) def print_plan(plan: Plan) -> None: for inventory in plan.inventories: print(f"\n{inventory.nas.name}: {len(inventory.ordinary)} eligible filesystem dataset(s)") print(f" ZFS root mountpoint: {inventory.root_mountpoint}") print(f" Syncthing path: {inventory.nas.sync_path}") for dataset in inventory.ordinary: print(f" + {dataset.name} -> {dataset.mountpoint}") if inventory.excluded: print(f" excluded containers/vm data: {len(inventory.excluded)} dataset(s)") if inventory.volumes: print(f" skipped zvols: {', '.join(ds.name for ds in inventory.volumes)}") if inventory.other: print(f" skipped non-mounted/unsupported datasets: {', '.join(ds.name for ds in inventory.other)}") print(f"\nFolder ID: {plan.folder_id} (Send & Receive on both NASes)") print("Ignored paths on both NASes: " + ", ".join(plan.excludes)) print("Permissions: ignored by Syncthing for now; configure/review ACLs separately.") print(f"Remote-change versioning: staggered, {plan.versioning_max_age_days} day(s) (0 means forever).") if plan.actions: print("\nPlanned actions:") for action in plan.actions: print(f" - {action}") else: print("\nNo configuration changes needed.") def apply_plan(plan: Plan, apis: tuple[SyncthingApi, SyncthingApi]) -> None: first, second = plan.inventories first_api, second_api = apis # Create both folder configurations paused so neither side starts syncing alone. first_api.ensure_folder( plan.folder_id, plan.folder_label, first.nas.sync_path, _peer_config(first_api, second.nas.device_id), plan.interval, plan.versioning_max_age_days, ) second_api.ensure_folder( plan.folder_id, plan.folder_label, second.nas.sync_path, _peer_config(second_api, first.nas.device_id), plan.interval, plan.versioning_max_age_days, ) # Apply exclusions before either folder is activated. first_api.ensure_ignores(plan.folder_id, plan.excludes) second_api.ensure_ignores(plan.folder_id, plan.excludes) first_api.activate_folder(plan.folder_id) second_api.activate_folder(plan.folder_id) def _peer_config(api: SyncthingApi, device_id: str) -> dict[str, Any]: devices = api.request("GET", "/rest/config/devices") peer = next( (device for device in devices if _normalize_device_id(device.get("deviceID", "")) == _normalize_device_id(device_id)), None, ) if peer is None: raise SyncError(f"Syncthing peer device {device_id} is not configured on {api.nas.name}.") return peer def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config", default="truenas-sync.toml", help="TOML config file (default: %(default)s)") mode = parser.add_mutually_exclusive_group() mode.add_argument("--dry-run", action="store_true", help="Read-only discovery and plan (the default).") mode.add_argument("--apply", action="store_true", help="Apply Syncthing folder configuration.") args = parser.parse_args(argv) try: general, nas1, nas2 = load_config(args.config) root = general["root"] excludes = general["exclude"] inventories = (discover(nas1, root, excludes), discover(nas2, root, excludes)) apis = (SyncthingApi(nas1), SyncthingApi(nas2)) plan = make_plan(inventories, general, apis) print_plan(plan) if args.apply: print("\nApplying changes. Ensure both NASes have fresh ZFS snapshots before first activation.") apply_plan(plan, apis) print("Done. Syncthing will scan and sync both roots.") else: print("\nDry run only; no Syncthing configuration was changed. Use --apply to configure it.") return 0 except SyncError as exc: print(f"ERROR: {exc}", file=sys.stderr) return 2 if __name__ == "__main__": raise SystemExit(main())