First commit
This commit is contained in:
@@ -0,0 +1,62 @@
|
|||||||
|
# TrueNAS two-way file sync controller
|
||||||
|
|
||||||
|
This prototype configures **Syncthing** to continuously sync the contents under `stor0` in both directions. A small controller discovers the ZFS datasets on both TrueNAS SCALE systems over SSH and validates that eligible filesystem datasets are mounted beneath the `stor0` root. Syncthing syncs the root tree, so newly created directories and datasets are included on a scan without adding a folder for each dataset.
|
||||||
|
|
||||||
|
The default exclusions are `stor0/containers` and `stor0/vm_stor`. Zvols are reported but not included. Permissions are ignored by Syncthing for now; ACLs can be configured after the content sync is tested. New folders are configured with staggered Syncthing file versioning (180 days by default; configurable in TOML).
|
||||||
|
|
||||||
|
> **Important:** the Syncthing app/container on each NAS must be able to see the entire `stor0` mount tree, including nested ZFS dataset mounts created after the app starts. Test that before relying on this. If the app only sees the root dataset and not child mounts, dynamic discovery will not work until its host-path/mount configuration is corrected.
|
||||||
|
|
||||||
|
## Safety notes
|
||||||
|
|
||||||
|
- `--dry-run` is the default. It performs read-only SSH and Syncthing API requests and makes no changes.
|
||||||
|
- Before the first `--apply`, take fresh ZFS snapshots on both NASes. Initial two-way sync can find different versions of the same path; Syncthing may create conflict copies.
|
||||||
|
- Syncthing propagates changes and deletions. The controller enables staggered file versioning for newly created sync folders, but also rely on independently retained ZFS snapshots before production use. Syncthing versioning stores replaced/deleted remote copies in `.stversions` and uses additional disk space.
|
||||||
|
- Do not sync active container databases/mail stores or live VM disks as ordinary files. This controller excludes the named `containers` and `vm_stor` subtrees and all zvols. Plan app-aware/VM failover separately.
|
||||||
|
- Both NASes can accept changes, but simultaneous edits to the same file while disconnected can create conflict copies; they cannot be merged automatically in every format.
|
||||||
|
- Dataset mountpoints outside the root mount are rejected instead of silently omitted. `canmount=off` datasets and zvols are reported as skipped.
|
||||||
|
- The controller never runs `rm`, `zfs destroy`, or snapshot deletion commands. Syncthing itself does propagate file deletions. If a child dataset is unmounted or destroyed, its files can appear to have been deleted from the sync root and those deletions may propagate; only do that intentionally, with snapshots/versioning available. The ZFS dataset object itself is not recreated or deleted on the other NAS.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- Python 3.11+
|
||||||
|
- SSH access from the controller host to both NASes, with permission to run read-only `zfs list`
|
||||||
|
- Syncthing installed/running on both NASes, with the two devices already paired
|
||||||
|
- Syncthing REST API access and API keys for both instances
|
||||||
|
- A Syncthing folder path on each NAS that points to that NAS's `stor0` root **inside the Syncthing app/container**
|
||||||
|
|
||||||
|
Use HTTPS for the Syncthing API when it is reachable over a network. Restrict API access with firewall rules; the API key grants control over Syncthing.
|
||||||
|
|
||||||
|
## Configure
|
||||||
|
|
||||||
|
1. Copy `truenas-sync.example.toml` to `truenas-sync.toml` and protect it (`chmod 600 truenas-sync.toml` on Linux). Fill in SSH targets, Syncthing API URLs/keys, each device ID, and each path as seen inside the Syncthing app.
|
||||||
|
2. Confirm both Syncthing devices are paired in the Syncthing UI. The controller will not pair devices automatically.
|
||||||
|
3. Confirm the configured Syncthing paths resolve to each `stor0` root and that the app can see the child dataset mountpoints. The host mountpoint returned by ZFS is shown separately in the dry-run.
|
||||||
|
4. Run a plan:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 truenas_sync.py --config truenas-sync.toml --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
5. Review every eligible/excluded/skipped dataset and fix any errors. Take fresh snapshots on both NASes, then configure the folder:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 truenas_sync.py --config truenas-sync.toml --apply
|
||||||
|
```
|
||||||
|
|
||||||
|
`--dry-run` checks the discovered datasets and plans Syncthing configuration; it does **not** calculate a file-by-file transfer/deletion preview. `--apply` activates bidirectional sync for the entire configured root, so do not use it for the first time against production data until the inventory and snapshots are reviewed. For a small pilot, set `dataset_root = "stor0/sync_test"`, use `sync_path = "/data/stor0/sync_test"` on both peers, and give it a distinct `folder_id`. Remove the pilot folder configuration on both peers (keep the files) before expanding to `stor0`; Syncthing does not support nested shared folders safely.
|
||||||
|
|
||||||
|
The controller creates the same Syncthing folder ID on each NAS in paused state, adds exclusions, then activates the folders. It is safe to run again once configured. It refuses to rewrite an existing folder whose path/peer differs, and refuses to change missing exclusion rules on an already-active folder.
|
||||||
|
|
||||||
|
## Dynamic dataset behavior
|
||||||
|
|
||||||
|
Run the controller periodically (for example every 5 minutes) to re-inventory datasets and catch mount/path issues. The controller does not create a per-dataset Syncthing folder: the single Syncthing root covers the directory tree. Syncthing's filesystem watcher plus periodic rescans discovers new content. For a newly created ZFS dataset, verify that its mount is visible inside the Syncthing app and that the app's scanner sees a test file before trusting it.
|
||||||
|
|
||||||
|
The script currently assumes the matching relative path exists under each side's sync root. If a dataset exists only on one side, Syncthing can create the corresponding directory on the other side; it does not create a ZFS dataset there. `dataset_root` may be a pool root such as `stor0` or a deeper ZFS dataset path such as `stor0/sync_test`.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
Run the offline unit tests (no NAS or Syncthing connection required):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 -m unittest -v
|
||||||
|
```
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from truenas_sync import (
|
||||||
|
Dataset,
|
||||||
|
Nas,
|
||||||
|
SyncError,
|
||||||
|
_is_child_path,
|
||||||
|
classify_inventory,
|
||||||
|
load_config,
|
||||||
|
make_plan,
|
||||||
|
parse_dataset_output,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def nas(name: str = "test", device_id: str = "AAAA-BBBB") -> Nas:
|
||||||
|
return Nas(name, "root@example", "http://localhost:8384", "secret", device_id, "/data/stor0")
|
||||||
|
|
||||||
|
|
||||||
|
class DatasetDiscoveryTests(unittest.TestCase):
|
||||||
|
def test_parse_zfs_output(self):
|
||||||
|
result = parse_dataset_output(
|
||||||
|
"stor0\tfilesystem\t/mnt/stor0\ton\tyes\n"
|
||||||
|
"stor0/Documents\tfilesystem\t/mnt/stor0/Documents\ton\tyes\n"
|
||||||
|
)
|
||||||
|
self.assertEqual([item.name for item in result], ["stor0", "stor0/Documents"])
|
||||||
|
|
||||||
|
def test_bad_zfs_output_fails_closed(self):
|
||||||
|
with self.assertRaises(SyncError):
|
||||||
|
parse_dataset_output("stor0 filesystem /mnt/stor0 on yes\n")
|
||||||
|
|
||||||
|
def test_classifies_ordinary_datasets_and_exclusions(self):
|
||||||
|
inventory = classify_inventory(
|
||||||
|
nas(),
|
||||||
|
"stor0",
|
||||||
|
["containers", "vm_stor"],
|
||||||
|
[
|
||||||
|
Dataset("stor0", "filesystem", "/mnt/stor0", "on", "yes"),
|
||||||
|
Dataset("stor0/Documents", "filesystem", "/mnt/stor0/Documents", "on", "yes"),
|
||||||
|
Dataset("stor0/series", "filesystem", "/mnt/stor0/series", "on", "yes"),
|
||||||
|
Dataset("stor0/containers", "filesystem", "/mnt/stor0/containers", "on", "yes"),
|
||||||
|
Dataset("stor0/containers/mail", "filesystem", "/mnt/stor0/containers/mail", "on", "yes"),
|
||||||
|
Dataset("stor0/vm_stor", "filesystem", "/mnt/stor0/vm_stor", "on", "yes"),
|
||||||
|
Dataset("stor0/other-vol", "volume", "-", "on", "-"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
self.assertEqual([item.name for item in inventory.ordinary], ["stor0", "stor0/Documents", "stor0/series"])
|
||||||
|
self.assertEqual(
|
||||||
|
[item.name for item in inventory.excluded],
|
||||||
|
["stor0/containers", "stor0/containers/mail", "stor0/vm_stor"],
|
||||||
|
)
|
||||||
|
self.assertEqual([item.name for item in inventory.volumes], ["stor0/other-vol"])
|
||||||
|
|
||||||
|
def test_unmounted_eligible_dataset_is_an_error(self):
|
||||||
|
with self.assertRaisesRegex(SyncError, "not mounted"):
|
||||||
|
classify_inventory(
|
||||||
|
nas(),
|
||||||
|
"stor0",
|
||||||
|
["containers", "vm_stor"],
|
||||||
|
[
|
||||||
|
Dataset("stor0", "filesystem", "/mnt/stor0", "on", "yes"),
|
||||||
|
Dataset("stor0/Documents", "filesystem", "/mnt/stor0/Documents", "on", "no"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_custom_mount_outside_root_is_an_error(self):
|
||||||
|
with self.assertRaisesRegex(SyncError, "mounted outside"):
|
||||||
|
classify_inventory(
|
||||||
|
nas(),
|
||||||
|
"stor0",
|
||||||
|
["containers", "vm_stor"],
|
||||||
|
[
|
||||||
|
Dataset("stor0", "filesystem", "/mnt/stor0", "on", "yes"),
|
||||||
|
Dataset("stor0/Documents", "filesystem", "/mnt/archive/Documents", "on", "yes"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_nested_dataset_can_be_used_as_a_pilot_root(self):
|
||||||
|
inventory = classify_inventory(
|
||||||
|
nas(),
|
||||||
|
"stor0/sync_test",
|
||||||
|
[],
|
||||||
|
[
|
||||||
|
Dataset("stor0/sync_test", "filesystem", "/mnt/stor0/sync_test", "on", "yes"),
|
||||||
|
Dataset("stor0/sync_test/subdir", "filesystem", "/mnt/stor0/sync_test/subdir", "on", "yes"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
self.assertEqual(inventory.root_mountpoint, "/mnt/stor0/sync_test")
|
||||||
|
self.assertEqual([item.name for item in inventory.ordinary], ["stor0/sync_test", "stor0/sync_test/subdir"])
|
||||||
|
|
||||||
|
def test_path_check_does_not_accept_sibling_prefix(self):
|
||||||
|
self.assertTrue(_is_child_path("/mnt/stor0", "/mnt/stor0/Documents"))
|
||||||
|
self.assertFalse(_is_child_path("/mnt/stor0", "/mnt/stor00/Documents"))
|
||||||
|
|
||||||
|
|
||||||
|
class ConfigTests(unittest.TestCase):
|
||||||
|
def test_loads_names_and_sync_options(self):
|
||||||
|
content = '''
|
||||||
|
[general]
|
||||||
|
dataset_root = "stor0"
|
||||||
|
exclude = ["containers", "vm_stor"]
|
||||||
|
|
||||||
|
[helsinki]
|
||||||
|
ssh_target = "root@nas1"
|
||||||
|
api_url = "http://nas1:8384"
|
||||||
|
api_key = "key1"
|
||||||
|
device_id = "AAAA-BBBB"
|
||||||
|
sync_path = "/data/stor0"
|
||||||
|
|
||||||
|
[jarvenpaa]
|
||||||
|
ssh_target = "root@nas2"
|
||||||
|
api_url = "http://nas2:8384"
|
||||||
|
api_key = "key2"
|
||||||
|
device_id = "CCCC-DDDD"
|
||||||
|
sync_path = "/data/stor0"
|
||||||
|
'''
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
config = Path(directory) / "config.toml"
|
||||||
|
config.write_text(content, encoding="utf-8")
|
||||||
|
general, first, second = load_config(config)
|
||||||
|
self.assertEqual(general["root"], "stor0")
|
||||||
|
self.assertEqual(general["folder_id"], "truenas-stor0-files")
|
||||||
|
self.assertEqual(general["versioning_max_age_days"], 180)
|
||||||
|
self.assertEqual(first.name, "helsinki")
|
||||||
|
self.assertEqual(second.name, "jarvenpaa")
|
||||||
|
self.assertEqual(first.device_id, "AAAA-BBBB")
|
||||||
|
|
||||||
|
def test_rejects_same_device_id_even_with_different_hyphenation(self):
|
||||||
|
content = '''
|
||||||
|
[general]
|
||||||
|
[helsinki]
|
||||||
|
ssh_target = "root@nas1"
|
||||||
|
api_url = "http://nas1:8384"
|
||||||
|
api_key = "key1"
|
||||||
|
device_id = "AAAA-BBBB"
|
||||||
|
sync_path = "/data/stor0"
|
||||||
|
[jarvenpaa]
|
||||||
|
ssh_target = "root@nas2"
|
||||||
|
api_url = "http://nas2:8384"
|
||||||
|
api_key = "key2"
|
||||||
|
device_id = "AAAABBBB"
|
||||||
|
sync_path = "/data/stor0"
|
||||||
|
'''
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
config = Path(directory) / "config.toml"
|
||||||
|
config.write_text(content, encoding="utf-8")
|
||||||
|
with self.assertRaisesRegex(SyncError, "must be different"):
|
||||||
|
load_config(config)
|
||||||
|
|
||||||
|
|
||||||
|
class PlanTests(unittest.TestCase):
|
||||||
|
def test_plan_uses_bidirectional_root_and_root_anchored_exclusions(self):
|
||||||
|
first = nas("helsinki", "AAAA-BBBB")
|
||||||
|
second = nas("jarvenpaa", "CCCC-DDDD")
|
||||||
|
rows = [
|
||||||
|
Dataset("stor0", "filesystem", "/mnt/stor0", "on", "yes"),
|
||||||
|
Dataset("stor0/Documents", "filesystem", "/mnt/stor0/Documents", "on", "yes"),
|
||||||
|
]
|
||||||
|
inventories = (
|
||||||
|
classify_inventory(first, "stor0", ["containers", "vm_stor"], rows),
|
||||||
|
classify_inventory(second, "stor0", ["containers", "vm_stor"], rows),
|
||||||
|
)
|
||||||
|
|
||||||
|
class ReadOnlyApi:
|
||||||
|
def __init__(self, peer_id):
|
||||||
|
self.peer_id = peer_id
|
||||||
|
|
||||||
|
def get_state(self, folder_id):
|
||||||
|
return {"devices": [{"deviceID": self.peer_id}], "folder": None, "ignores": []}
|
||||||
|
|
||||||
|
general = {
|
||||||
|
"folder_id": "truenas-stor0-files",
|
||||||
|
"folder_label": "stor0 files",
|
||||||
|
"exclude": ["containers", "vm_stor"],
|
||||||
|
"rescan_interval_seconds": 60,
|
||||||
|
"versioning_max_age_days": 180,
|
||||||
|
}
|
||||||
|
plan = make_plan(inventories, general, (ReadOnlyApi("CCCC-DDDD"), ReadOnlyApi("AAAA-BBBB")))
|
||||||
|
self.assertEqual(plan.excludes, ("/containers", "/vm_stor"))
|
||||||
|
self.assertEqual(plan.versioning_max_age_days, 180)
|
||||||
|
self.assertEqual(len(plan.actions), 6)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
[general]
|
||||||
|
dataset_root = "stor0"
|
||||||
|
folder_id = "truenas-stor0-files"
|
||||||
|
folder_label = "stor0 ordinary files"
|
||||||
|
rescan_interval_seconds = 60
|
||||||
|
versioning_max_age_days = 180
|
||||||
|
exclude = ["containers", "vm_stor"]
|
||||||
|
|
||||||
|
[helsinki]
|
||||||
|
ssh_target = "root@nas1.example.net"
|
||||||
|
api_url = "https://nas1.example.net:8384"
|
||||||
|
api_key = "REPLACE_WITH_SYNCTHING_API_KEY"
|
||||||
|
device_id = "REPLACE-WITH-HELSINKI-SYNCTHING-DEVICE-ID"
|
||||||
|
# This is the path as seen INSIDE the Syncthing app/container.
|
||||||
|
sync_path = "/data/stor0"
|
||||||
|
|
||||||
|
[jarvenpaa]
|
||||||
|
ssh_target = "root@nas2.example.net"
|
||||||
|
api_url = "https://nas2.example.net:8384"
|
||||||
|
api_key = "REPLACE_WITH_SYNCTHING_API_KEY"
|
||||||
|
device_id = "REPLACE-WITH-JARVENPAA-SYNCTHING-DEVICE-ID"
|
||||||
|
sync_path = "/data/stor0"
|
||||||
+488
@@ -0,0 +1,488 @@
|
|||||||
|
#!/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())
|
||||||
Reference in New Issue
Block a user