Coverage for bzfs_main/argparse_cli.py: 100%
171 statements
« prev ^ index » next coverage.py v7.15.1, created at 2026-07-21 12:39 +0000
« prev ^ index » next coverage.py v7.15.1, created at 2026-07-21 12:39 +0000
1# Copyright 2024 Wolfgang Hoschek AT mac DOT com
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14#
15"""Documentation, definition of input data and ArgumentParser used by the 'bzfs' CLI."""
17from __future__ import (
18 annotations,
19)
20import argparse
21import dataclasses
22import itertools
23from typing import (
24 Final,
25)
27from bzfs_main.argparse_actions import (
28 CheckPercentRange,
29 DatasetPairsAction,
30 DeleteDstSnapshotsExceptPlanAction,
31 FileOrLiteralAction,
32 IncludeSnapshotPlanAction,
33 NewSnapshotFilterGroupAction,
34 NonEmptyStringAction,
35 SafeDirectoryNameAction,
36 SafeFileNameAction,
37 SSHConfigFileNameAction,
38 TimeRangeAndRankRangeAction,
39)
40from bzfs_main.detect import (
41 DISABLE_PRG,
42 DUMMY_DATASET,
43)
44from bzfs_main.period_anchors import (
45 PeriodAnchors,
46)
47from bzfs_main.util.check_range import (
48 CheckRange,
49)
50from bzfs_main.util.utils import (
51 ENV_VAR_PREFIX,
52 PROG_NAME,
53 format_dict,
54)
56# constants:
57__version__: Final[str] = "1.24.0.dev0"
58PROG_AUTHOR: Final[str] = "Wolfgang Hoschek"
59EXCLUDE_DATASET_REGEXES_DEFAULT: Final[str] = r"(?:.*/)?[Tt][Ee]?[Mm][Pp][-_]?[0-9]*" # skip tmp datasets by default
60LOG_DIR_DEFAULT: Final[str] = PROG_NAME + "-logs"
61SKIP_ON_ERROR_DEFAULT: Final[str] = "dataset"
62CMP_CHOICES_ITEMS: Final[tuple[str, str, str]] = ("src", "dst", "all")
63ZFS_RECV_O: Final[str] = "zfs_recv_o"
64ZFS_RECV_X: Final[str] = "zfs_recv_x"
65ZFS_RECV_GROUPS: Final[dict[str, str]] = {ZFS_RECV_O: "-o", ZFS_RECV_X: "-x", "zfs_set": ""}
66ZFS_RECV_O_INCLUDE_REGEX_DEFAULT: Final[str] = "|".join(
67 [
68 "aclinherit",
69 "aclmode",
70 "acltype",
71 "atime",
72 "checksum",
73 "compression",
74 "copies",
75 "logbias",
76 "primarycache",
77 "recordsize",
78 "redundant_metadata",
79 "relatime",
80 "secondarycache",
81 "snapdir",
82 "sync",
83 "xattr",
84 ]
85)
88def argument_parser() -> argparse.ArgumentParser:
89 """Returns the CLI parser used by bzfs."""
90 create_src_snapshots_plan_example1: str = str({"test": {"": {"adhoc": 1}}}).replace(" ", "")
91 create_src_snapshots_plan_example2: str = str({"prod": {"us-west": {"minutely": 40, "hourly": 36, "daily": 31}}})
92 create_src_snapshots_plan_example2 = create_src_snapshots_plan_example2.replace(" ", "")
93 delete_dst_snapshots_except_plan_example1: str = str(
94 {
95 "prod": {
96 "us-west": {
97 "secondly": 40,
98 "minutely": 40,
99 "hourly": 36,
100 "daily": 31,
101 "weekly": 12,
102 "monthly": 18,
103 "yearly": 5,
104 }
105 }
106 }
107 ).replace(" ", "")
108 monitor_snapshots_example: str = str(
109 {
110 "prod": {
111 "us-west": {
112 "minutely": {"latest": {"warning": "30 seconds", "critical": "300 seconds"}},
113 "hourly": {"latest": {"warning": "30 minutes", "critical": "300 minutes"}},
114 "daily": {"latest": {"warning": "4 hours", "critical": "8 hours"}},
115 },
116 },
117 }
118 ).replace(" ", "")
120 # fmt: off
121 parser: argparse.ArgumentParser = argparse.ArgumentParser(
122 prog=PROG_NAME,
123 allow_abbrev=False,
124 formatter_class=argparse.RawTextHelpFormatter,
125 description=rf"""
126On the first run, {PROG_NAME} replicates the source dataset and all its snapshots to the destination.
127On subsequent runs, it sends only changes since the previous run by incrementally replicating snapshots
128created on the source after that run. Source snapshots older than the most recent common snapshot
129on the destination are skipped automatically.
131Unless {PROG_NAME} is told to create snapshots or bookmarks on the source, it treats the source as read-only. With
132`--dryrun`, it also treats the destination as read-only. In normal operation, the destination is
133append-only. Optional flags can delete destination snapshots and datasets if you want to manage storage
134space consumption, reconcile divergence, restore production from backup, or resync backup from production.
136{PROG_NAME} supports include/exclude filters that can be combined to choose which datasets,
137snapshots, and properties to create, replicate, delete, or compare.
139A common setup uses scheduled `cron` jobs: one to create and prune source snapshots, one to prune
140destination snapshots, and one to replicate recently created snapshots from source to destination.
141Schedules can run every N milliseconds, seconds, minutes, hours, days, weeks, months, or years.
143Snapshot creation, replication, pruning, monitoring, and comparison work with snapshots in any naming
144format, including snapshots created by third-party tools or by manual zfs snapshot commands.
145These functions can also be used independently.
147The source can push to the destination, and the destination can pull from the source. {PROG_NAME}
148runs on the initiator host, which can be the source host (push mode), destination host (pull mode),
149same host (local mode, no network, no ssh), or a third-party host that can SSH
150into source and destination (pull-push mode). In pull-push mode, the source `zfs send` stream is
151relayed by the initiator to the destination `zfs receive`, without storing anything locally.
152For bulk data transfers, remote-to-remote mode (`--r2r=pull` or `--r2r=push`) can instead transfer the
153stream directly between source and destination to avoid making the initiator a bandwidth bottleneck. In
154this mode, {PROG_NAME} does not need to be installed on source or destination; only the `zfs` CLI is
155required there. {PROG_NAME} can run as root or as a non-root user via sudo or delegated `zfs allow`
156permissions.
158{PROG_NAME} is written in Python and continuously tested with unit and integration tests on old and
159new ZFS versions, on multiple Linux and FreeBSD versions, and on all Python versions >= 3.9 (including
160latest stable, currently python-3.14).
162{PROG_NAME} is a stand-alone program with zero required dependencies. It is meant to run in restricted
163barebones server environments. No external Python packages are required; indeed no Python package
164management at all is required. You can symlink the program wherever you like, such as /usr/local/bin,
165and run it like a shell script or binary executable.
167{PROG_NAME} replicates snapshots for multiple datasets in parallel. It also deletes (or monitors or
168compares) snapshots of multiple datasets in parallel. Atomic snapshots can be created as often as
169every N milliseconds.
171Replication progress (e.g. throughput and ETA) is shown aggregated across parallel replication tasks.
172Example console status line:
174`2025-01-17 01:23:04 [I] zfs sent 41.7 GiB 0:00:46 [963 MiB/s] [907 MiB/s] 80% ETA 0:00:04 ETA 01:23:08`
176{PROG_NAME} uses streaming algorithms to process millions of datasets with low memory usage and low latency.
177It handles replication policies with multiple sources and multiple destinations per source.
179Optionally, {PROG_NAME} applies bandwidth rate limiting and progress monitoring (via `pv`) during
180`zfs send/receive` transfers. Over the network, it can insert lightweight compression (via `zstd`)
181and buffering (via `mbuffer`) between endpoints. If one of these tools is not installed, {PROG_NAME}
182auto-detects that and continues without that auxiliary feature.
184# Periodic Jobs with bzfs_jobrunner
186The project also ships with [bzfs_jobrunner](README_bzfs_jobrunner.md), a companion program that wraps
187`{PROG_NAME}` for periodic snapshot creation, replication, pruning, and monitoring across N source hosts
188and M destination hosts, using one shared fleet-wide [jobconfig](bzfs_testbed/bzfs_job_testbed.py)
189script.
191Typical use cases include geo-replicated backup where each destination host is in a different region
192and receives replicas from the same set of source hosts, low-latency replication from a primary to a
193secondary or to M read replicas, and backups to removable drives.
195# Quickstart
197* Create adhoc atomic snapshots without a schedule:
199```
200$ {PROG_NAME} tank1/foo/bar dummy --recursive --skip-replication --create-src-snapshots \
201--create-src-snapshots-plan "{create_src_snapshots_plan_example1}"
202```
204```
205$ zfs list -t snapshot tank1/foo/bar
206tank1/foo/bar@test_2024-11-06_08:30:05_adhoc
207```
209* Create periodic atomic snapshots on a schedule, every minute, every hour and every day, by launching this from a periodic `cron` job:
211```
212$ {PROG_NAME} tank1/foo/bar dummy --recursive --skip-replication --create-src-snapshots \
213--create-src-snapshots-plan \
214"{create_src_snapshots_plan_example2}"
215```
217```
218$ zfs list -t snapshot tank1/foo/bar
219tank1/foo/bar@prod_us-west_2024-11-06_08:30:05_daily
220tank1/foo/bar@prod_us-west_2024-11-06_08:30:05_hourly
221tank1/foo/bar@prod_us-west_2024-11-06_08:30:05_minutely
222```
224Note: A periodic snapshot is created if it is due per the schedule indicated by its suffix (e.g. `_daily` or `_hourly`
225or `_minutely` or `_2secondly` or `_100millisecondly`), or if the --create-src-snapshots-even-if-not-due flag is specified,
226or if the most recent scheduled snapshot is somehow missing. In the latter case {PROG_NAME} immediately creates a snapshot
227(named with the current time, not backdated to the missed time), and then resumes the original schedule. If the suffix is
228`_adhoc` or not a known period then a snapshot is considered non-periodic and is thus created immediately regardless of the
229creation time of any existing snapshot.
231* Replication example in local mode (no network, no ssh), to replicate ZFS dataset tank1/foo/bar to tank2/boo/bar:
233```
234$ {PROG_NAME} tank1/foo/bar tank2/boo/bar
235```
237```
238$ zfs list -t snapshot tank1/foo/bar
239tank1/foo/bar@prod_us-west_2024-11-06_08:30:05_daily
240tank1/foo/bar@prod_us-west_2024-11-06_08:30:05_hourly
241tank1/foo/bar@prod_us-west_2024-11-06_08:30:05_minutely
242```
244```
245$ zfs list -t snapshot tank2/boo/bar
246tank2/boo/bar@prod_us-west_2024-11-06_08:30:05_daily
247tank2/boo/bar@prod_us-west_2024-11-06_08:30:05_hourly
248tank2/boo/bar@prod_us-west_2024-11-06_08:30:05_minutely
249```
251* Same example in pull mode:
253```
254$ {PROG_NAME} root@host1.example.com:tank1/foo/bar tank2/boo/bar
255```
257* Same example in push mode:
259```
260$ {PROG_NAME} tank1/foo/bar root@host2.example.com:tank2/boo/bar
261```
263* Same example in pull-push mode:
265```
266$ {PROG_NAME} root@host1:tank1/foo/bar root@host2:tank2/boo/bar
267```
269* Same example with direct remote-to-remote transfer via `--r2r=pull`:
271```
272$ {PROG_NAME} --r2r=pull root@host1:tank1/foo/bar root@host2:tank2/boo/bar
273```
275* Same example with direct remote-to-remote transfer via `--r2r=push`:
277```
278$ {PROG_NAME} --r2r=push root@host1:tank1/foo/bar root@host2:tank2/boo/bar
279```
281* Example in local mode (no network, no ssh) to recursively replicate ZFS dataset tank1/foo/bar and its descendant
282datasets to tank2/boo/bar:
284```
285$ {PROG_NAME} --recursive tank1/foo/bar tank2/boo/bar
286```
288```
289$ zfs list -t snapshot -r tank1/foo/bar
290tank1/foo/bar@prod_us-west_2024-11-06_08:30:05_daily
291tank1/foo/bar@prod_us-west_2024-11-06_08:30:05_hourly
292tank1/foo/bar@prod_us-west_2024-11-06_08:30:05_minutely
293tank1/foo/bar/baz@prod_us-west_2024-11-06_08:40:00_daily
294tank1/foo/bar/baz@prod_us-west_2024-11-06_08:40:00_hourly
295tank1/foo/bar/baz@prod_us-west_2024-11-06_08:40:00_minutely
296```
298```
299$ zfs list -t snapshot -r tank2/boo/bar
300tank2/boo/bar@prod_us-west_2024-11-06_08:30:05_daily
301tank2/boo/bar@prod_us-west_2024-11-06_08:30:05_hourly
302tank2/boo/bar@prod_us-west_2024-11-06_08:30:05_minutely
303tank2/boo/bar/baz@prod_us-west_2024-11-06_08:40:00_daily
304tank2/boo/bar/baz@prod_us-west_2024-11-06_08:40:00_hourly
305tank2/boo/bar/baz@prod_us-west_2024-11-06_08:40:00_minutely
306```
308* Replicate all daily snapshots created during the last 31 days, and at the same time ensure that the latest 31 daily
309snapshots (per dataset) are replicated regardless of creation time. Same for 40 minutely snapshots, and 36 hourly
310snapshots:
312```
313$ {PROG_NAME} tank1/foo/bar tank2/boo/bar --recursive --include-snapshot-plan \
314"{create_src_snapshots_plan_example2}"
315```
317Note: The example above compares the specified times against the standard ZFS 'creation' time property of the snapshots
318(which is a UTC Unix time in integer seconds), rather than against a timestamp that may be part of the snapshot name.
320* Retain all secondly snapshots that were created less than 40 seconds ago, and ensure that the latest 40
321secondly snapshots (per dataset) are retained regardless of creation time. Same for 40 minutely snapshots, 36 hourly
322snapshots, 31 daily snapshots, 12 weekly snapshots, 18 monthly snapshots, and 5 yearly snapshots:
324```
325$ {PROG_NAME} {DUMMY_DATASET} tank2/boo/bar --dryrun --recursive --skip-replication \
326--delete-dst-snapshots --delete-dst-snapshots-except-plan \
327"{delete_dst_snapshots_except_plan_example1}"
328```
330Note: This also prints how many GB of disk space in total would be freed if the command were to be run for real without
331the --dryrun flag.
333* Compare source and destination dataset trees recursively, for example to check if all recently taken snapshots have
334been successfully replicated by a periodic job. List snapshots only contained in src (tagged with 'src'),
335only contained in dst (tagged with 'dst'), and contained in both src and dst (tagged with 'all'), restricted to hourly
336and daily snapshots taken within the last 7 days, excluding the last 4 hours (to allow for some slack/stragglers),
337excluding temporary datasets:
339```
340$ {PROG_NAME} tank1/foo/bar tank2/boo/bar --skip-replication --compare-snapshot-lists \
341--recursive --include-snapshot-regex '.*_(hourly|daily)' \
342--include-snapshot-times-and-ranks '7 days ago..4 hours ago' --exclude-dataset-regex \
343'(.*/)?tmp.*'
344```
346If the resulting TSV output file contains zero lines starting with the prefix 'src' and zero lines starting with the
347prefix 'dst' then no source snapshots are missing on the destination, and no destination snapshots are missing
348on the source, indicating that the periodic replication and pruning jobs perform as expected. The TSV output is sorted
349by dataset, and by ZFS creation time within each dataset - the first and last line prefixed with 'all' contains the
350metadata of the oldest and latest common snapshot, respectively. The --compare-snapshot-lists option also directly
351logs [various summary stats](https://github.com/whoschek/bzfs/blob/main/bzfs_docs/compare-snapshot-lists-example.log),
352such as the metadata of the latest common snapshot, latest snapshots and oldest snapshots, as well as the time diff
353between the latest common snapshot and latest snapshot only in src (and only in dst), as well as how many src snapshots
354and how many GB of data are missing on dst, etc.
356* Alert the user if the ZFS 'creation' time property of the latest source or destination snapshot for any specified
357snapshot name pattern within the selected datasets is too old wrt. the specified age limit. The purpose is to check if
358snapshots are successfully created and replicated on schedule.
359Process exit code is 0, 1, 2 on OK, WARNING, CRITICAL, respectively.
360The example alerts the user if the *latest* source or destination snapshot named `prod_us-west_<timestamp>_hourly` is
361more than 30 minutes late (i.e. more than 30+60=90 minutes old) [warning], or more than 300 minutes late (i.e. more
362than 300+60=360 minutes old) [critical]. Analog for minutely and daily snapshots:
364```
365$ {PROG_NAME} tank1/foo/bar tank2/boo/bar --recursive --skip-replication -v --monitor-snapshots \
366"{monitor_snapshots_example}"
367```
369* Example that makes destination identical to source even if the two have drastically diverged:
371```
372$ {PROG_NAME} tank1/foo/bar tank2/boo/bar --dryrun --recursive --force --delete-dst-datasets \
373--delete-dst-snapshots
374```
376""")
378 parser.add_argument(
379 "--no-argument-file", action="store_true",
380 # help="Disable support for reading the names of datasets and snapshots from a file.\n\n")
381 help=argparse.SUPPRESS)
382 parser.add_argument(
383 "root_dataset_pairs", nargs="+", action=DatasetPairsAction, metavar="SRC_DATASET DST_DATASET",
384 help="SRC_DATASET: "
385 "Source ZFS dataset (and its descendants) that will be replicated. Can be a ZFS filesystem or ZFS volume. "
386 "Format is [[user@]host:]dataset. The host name can also be an IPv4 address (or an IPv6 address where "
387 "each ':' colon character must be replaced with a '|' pipe character for disambiguation). If the "
388 "host name is '-', the dataset will be on the local host, and the corresponding SSH leg will be omitted. "
389 "The same is true if the host is omitted and the dataset does not contain a ':' colon at the same time. "
390 "Local dataset examples: `tank1/foo/bar`, `tank1`, `-:tank1/foo/bar:baz:boo` "
391 "Remote dataset examples: `host:tank1/foo/bar`, `host.example.com:tank1/foo/bar`, "
392 "`root@host:tank`, `root@host.example.com:tank1/foo/bar`, `user@127.0.0.1:tank1/foo/bar:baz:boo`, "
393 "`user@||1:tank1/foo/bar:baz:boo`. "
394 "The first component of the ZFS dataset name is the ZFS pool name, here `tank1`. "
395 "If the option starts with a `+` prefix then dataset names are read from the UTF-8 text file given "
396 "after the `+` prefix, with each line in the file containing a SRC_DATASET and a DST_DATASET, "
397 "separated by a tab character. The basename must contain the substring 'bzfs_argument_file'. "
398 "Example: `+root_dataset_names_bzfs_argument_file.txt`, "
399 "`+/path/to/root_dataset_names_bzfs_argument_file.txt`\n\n"
400 "DST_DATASET: "
401 "Destination ZFS dataset for replication and deletion. Has same naming format as SRC_DATASET. During "
402 "replication, destination datasets that do not yet exist are created as necessary, along with their "
403 "parent and ancestors.\n\n"
404 f"*Performance Note:* {PROG_NAME} automatically replicates multiple datasets in parallel. It replicates "
405 "snapshots in parallel across datasets and serially within a dataset. All child datasets of a dataset "
406 "may be processed in parallel. For consistency, processing of a dataset only starts after processing of "
407 "all its ancestor datasets has completed. Further, when a thread is ready to start processing another "
408 "dataset, it chooses the next dataset wrt. lexicographical sort order from the datasets that are "
409 "currently available for start of processing. Initially, only the roots of the selected dataset subtrees "
410 "are available for start of processing. The degree of parallelism is configurable with the --threads "
411 "option (see below).\n\n")
412 parser.add_argument(
413 "--recursive", "-r", action="store_true",
414 help="During snapshot creation, replication, deletion and comparison, also consider descendant datasets, i.e. "
415 "datasets within the dataset tree, including children, and children of children, etc.\n\n")
416 parser.add_argument(
417 "--include-dataset", action=FileOrLiteralAction, nargs="+", default=[], metavar="DATASET",
418 help="During snapshot creation, replication, deletion and comparison, select any ZFS dataset (and its descendants) "
419 "that is contained within SRC_DATASET (DST_DATASET in case of deletion) if its dataset name is one of the "
420 "given include dataset names but none of the exclude dataset names. If a dataset is excluded its descendants "
421 "are automatically excluded too, and this decision is never reconsidered even for the descendants because "
422 "exclude takes precedence over include.\n\n"
423 "A dataset name is absolute if the specified dataset is prefixed by `/`, e.g. `/tank/baz/tmp`. "
424 "Otherwise the dataset name is relative wrt. source and destination, e.g. `baz/tmp` if the source "
425 "is `tank`.\n\n"
426 "This option is automatically translated to an --include-dataset-regex (see below) and can be "
427 "specified multiple times.\n\n"
428 "If the option starts with a `+` prefix then dataset names are read from the newline-separated "
429 "UTF-8 text file given after the `+` prefix, one dataset per line inside of the text file. The basename "
430 "must contain the substring 'bzfs_argument_file'.\n\n"
431 "Examples: `/tank/baz/tmp` (absolute), `baz/tmp` (relative), "
432 "`+dataset_names_bzfs_argument_file.txt`, `+/path/to/dataset_names_bzfs_argument_file.txt`\n\n")
433 parser.add_argument(
434 "--exclude-dataset", action=FileOrLiteralAction, nargs="+", default=[], metavar="DATASET",
435 help="Same syntax as --include-dataset (see above) except that the option is automatically translated to an "
436 "--exclude-dataset-regex (see below).\n\n")
437 parser.add_argument(
438 "--include-dataset-regex", action=FileOrLiteralAction, nargs="+", default=[], metavar="REGEX",
439 help="During snapshot creation, replication (and deletion) and comparison, select any ZFS dataset (and its "
440 "descendants) that is contained within SRC_DATASET (DST_DATASET in case of deletion) if its relative dataset "
441 "path (e.g. `baz/tmp`) wrt. SRC_DATASET (DST_DATASET in case of deletion) matches at least one of the given "
442 "include regular expressions but none of the exclude regular expressions. "
443 "If a dataset is excluded its descendants are automatically excluded too, and this decision is never "
444 "reconsidered even for the descendants because exclude takes precedence over include.\n\n"
445 "This option can be specified multiple times. "
446 "A leading `!` character indicates logical negation, i.e. the regex matches if the regex with the "
447 "leading `!` character removed does not match.\n\n"
448 "If the option starts with a `+` prefix then regex names are read from the newline-separated "
449 "UTF-8 text file given after the `+` prefix, one regex per line inside of the text file. The basename "
450 "must contain the substring 'bzfs_argument_file'.\n\n"
451 "Default: `.*` (include all datasets).\n\n"
452 "Examples: `baz/tmp`, `(.*/)?doc[^/]*/(private|confidential).*`, `!public`, "
453 "`+dataset_regexes_bzfs_argument_file.txt`, `+/path/to/dataset_regexes_bzfs_argument_file.txt`\n\n")
454 parser.add_argument(
455 "--exclude-dataset-regex", action=FileOrLiteralAction, nargs="+", default=[], metavar="REGEX",
456 help="Same syntax as --include-dataset-regex (see above) except that the default is "
457 f"`{EXCLUDE_DATASET_REGEXES_DEFAULT}` (exclude tmp datasets). Example: `!.*` (exclude no dataset)\n\n")
458 parser.add_argument(
459 "--exclude-dataset-property", default=None, action=NonEmptyStringAction, metavar="STRING",
460 help="The name of a ZFS dataset user property (optional). If this option is specified, the effective value "
461 "(potentially inherited) of that user property is read via 'zfs list' for each selected source dataset "
462 "to determine whether the dataset will be included or excluded, as follows:\n\n"
463 "a) Value is 'true' or '-' or empty string or the property is missing: Include the dataset.\n\n"
464 "b) Value is 'false': Exclude the dataset and its descendants.\n\n"
465 "c) Value is a comma-separated list of host names (no spaces, for example: "
466 "'store001,store002'): Include the dataset if the host name of "
467 f"the host executing {PROG_NAME} is contained in the list, otherwise exclude the dataset and its "
468 "descendants.\n\n"
469 "If a dataset is excluded its descendants are automatically excluded too, and the property values of the "
470 "descendants are ignored because exclude takes precedence over include.\n\n"
471 "Examples: 'syncoid:sync', 'com.example.eng.project.x:backup'\n\n"
472 "*Note:* The use of --exclude-dataset-property is discouraged for most use cases. It is more flexible, "
473 "more powerful, *and* more efficient to instead use a combination of --include/exclude-dataset-regex "
474 "and/or --include/exclude-dataset to achieve the same or better outcome.\n\n")
475 parser.add_argument(
476 "--include-snapshot-regex", action=FileOrLiteralAction, nargs="+", default=[], metavar="REGEX",
477 help="During replication, deletion and comparison, select any source ZFS snapshot that has a name (i.e. the part "
478 "after the '@') that matches at least one of the given include regular expressions but none of the "
479 "exclude regular expressions. If a snapshot is excluded this decision is never reconsidered because "
480 "exclude takes precedence over include.\n\n"
481 "This option can be specified multiple times. "
482 "A leading `!` character indicates logical negation, i.e. the regex matches if the regex with the "
483 "leading `!` character removed does not match.\n\n"
484 "Default: `.*` (include all snapshots). "
485 "Examples: `test_.*`, `!prod_.*`, `.*_(hourly|frequent)`, `!.*_(weekly|daily)`\n\n"
486 "*Note:* All --include/exclude-snapshot-* CLI option groups are combined into a mini filter pipeline. "
487 "A filter pipeline is executed in the order given on the command line, left to right. For example if "
488 "--include-snapshot-times-and-ranks (see below) is specified on the command line before "
489 "--include/exclude-snapshot-regex, then --include-snapshot-times-and-ranks will be applied before "
490 "--include/exclude-snapshot-regex. The pipeline results would not always be the same if the order were "
491 "reversed. Order matters.\n\n"
492 "*Note:* During replication, bookmarks are always retained aka selected in order to help find common "
493 "snapshots between source and destination.\n\n")
494 parser.add_argument(
495 "--exclude-snapshot-regex", action=FileOrLiteralAction, nargs="+", default=[], metavar="REGEX",
496 help="Same syntax as --include-snapshot-regex (see above) except that the default is to exclude no "
497 "snapshots.\n\n")
498 parser.add_argument(
499 "--include-snapshot-times-and-ranks", action=TimeRangeAndRankRangeAction, nargs="+", default=[],
500 metavar=("TIMERANGE", "RANKRANGE"),
501 help="This option takes as input parameters a time range filter and an optional rank range filter. It "
502 "separately computes the results for each filter and selects the UNION of both results. "
503 "To instead use a pure rank range filter (no UNION), or a pure time range filter (no UNION), simply "
504 "use 'notime' aka '0..0' to indicate an empty time range, or omit the rank range, respectively. "
505 "This option can be specified multiple times.\n\n"
506 "<b>*Replication Example (UNION):* </b>\n\n"
507 "Specify to replicate all daily snapshots created during the last 7 days, "
508 "and at the same time ensure that the latest 7 daily snapshots (per dataset) are replicated regardless "
509 "of creation time, like so: "
510 "`--include-snapshot-regex '.*_daily' --include-snapshot-times-and-ranks '7 days ago..anytime' 'latest 7'`\n\n"
511 "<b>*Deletion Example (no UNION):* </b>\n\n"
512 "Specify to delete all daily snapshots older than 7 days, but ensure that the "
513 "latest 7 daily snapshots (per dataset) are retained regardless of creation time, like so: "
514 "`--include-snapshot-regex '.*_daily' --include-snapshot-times-and-ranks notime 'all except latest 7' "
515 "--include-snapshot-times-and-ranks 'anytime..7 days ago'`"
516 "\n\n"
517 "This helps to safely cope with irregular scenarios where no snapshots were created or received within "
518 "the last 7 days, or where more than 7 daily snapshots were created within the last 7 days. It can also "
519 "help to avoid accidental pruning of the last snapshot that source and destination have in common.\n\n"
520 ""
521 "<b>*TIMERANGE:* </b>\n\n"
522 "The ZFS 'creation' time of a snapshot (and bookmark) must fall into this time range in order for the "
523 "snapshot to be included. The time range consists of a 'start' time, followed by a '..' separator, "
524 "followed by an 'end' time. For example '2024-01-01..2024-04-01', or 'anytime..anytime' aka `*..*` aka all "
525 "times, or 'notime' aka '0..0' aka empty time range. Only snapshots (and bookmarks) in the half-open time "
526 "range [start, end) are included; other snapshots (and bookmarks) are excluded. If a snapshot is excluded "
527 "this decision is never reconsidered because exclude takes precedence over include. Each of the two specified "
528 "times can take any of the following forms:\n\n"
529 "* a) `anytime` aka `*` wildcard; represents negative or positive infinity.\n\n"
530 "* b) a non-negative integer representing a UTC Unix time in seconds. Example: 1728109805\n\n"
531 "* c) an ISO 8601 datetime string with or without timezone. Examples: '2024-10-05', "
532 "'2024-10-05T14:48:55', '2024-10-05T14:48:55+02', '2024-10-05T14:48:55-04:30'. If the datetime string "
533 "does not contain time zone info then it is assumed to be in the local time zone. Timezone string support "
534 "requires Python ≥ 3.11.\n\n"
535 "* d) a duration that indicates how long ago from the current time, using the following syntax: "
536 "a non-negative integer, followed by an optional space, followed by a duration unit that is "
537 "*one* of 'seconds', 'secs', 'minutes', 'mins', 'hours', 'days', 'weeks', 'months', 'years', "
538 "followed by an optional space, followed by the word 'ago'. "
539 "Examples: '0secs ago', '40 mins ago', '36hours ago', '90days ago', '12weeksago'.\n\n"
540 "* Note: This option compares the specified time against the standard ZFS 'creation' time property of the "
541 "snapshot (which is a UTC Unix time in integer seconds), rather than against a timestamp that may be "
542 "part of the snapshot name. You can list the ZFS creation time of snapshots and bookmarks as follows: "
543 "`zfs list -t snapshot,bookmark -o name,creation -s creation -d 1 $SRC_DATASET` (optionally add "
544 "the -p flag to display UTC Unix time in integer seconds).\n\n"
545 "*Note:* During replication, bookmarks are always retained aka selected in order to help find common "
546 "snapshots between source and destination.\n\n"
547 ""
548 "<b>*RANKRANGE:* </b>\n\n"
549 "Specifies to include the N (or N%%) oldest snapshots or latest snapshots, and exclude all other "
550 "snapshots (default: include no snapshots). Snapshots are sorted by creation time (actually, by the "
551 "'createtxg' ZFS property, which serves the same purpose but is more precise). The rank position of a "
552 "snapshot is the zero-based integer position of the snapshot within that sorted list. A rank consists of the "
553 "optional words 'all except' (followed by an optional space), followed by the word 'oldest' or 'latest', "
554 "followed by a non-negative integer, followed by an optional '%%' percent sign. A rank range consists of a "
555 "lower rank, followed by a '..' separator, followed by a higher rank. "
556 "If the optional lower rank is missing it is assumed to be 0. Examples:\n\n"
557 "* 'oldest 10%%' aka 'oldest 0..oldest 10%%' (include the oldest 10%% of all snapshots)\n\n"
558 "* 'latest 10%%' aka 'latest 0..latest 10%%' (include the latest 10%% of all snapshots)\n\n"
559 "* 'all except latest 10%%' aka 'oldest 90%%' aka 'oldest 0..oldest 90%%' (include all snapshots except the "
560 "latest 10%% of all snapshots)\n\n"
561 "* 'oldest 90' aka 'oldest 0..oldest 90' (include the oldest 90 snapshots)\n\n"
562 "* 'latest 90' aka 'latest 0..latest 90' (include the latest 90 snapshots)\n\n"
563 "* 'all except oldest 90' aka 'oldest 90..oldest 100%%' (include all snapshots except the oldest 90 snapshots)"
564 "\n\n"
565 "* 'all except latest 90' aka 'latest 90..latest 100%%' (include all snapshots except the latest 90 snapshots)"
566 "\n\n"
567 "* 'latest 1' aka 'latest 0..latest 1' (include the latest snapshot)\n\n"
568 "* 'all except latest 1' aka 'latest 1..latest 100%%' (include all snapshots except the latest snapshot)\n\n"
569 "* 'oldest 2' aka 'oldest 0..oldest 2' (include the oldest 2 snapshots)\n\n"
570 "* 'all except oldest 2' aka 'oldest 2..oldest 100%%' (include all snapshots except the oldest 2 snapshots)\n\n"
571 "* 'oldest 100%%' aka 'oldest 0..oldest 100%%' (include all snapshots)\n\n"
572 "* 'oldest 0%%' aka 'oldest 0..oldest 0%%' (include no snapshots)\n\n"
573 "* 'oldest 0' aka 'oldest 0..oldest 0' (include no snapshots)\n\n"
574 "*Note for multiple RANKRANGEs:* `--include-snapshot-times-and-ranks TIMERANGE RANKRANGE1 RANKRANGE2` is "
575 "equivalent to `--include-snapshot-times-and-ranks TIMERANGE RANKRANGE1 --include-snapshot-times-and-ranks "
576 "TIMERANGE RANKRANGE2`.\n\n"
577 "*Note:* Percentage calculations are not based on the number of snapshots "
578 "contained in the dataset on disk, but rather based on the number of snapshots arriving at the filter. "
579 "For example, if only two daily snapshots arrive at the filter because a prior filter excludes hourly "
580 "snapshots, then 'latest 10' will only include these two daily snapshots, and 'latest 50%%' will only "
581 "include one of these two daily snapshots.\n\n"
582 "*Note:* During replication, bookmarks are always retained aka selected in order to help find common "
583 "snapshots between source and destination. Bookmarks do not count towards N or N%% wrt. rank.\n\n"
584 "*Note:* If a snapshot is excluded this decision is never reconsidered because exclude takes precedence "
585 "over include.\n\n")
587 src_snapshot_plan_example = {
588 "prod": {
589 "onsite": {"secondly": 40, "minutely": 40, "hourly": 36, "daily": 31, "weekly": 12, "monthly": 18, "yearly": 5},
590 "us-west": {"secondly": 0, "minutely": 0, "hourly": 36, "daily": 31, "weekly": 12, "monthly": 18, "yearly": 5},
591 "eu-west": {"secondly": 0, "minutely": 0, "hourly": 36, "daily": 31, "weekly": 12, "monthly": 18, "yearly": 5},
592 },
593 "test": {
594 "offsite": {"12hourly": 42, "weekly": 12},
595 "onsite": {"100millisecondly": 42},
596 },
597 }
598 parser.add_argument(
599 "--include-snapshot-plan", action=IncludeSnapshotPlanAction, default=None, metavar="DICT_STRING",
600 help="Replication periods to be used if replicating snapshots within the selected destination datasets. "
601 "Has the same format as --create-src-snapshots-plan and --delete-dst-snapshots-except-plan (see below). "
602 "Snapshots that do not match a period will not be replicated. To avoid unexpected surprises, make sure to "
603 "carefully specify ALL snapshot names and periods that shall be replicated, in combination with --dryrun.\n\n"
604 f"Example: `{format_dict(src_snapshot_plan_example)}`. This example will, for the organization 'prod' and the "
605 "intended logical target 'onsite', replicate secondly snapshots that were created less than 40 seconds ago, "
606 "yet replicate the latest 40 secondly snapshots regardless of creation time. Analog for the latest 40 minutely "
607 "snapshots, latest 36 hourly snapshots, etc. "
608 "Note: A zero within a period (e.g. 'hourly': 0) indicates that no snapshots shall be replicated for the given "
609 "period.\n\n"
610 "Note: --include-snapshot-plan is a convenience option that auto-generates a series of the following other "
611 "options: --new-snapshot-filter-group, --include-snapshot-regex, --include-snapshot-times-and-ranks\n\n")
612 parser.add_argument(
613 "--new-snapshot-filter-group", action=NewSnapshotFilterGroupAction, nargs=0,
614 help="Starts a new snapshot filter group containing separate --{include|exclude}-snapshot-* filter options. The "
615 "program separately computes the results for each filter group and selects the UNION of all results. "
616 "This option can be specified multiple times and serves as a separator between groups. Example:\n\n"
617 "Delete all minutely snapshots older than 40 minutes, but ensure that the latest 40 minutely snapshots (per "
618 "dataset) are retained regardless of creation time. Additionally, delete all hourly snapshots older than 36 "
619 "hours, but ensure that the latest 36 hourly snapshots (per dataset) are retained regardless of creation time. "
620 "Additionally, delete all daily snapshots older than 31 days, but ensure that the latest 31 daily snapshots "
621 "(per dataset) are retained regardless of creation time: "
622 f"`{PROG_NAME} {DUMMY_DATASET} tank2/boo/bar --dryrun --recursive --skip-replication --delete-dst-snapshots "
623 "--include-snapshot-regex '.*_minutely' --include-snapshot-times-and-ranks notime 'all except latest 40' "
624 "--include-snapshot-times-and-ranks 'anytime..40 minutes ago' "
625 "--new-snapshot-filter-group "
626 "--include-snapshot-regex '.*_hourly' --include-snapshot-times-and-ranks notime 'all except latest 36' "
627 "--include-snapshot-times-and-ranks 'anytime..36 hours ago' "
628 "--new-snapshot-filter-group "
629 "--include-snapshot-regex '.*_daily' --include-snapshot-times-and-ranks notime 'all except latest 31' "
630 "--include-snapshot-times-and-ranks 'anytime..31 days ago'`\n\n")
631 parser.add_argument(
632 "--create-src-snapshots", action="store_true",
633 help="Do nothing if the --create-src-snapshots flag is missing. Otherwise, before the replication step (see below), "
634 "atomically create new snapshots of the source datasets selected via --{include|exclude}-dataset* policy. "
635 "The names of the snapshots can be configured via --create-src-snapshots-* suboptions (see below). "
636 "To create snapshots only, without any other processing such as replication, etc, consider using this flag "
637 "together with the --skip-replication flag.\n\n"
638 "A periodic snapshot is created if it is due per the schedule indicated by --create-src-snapshots-plan "
639 "(for example '_daily' or '_hourly' or _'10minutely' or '_2secondly' or '_100millisecondly'), or if the "
640 "--create-src-snapshots-even-if-not-due flag is specified, or if the most recent scheduled snapshot "
641 f"is somehow missing. In the latter case {PROG_NAME} immediately creates a snapshot (tagged with the current "
642 "time, not backdated to the missed time), and then resumes the original schedule.\n\n"
643 "If the snapshot suffix is '_adhoc' or not a known period then a snapshot is considered "
644 "non-periodic and is thus created immediately regardless of the creation time of any existing snapshot.\n\n"
645 "The implementation attempts to fit as many datasets as possible into a single (atomic) 'zfs snapshot' command "
646 "line, using lexicographical sort order, and using 'zfs snapshot -r' to the extent that this is compatible "
647 "with the actual results of the schedule and the actual results of the --{include|exclude}-dataset* pruning "
648 "policy. The snapshots of all datasets that fit "
649 "within the same single 'zfs snapshot' CLI invocation will be taken within the same ZFS transaction group, and "
650 "correspondingly have identical 'createtxg' ZFS property (but not necessarily identical 'creation' ZFS time "
651 "property as ZFS actually provides no such guarantee), and thus be consistent. Dataset names that can't fit "
652 "into a single command line are spread over multiple command line invocations, respecting the limits that the "
653 "operating system places on the maximum length of a single command line, per `getconf ARG_MAX`.\n\n"
654 f"Note: All {PROG_NAME} functions including snapshot creation, replication, deletion, monitoring, comparison, "
655 "etc. happily work with any snapshots in any format, even created or managed by third party ZFS snapshot "
656 "management tools, including manual zfs snapshot/destroy.\n\n")
657 parser.add_argument(
658 "--create-src-snapshots-plan", default=None, type=str, metavar="DICT_STRING",
659 help="Creation periods that specify a schedule for when new snapshots shall be created on src within the selected "
660 "datasets. Has the same format as --delete-dst-snapshots-except-plan.\n\n"
661 f"Example: `{format_dict(src_snapshot_plan_example)}`. This example will, for the organization 'prod' and "
662 "the intended logical target 'onsite', create 'secondly' snapshots every second, 'minutely' snapshots every "
663 "minute, hourly snapshots every hour, and so on. "
664 "It will also create snapshots for the targets 'us-west' and 'eu-west' within the 'prod' organization. "
665 "In addition, it will create snapshots every 12 hours and every week for the 'test' organization, "
666 "and name them as being intended for the 'offsite' replication target. Analog for snapshots that are taken "
667 "every 100 milliseconds within the 'test' organization.\n\n"
668 "The example creates ZFS snapshots with names like "
669 "`prod_onsite_<timestamp>_secondly`, `prod_onsite_<timestamp>_minutely`, "
670 "`prod_us-west_<timestamp>_hourly`, `prod_us-west_<timestamp>_daily`, "
671 "`prod_eu-west_<timestamp>_hourly`, `prod_eu-west_<timestamp>_daily`, "
672 "`test_offsite_<timestamp>_12hourly`, `test_offsite_<timestamp>_weekly`, and so on.\n\n"
673 "Note: A period name that is missing indicates that no snapshots shall be created for the given period.\n\n"
674 "The period name can contain an optional positive integer immediately preceding the time period unit, for "
675 "example `_2secondly` or `_10minutely` or `_100millisecondly` to indicate that snapshots are taken every 2 "
676 "seconds, or every 10 minutes, or every 100 milliseconds, respectively.\n\n")
678 def argparser_escape(text: str) -> str:
679 return text.replace("%", "%%")
681 parser.add_argument(
682 "--create-src-snapshots-timeformat", default="%Y-%m-%d_%H:%M:%S", metavar="STRFTIME_SPEC",
683 help="Default is `%(default)s`. For the strftime format, see "
684 "https://docs.python.org/3.11/library/datetime.html#strftime-strptime-behavior. "
685 f"Examples: `{argparser_escape('%Y-%m-%d_%H:%M:%S.%f')}` (adds microsecond resolution), "
686 f"`{argparser_escape('%Y-%m-%d_%H:%M:%S%z')}` (adds timezone offset), "
687 f"`{argparser_escape('%Y-%m-%dT%H-%M-%S')}` (no colons).\n\n"
688 "The name of the snapshot created on the src is `$org_$target_strftime(--create-src-snapshots-time*)_$period`. "
689 "Example: `tank/foo@prod_us-west_2024-09-03_12:26:15_daily`\n\n")
690 parser.add_argument(
691 "--create-src-snapshots-timezone", default="", type=str, metavar="TZ_SPEC",
692 help=f"Default is the local timezone of the system running {PROG_NAME}. When creating a new snapshot on the source, "
693 "fetch the current time in the specified timezone, and feed that time, and the value of "
694 "--create-src-snapshots-timeformat, into the standard strftime() function to generate the timestamp portion "
695 "of the snapshot name. The TZ_SPEC input parameter is of the form 'UTC' or '+HHMM' or '-HHMM' for fixed UTC "
696 "offsets, or an IANA TZ identifier for auto-adjustment to daylight savings time, or the empty string to use "
697 "the local timezone, for example '', 'UTC', '+0000', '+0530', '-0400', 'America/Los_Angeles', 'Europe/Vienna'. "
698 "For a list of valid IANA TZ identifiers see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List"
699 "\n\nTo change the timezone not only for snapshot name creation, but in all respects for the entire program, "
700 "use the standard 'TZ' Unix environment variable, like so: `export TZ=UTC`.\n\n")
701 parser.add_argument(
702 "--create-src-snapshots-even-if-not-due", action="store_true",
703 help="Take snapshots immediately regardless of the creation time of any existing snapshot, even if snapshots "
704 "are periodic and not actually due per the schedule.\n\n")
705 parser.add_argument(
706 "--zfs-send-program-opts", type=str, default="--raw --compressed", metavar="STRING",
707 help="Parameters to fine-tune 'zfs send' behaviour (optional); will be passed into 'zfs send' CLI. "
708 "The value is split on runs of one or more whitespace characters. "
709 "Default is '%(default)s'. To run `zfs send` without options, specify the empty "
710 "string: `--zfs-send-program-opts=''`. "
711 "See https://openzfs.github.io/openzfs-docs/man/master/8/zfs-send.8.html "
712 "and https://github.com/openzfs/zfs/issues/13024\n\n"
713 "If these options request a different effective raw or non-raw mode from the one recorded in an existing ZFS "
714 f"receive resume token, {PROG_NAME} aborts the token (clears the incomplete receive state) and then proceeds "
715 "as usual. ZFS may be unable to change the mode for an existing destination dataset. In that case, restore the "
716 "previous send options.\n\n")
717 parser.add_argument(
718 "--zfs-recv-program-opts", type=str, default="-u", metavar="STRING",
719 help="Parameters to fine-tune 'zfs receive' behaviour (optional); will be passed into 'zfs receive' CLI. "
720 "The value is split on runs of one or more whitespace characters. "
721 "Default is '%(default)s'. To run `zfs receive` without options, specify the empty "
722 "string: `--zfs-recv-program-opts=''`. "
723 "Example: '-u -o canmount=noauto -o readonly=on -x keylocation -x keyformat -x encryption'. "
724 "See https://openzfs.github.io/openzfs-docs/man/master/8/zfs-receive.8.html "
725 "and https://openzfs.github.io/openzfs-docs/man/master/7/zfsprops.7.html\n\n")
726 parser.add_argument(
727 "--zfs-recv-program-opt", action="append", default=[], metavar="STRING",
728 help="Parameter to fine-tune 'zfs receive' behaviour (optional); will be passed into 'zfs receive' CLI. "
729 "The value can contain spaces and is not split. This option can be specified multiple times. Example: `"
730 "--zfs-recv-program-opt=-o "
731 "--zfs-recv-program-opt='org.zfsbootmenu:commandline=ro debug zswap.enabled=1'`\n\n")
732 parser.add_argument(
733 "--preserve-properties", nargs="+", default=[], metavar="STRING",
734 help="On replication, preserve the current value of ZFS properties with the given names on the destination "
735 "datasets. The destination ignores the property value it zfs receive's from the source if the property name "
736 "matches one of the given blacklist values. This prevents a compromised or untrusted source from overwriting "
737 "security-critical properties on the destination. The default is to preserve none, i.e. an empty blacklist.\n\n"
738 "Example blacklist that protects against dangerous overwrites: "
739 "mountpoint overlay sharenfs sharesmb exec setuid devices encryption keyformat keylocation\n\n"
740 "See https://openzfs.github.io/openzfs-docs/man/master/7/zfsprops.7.html and "
741 "https://openzfs.github.io/openzfs-docs/man/master/8/zfs-receive.8.html#x\n\n"
742 "Note: --preserve-properties uses the 'zfs recv -x' option and thus requires either OpenZFS ≥ 2.2.0 "
743 "(see https://github.com/openzfs/zfs/commit/b0269cd8ced242e66afc4fa856d62be29bb5a4ff), or that "
744 "'zfs send --props' is not used.\n\n")
745 parser.add_argument(
746 "--force-rollback-to-latest-snapshot", action="store_true",
747 help="Before replication, rollback the destination dataset to its most recent destination snapshot (if there "
748 "is one), via 'zfs rollback', just in case the destination dataset was modified since its most recent "
749 "snapshot. This is much less invasive than the other --force* options (see below).\n\n")
750 parser.add_argument(
751 "--force-rollback-to-latest-common-snapshot", action="store_true",
752 help="Before replication, delete destination ZFS snapshots that are more recent than the most recent common "
753 "snapshot ('conflicting snapshots'), via 'zfs rollback'. Do no rollback if no common snapshot exists.\n\n")
754 parser.add_argument(
755 "--force", action="store_true",
756 help="Same as --force-rollback-to-latest-common-snapshot (see above), except that additionally, if no common "
757 "snapshot exists, then delete all destination snapshots before starting replication, and proceed "
758 "without aborting. Without the --force* flags, the destination dataset is treated as append-only, hence "
759 "no destination snapshot that already exists is deleted, and instead the operation is aborted with an "
760 "error when encountering a conflicting snapshot.\n\n"
761 "Analogy: --force-rollback-to-latest-snapshot is a tiny hammer, whereas "
762 "--force-rollback-to-latest-common-snapshot is a medium sized hammer, --force is a large hammer, and "
763 "--force-destroy-dependents is a very large hammer. "
764 "Consider using the smallest hammer that can fix the problem. No hammer is ever used by default.\n\n")
765 parser.add_argument(
766 "--force-destroy-dependents", action="store_true",
767 help="On destination, --force and --force-rollback-to-latest-common-snapshot and --delete-* will add the "
768 "'-R' flag to their use of 'zfs rollback' and 'zfs destroy', causing them to delete dependents such as "
769 "clones and bookmarks. This can be very destructive and is rarely advisable.\n\n")
770 parser.add_argument(
771 "--force-unmount", action="store_true",
772 help="On destination, --force and --force-rollback-to-latest-common-snapshot will add the '-f' flag to their "
773 "use of 'zfs rollback' and 'zfs destroy'.\n\n")
774 parser.add_argument(
775 "--force-once", "--f1", action="store_true",
776 help="Use the --force option or --force-rollback-to-latest-common-snapshot option at most once to resolve a "
777 "conflict, then abort with an error on any subsequent conflict. This helps to interactively resolve "
778 "conflicts, one conflict at a time.\n\n")
779 parser.add_argument(
780 "--skip-parent", action="store_true",
781 help="During replication and deletion, skip processing of the SRC_DATASET and DST_DATASET and only process "
782 "their descendant datasets, i.e. children, and children of children, etc (with --recursive). No dataset "
783 "is processed unless --recursive is also specified. "
784 f"Analogy: `{PROG_NAME} --recursive --skip-parent src dst` is akin to Unix `cp -r src/* dst/` whereas "
785 f" `{PROG_NAME} --recursive --skip-parent --skip-replication --delete-dst-datasets dummy dst` is akin to "
786 "Unix `rm -r dst/*`\n\n")
787 parser.add_argument(
788 "--skip-missing-snapshots", choices=["fail", "dataset", "continue"], default="dataset", nargs="?",
789 help="During replication, handle source datasets that select no snapshots (and no relevant bookmarks) "
790 "as follows:\n\n"
791 "a) 'fail': Abort with an error.\n\n"
792 "b) 'dataset' (default): Skip the source dataset with a warning. Skip descendant datasets if "
793 "--recursive and destination dataset does not exist. Otherwise skip to the next dataset.\n\n"
794 "c) 'continue': Skip nothing. If destination snapshots exist, delete them (with --force) or abort "
795 "with an error (without --force). If there is no such abort, continue processing with the next dataset. "
796 "Eventually create empty destination dataset and ancestors if they do not yet exist and source dataset "
797 "has at least one descendant that selects at least one snapshot.\n\n")
798 parser.add_argument(
799 "--retries", dest="max_retries", type=int, min=0, default=2, action=CheckRange, metavar="INT",
800 help="The maximum number of times a retryable replication or deletion step shall be retried if it fails, for "
801 "example because of network hiccups (default: %(default)s, min: %(min)s). "
802 "Also consider this option if a periodic pruning script may simultaneously delete a dataset or "
803 f"snapshot or bookmark while {PROG_NAME} is running and attempting to access it.\n\n")
804 parser.add_argument(
805 "--retry-min-sleep-secs", type=float, min=0, default=0, action=CheckRange, metavar="FLOAT",
806 help="The minimum duration to sleep between retries (default: %(default)s).\n\n")
807 parser.add_argument(
808 "--retry-initial-max-sleep-secs", type=float, min=0, default=0.125, action=CheckRange, metavar="FLOAT",
809 help="The initial maximum duration to sleep between retries (default: %(default)s).\n\n")
810 parser.add_argument(
811 "--retry-max-sleep-secs", type=float, min=0, default=5 * 60, action=CheckRange, metavar="FLOAT",
812 help="The maximum duration to sleep between retries initially starts with --retry-initial-max-sleep-secs "
813 "(see above), and doubles on each retry, up to the final maximum of --retry-max-sleep-secs "
814 "(default: %(default)s). On each retry a random sleep time in the [--retry-min-sleep-secs, current max] range "
815 "is picked. In a nutshell: retry-min-sleep-secs ≤ retry-initial-max-sleep-secs ≤ retry-max-sleep-secs. "
816 "The timer resets after each operation.\n\n")
817 parser.add_argument(
818 "--retry-max-elapsed-secs", type=float, min=0, default=60 * 60, action=CheckRange, metavar="FLOAT",
819 help="A single operation (e.g. 'zfs send/receive' of the current dataset, or deletion of a list of snapshots "
820 "within the current dataset) will not be retried (or not retried anymore) once this much time has elapsed "
821 "since the initial start of the operation, including retries (default: %(default)s). "
822 "The timer resets after each operation completes or retries exhaust, such that subsequently failing "
823 "operations can again be retried.\n\n")
824 parser.add_argument(
825 "--skip-on-error", choices=["fail", "tree", "dataset"], default=SKIP_ON_ERROR_DEFAULT,
826 help="During replication and deletion, if an error is not retryable, or --retries has been exhausted, "
827 "or --skip-missing-snapshots raises an error, proceed as follows:\n\n"
828 "a) 'fail': Abort the program with an error. This mode is ideal for testing, clear "
829 "error reporting, and situations where consistency trumps availability.\n\n"
830 "b) 'tree': Log the error, skip the dataset tree rooted at the dataset for which the error "
831 "occurred, and continue processing the next (sibling) dataset tree. "
832 "Example: Assume datasets tank/user1/foo and tank/user2/bar and an error occurs while processing "
833 "tank/user1. In this case processing skips tank/user1/foo and proceeds with tank/user2.\n\n"
834 "c) 'dataset' (default): Same as 'tree' except if the destination dataset already exists, skip to "
835 "the next dataset instead.\n\n"
836 "Example: Assume datasets tank/user1/foo and tank/user2/bar and an error occurs while "
837 "processing tank/user1. In this case processing skips tank/user1 and proceeds with tank/user1/foo "
838 "if the destination already contains tank/user1. Otherwise processing continues with tank/user2. "
839 "This mode is for production use cases that require timely forward progress even in the presence of "
840 "partial failures. For example, assume the job is to backup the home directories or virtual machines "
841 "of thousands of users across an organization. Even if replication of some of the datasets for some "
842 "users fails due too conflicts, busy datasets, etc, the replication job will continue for the "
843 "remaining datasets and the remaining users.\n\n")
844 parser.add_argument(
845 "--skip-replication", action="store_true",
846 help="Skip replication step (see above) and proceed to the optional --delete-dst-datasets step "
847 "immediately (see below).\n\n")
848 parser.add_argument(
849 "--delete-dst-datasets", action="store_true",
850 help="Do nothing if the --delete-dst-datasets option is missing. Otherwise, after successful replication "
851 "step, if any, delete existing destination datasets that are selected via --{include|exclude}-dataset* "
852 "policy yet do not exist within SRC_DATASET (which can be an empty dataset, such as the hardcoded virtual "
853 f"dataset named '{DUMMY_DATASET}'!). Do not recurse without --recursive. With --recursive, never delete "
854 "non-selected dataset subtrees or their ancestors.\n\n"
855 "For example, if the destination contains datasets h1,h2,h3,d1 whereas source only contains h3, "
856 "and the include/exclude policy selects h1,h2,h3,d1, then delete datasets h1,h2,d1 on "
857 "the destination to make it 'the same'. On the other hand, if the include/exclude policy "
858 "only selects h1,h2,h3 then only delete datasets h1,h2 on the destination to make it 'the same'.\n\n"
859 "Example to delete all tmp datasets within tank2/boo/bar: "
860 f"`{PROG_NAME} {DUMMY_DATASET} tank2/boo/bar --dryrun --skip-replication --recursive "
861 "--delete-dst-datasets --include-dataset-regex '(.*/)?tmp.*' --exclude-dataset-regex '!.*'`\n\n")
862 parser.add_argument(
863 "--delete-dst-snapshots", choices=["snapshots", "bookmarks"], default=None, const="snapshots", nargs="?",
864 help="Do nothing if the --delete-dst-snapshots option is missing. Otherwise, after successful "
865 "replication, and successful --delete-dst-datasets step, if any, delete existing destination snapshots "
866 "whose GUID does not exist within the source dataset (which can be an empty dummy dataset!) if the "
867 "destination snapshots are selected by the --include/exclude-snapshot-* policy, and the destination "
868 "dataset is selected via --{include|exclude}-dataset* policy. Does not recurse without --recursive.\n\n"
869 "For example, if the destination dataset contains snapshots h1,h2,h3,d1 (h=hourly, d=daily) whereas "
870 "the source dataset only contains snapshot h3, and the include/exclude policy selects "
871 "h1,h2,h3,d1, then delete snapshots h1,h2,d1 on the destination dataset to make it 'the same'. "
872 "On the other hand, if the include/exclude policy only selects snapshots h1,h2,h3 then only "
873 "delete snapshots h1,h2 on the destination dataset to make it 'the same'.\n\n"
874 "*Note:* To delete snapshots regardless, consider using --delete-dst-snapshots in combination with a "
875 f"source that is an empty dataset, such as the hardcoded virtual dataset named '{DUMMY_DATASET}', like so:"
876 f" `{PROG_NAME} {DUMMY_DATASET} tank2/boo/bar --dryrun --skip-replication --delete-dst-snapshots "
877 "--include-snapshot-regex '.*_daily' --recursive`\n\n"
878 "*Note:* Use --delete-dst-snapshots=bookmarks to delete non-temporary bookmarks instead of snapshots, in "
879 "which case no snapshots are selected and the --{include|exclude}-snapshot-* filter options treat bookmarks "
880 "as snapshots wrt. selecting.\n\n"
881 "*Note:* Does not attempt to delete snapshots that carry a `zfs hold`; instead auto-skips them without "
882 "failing.\n\n"
883 "*Performance Note:* --delete-dst-snapshots operates on multiple datasets in parallel (and serially "
884 f"within a dataset), using the same dataset order as {PROG_NAME} replication. "
885 "The degree of parallelism is configurable with the --threads option (see below).\n\n")
886 parser.add_argument(
887 "--force-delete-dst-tmp-bookmarks", action="store_true",
888 help=argparse.SUPPRESS)
889 parser.add_argument(
890 "--delete-dst-snapshots-no-crosscheck", action="store_true",
891 help="This flag indicates that --delete-dst-snapshots=snapshots shall check the source dataset only for "
892 "a snapshot with the same GUID, and ignore whether a bookmark with the same GUID is present in the "
893 "source dataset. Similarly, it also indicates that --delete-dst-snapshots=bookmarks shall check the source "
894 "dataset only for a bookmark with the same GUID, and ignore whether a snapshot with the same GUID is present "
895 "in the source dataset.\n\n")
896 parser.add_argument(
897 "--delete-dst-snapshots-except", action="store_true",
898 help="This flag indicates that the --include/exclude-snapshot-* options shall have inverted semantics for the "
899 "--delete-dst-snapshots option, thus deleting all snapshots except for the selected snapshots (within the "
900 "specified datasets), instead of deleting all selected snapshots (within the specified datasets). In other "
901 "words, this flag enables to specify which snapshots to retain instead of which snapshots to delete.\n\n"
902 "*Synchronization vs. Backup*: When a real (non-dummy) source dataset is specified in combination with "
903 "--delete-dst-snapshots-except, then any destination snapshot retained by the rules above is actually only "
904 "retained if it also exists in the source dataset - __all other destination snapshots are deleted__. This is "
905 "great for synchronization use cases but should __NEVER BE USED FOR LONG-TERM ARCHIVAL__. Long-term archival "
906 "use cases should instead specify the `dummy` source dataset as they require an independent retention policy "
907 "that is not tied to the current contents of the source dataset.\n\n")
908 parser.add_argument(
909 "--delete-dst-snapshots-except-plan", action=DeleteDstSnapshotsExceptPlanAction, default=None, metavar="DICT_STRING",
910 help="Retention periods to be used if pruning snapshots or bookmarks within the selected destination datasets via "
911 "--delete-dst-snapshots. Has the same format as --create-src-snapshots-plan. "
912 "Snapshots (--delete-dst-snapshots=snapshots) or bookmarks (with --delete-dst-snapshots=bookmarks) that "
913 "do not match a period will be deleted. To avoid unexpected surprises, make sure to carefully specify ALL "
914 "snapshot names and periods that shall be retained, in combination with --dryrun.\n\n"
915 f"Example: `{format_dict(src_snapshot_plan_example)}`. This example will, for the organization 'prod' and "
916 "the intended logical target 'onsite', retain secondly snapshots that were created less than 40 seconds ago, "
917 "yet retain the latest 40 secondly snapshots regardless of creation time. Analog for the latest 40 minutely "
918 "snapshots, latest 36 hourly snapshots, etc. "
919 "It will also retain snapshots for the targets 'us-west' and 'eu-west' within the 'prod' organization. "
920 "In addition, within the 'test' organization, it will retain snapshots that are created every 12 hours and "
921 "every week as specified, and name them as being intended for the 'offsite' replication target. Analog for "
922 "snapshots that are taken every 100 milliseconds within the 'test' organization. "
923 "All other snapshots within the selected datasets will be deleted - you've been warned!\n\n"
924 "The example scans the selected ZFS datasets for snapshots with names like "
925 "`prod_onsite_<timestamp>_secondly`, `prod_onsite_<timestamp>_minutely`, "
926 "`prod_us-west_<timestamp>_hourly`, `prod_us-west_<timestamp>_daily`, "
927 "`prod_eu-west_<timestamp>_hourly`, `prod_eu-west_<timestamp>_daily`, "
928 "`test_offsite_<timestamp>_12hourly`, `test_offsite_<timestamp>_weekly`, and so on, and deletes all snapshots "
929 "that do not match a retention rule.\n\n"
930 "Note: A zero within a period (e.g. 'hourly': 0) indicates that no snapshots shall be retained for the given "
931 "period.\n\n"
932 "Note: --delete-dst-snapshots-except-plan is a convenience option that auto-generates a series of the "
933 "following other options: --delete-dst-snapshots-except, "
934 "--new-snapshot-filter-group, --include-snapshot-regex, --include-snapshot-times-and-ranks\n\n")
935 parser.add_argument(
936 "--delete-empty-dst-datasets", choices=["snapshots", "snapshots+bookmarks"], default=None,
937 const="snapshots+bookmarks", nargs="?",
938 help="Do nothing if the --delete-empty-dst-datasets option is missing or --recursive is missing. Otherwise, "
939 "after successful replication "
940 "step and successful --delete-dst-datasets and successful --delete-dst-snapshots steps, if any, "
941 "delete any selected destination dataset that has no snapshot and no bookmark if all descendants of "
942 "that destination dataset are also selected and do not have a snapshot or bookmark either "
943 "(again, only if the existing destination dataset is selected via --{include|exclude}-dataset* policy). "
944 "Never delete non-selected dataset subtrees or their ancestors.\n\n"
945 "For example, if the destination contains datasets h1,d1, and the include/exclude policy "
946 "selects h1,d1, then check if h1,d1 can be deleted. "
947 "On the other hand, if the include/exclude policy only selects h1 then only check if h1 can be deleted.\n\n"
948 "*Note:* Use --delete-empty-dst-datasets=snapshots to delete snapshot-less datasets even if they still "
949 "contain bookmarks.\n\n")
950 monitor_snapshot_plan_example = {
951 "prod": {
952 "onsite": {
953 "100millisecondly": {"latest": {"warning": "300 milliseconds", "critical": "2 seconds"}},
954 "secondly": {"latest": {"warning": "2 seconds", "critical": "14 seconds"}},
955 "minutely": {"latest": {"warning": "30 seconds", "critical": "300 seconds"}},
956 "hourly": {"latest": {"warning": "30 minutes", "critical": "300 minutes"}},
957 "daily": {"latest": {"warning": "4 hours", "critical": "8 hours"}},
958 "weekly": {"latest": {"warning": "2 days", "critical": "8 days"}},
959 "monthly": {"latest": {"warning": "2 days", "critical": "8 days"}},
960 "yearly": {"latest": {"warning": "5 days", "critical": "14 days"}},
961 "10minutely": {"latest": {"warning": "0 minutes", "critical": "0 minutes"}},
962 },
963 "": {
964 "daily": {"latest": {"warning": "4 hours", "critical": "8 hours"}},
965 },
966 },
967 }
968 monitor_snapshots_output_example: str = (
969 "`--monitor_snapshots: OK. Latest snapshot for tank/foo@prod_<timestamp>_daily is 4.18h old: @prod_2025-01-10_08:30:05_daily`\n\n"
970 "`--monitor_snapshots: OK. Latest snapshot for tank/bar@prod_<timestamp>_daily is 4.18h old: @prod_2025-01-10_08:30:05_daily`\n\n"
971 "`--monitor_snapshots: Latest snapshot for tank/baz@prod_<timestamp>_daily is 1.2d old but should be at most 1.1d old: @prod_2025-01-09_08:30:05_daily`\n\n"
972 " ...\n\n"
973 "`ERROR: Exiting bzfs with status code 2. Cause: --monitor_snapshots: Latest snapshot for tank/baz@prod_<timestamp>_daily is 1.2d old but should be at most 1.1d old: @prod_2025-01-09_08:30:05_daily`\n\n"
974 )
975 parser.add_argument(
976 "--monitor-snapshots", default="{}", type=str, metavar="DICT_STRING",
977 help="Do nothing if the --monitor-snapshots flag is missing. Otherwise, after all other steps, "
978 "alert the user if the ZFS 'creation' time property of the latest snapshot for any specified snapshot name "
979 "pattern within the selected datasets is too old wrt. the specified age limit. The purpose is to check if "
980 "snapshots are successfully taken on schedule, successfully replicated on schedule, and successfully pruned on "
981 "schedule. Process exit code is 0, 1, 2 on OK, WARNING, CRITICAL, respectively. "
982 f"Example DICT_STRING: `{format_dict(monitor_snapshot_plan_example)}`. "
983 "This example alerts the user if the latest src or dst snapshot named `prod_onsite_<timestamp>_hourly` is more "
984 "than 30 minutes late (i.e. more than 30+60=90 minutes old) [warning] or more than 300 minutes late (i.e. more "
985 "than 300+60=360 minutes old) [critical]. "
986 "Analog for the latest snapshot named `prod_<timestamp>_daily`, and so on.\n\n"
987 "Note: A duration that is missing or zero (e.g. '0 minutes') indicates that no snapshots shall be checked for "
988 "the given snapshot name pattern.\n\n"
989 f"Example output with `--verbose`:\n\n{monitor_snapshots_output_example}\n\n")
990 parser.add_argument(
991 "--monitor-snapshots-dont-warn", action="store_true",
992 help="Log a message for monitoring warnings but nonetheless exit with zero exit code.\n\n")
993 parser.add_argument(
994 "--monitor-snapshots-dont-crit", action="store_true",
995 help="Log a message for monitoring criticals but nonetheless exit with zero exit code.\n\n")
996 parser.add_argument(
997 "--monitor-snapshots-no-latest-check", action="store_true",
998 # help="Disable monitoring check of latest snapshot.\n\n")
999 help=argparse.SUPPRESS)
1000 parser.add_argument(
1001 "--monitor-snapshots-no-oldest-check", action="store_true",
1002 # help="Disable monitoring check of oldest snapshot.\n\n")
1003 help=argparse.SUPPRESS)
1004 cmp_choices_dflt: str = "+".join(CMP_CHOICES_ITEMS)
1005 cmp_choices: list[str] = []
1006 for i in range(len(CMP_CHOICES_ITEMS)):
1007 cmp_choices += ["+".join(c) for c in itertools.combinations(CMP_CHOICES_ITEMS, i + 1)]
1008 parser.add_argument(
1009 "--compare-snapshot-lists", choices=cmp_choices, default="", const=cmp_choices_dflt, nargs="?",
1010 help="Do nothing if the --compare-snapshot-lists option is missing. Otherwise, after successful replication "
1011 "step and successful --delete-dst-datasets, --delete-dst-snapshots steps and --delete-empty-dst-datasets "
1012 "steps, if any, proceed as follows:\n\n"
1013 "Compare source and destination dataset trees recursively wrt. snapshots, for example to check if all "
1014 "recently taken snapshots have been successfully replicated by a periodic job.\n\n"
1015 "Example: List snapshots only contained in source (tagged with 'src'), only contained in destination "
1016 "(tagged with 'dst'), and contained in both source and destination (tagged with 'all'), restricted to "
1017 "hourly and daily snapshots taken within the last 7 days, excluding the last 4 hours (to allow for some "
1018 "slack/stragglers), excluding temporary datasets: "
1019 f"`{PROG_NAME} tank1/foo/bar tank2/boo/bar --skip-replication "
1020 "--compare-snapshot-lists=src+dst+all --recursive --include-snapshot-regex '.*_(hourly|daily)' "
1021 "--include-snapshot-times-and-ranks '7 days ago..4 hours ago' --exclude-dataset-regex 'tmp.*'`\n\n"
1022 "This outputs a TSV file containing the following columns:\n\n"
1023 "`location creation_iso createtxg rel_name guid root_dataset rel_dataset name creation written`\n\n"
1024 "Example output row:\n\n"
1025 "`src 2024-11-06_08:30:05 17435050 /foo@test_2024-11-06_08:30:05_daily 2406491805272097867 tank1/src "
1026 "/foo tank1/src/foo@test_2024-10-06_08:30:04_daily 1730878205 24576`\n\n"
1027 "If the TSV output file contains zero lines starting with the prefix 'src' and zero lines starting with "
1028 "the prefix 'dst' then no source snapshots are missing on the destination, and no destination "
1029 "snapshots are missing on the source, indicating that the periodic replication and pruning jobs perform "
1030 "as expected. The TSV output is sorted by rel_dataset, and by ZFS creation time within each rel_dataset "
1031 "- the first and last line prefixed with 'all' contains the metadata of the oldest and latest common "
1032 "snapshot, respectively. Third party tools can use this info for post-processing, for example using "
1033 "custom scripts using 'csplit' or duckdb analytics queries.\n\n"
1034 "The --compare-snapshot-lists option also directly logs [various summary stats]"
1035 "(https://github.com/whoschek/bzfs/blob/main/bzfs_docs/compare-snapshot-lists-example.log), "
1036 "such as the metadata of the latest common snapshot, latest snapshots and oldest snapshots, as well as the "
1037 "time diff between the latest common snapshot and latest snapshot only in src (and only in dst), as well as "
1038 "how many src snapshots and how many GB of data are missing on dst, etc.\n\n"
1039 "*Note*: By default, if the source ZFS pool supports bookmarks, source bookmarks also participate in the "
1040 "comparison. A source bookmark and destination snapshot with the same GUID are considered to be contained "
1041 "in both locations, even if the corresponding source snapshot has already been deleted. Unmatched temporary "
1042 f"bookmarks managed by {PROG_NAME} remain hidden. Specify --no-use-bookmark to compare snapshots only.\n\n"
1043 "*Note*: Consider omitting the 'all' flag to reduce noise and instead focus on missing snapshots only, "
1044 "like so: --compare-snapshot-lists=src+dst \n\n"
1045 "*Note*: The source can also be an empty dataset, such as the hardcoded virtual dataset named "
1046 f"'{DUMMY_DATASET}'.\n\n"
1047 "*Note*: --compare-snapshot-lists is typically *much* faster than standard 'zfs list -t snapshot' CLI "
1048 "usage because the former issues requests with a higher degree of parallelism than the latter. The "
1049 "degree is configurable with the --threads option (see below).\n\n")
1050 parser.add_argument(
1051 "--cache-snapshots", action="store_true",
1052 help="If --cache-snapshots is specified, maintain a persistent local cache of recent snapshot creation times, "
1053 "recent successful replication times, and recent monitoring times, and compare them to a quick "
1054 "'zfs list -t filesystem,volume -p -o snapshots_changed' to help determine if a new snapshot shall be created "
1055 "on the src, and if there are any changes that need to be replicated or monitored. Enabling the cache "
1056 "improves performance if --create-src-snapshots and/or replication and/or --monitor-snapshots is invoked "
1057 "frequently (e.g. every minute via cron) over a large number of datasets, with each dataset containing a large "
1058 "number of snapshots, yet it is seldom for a new src snapshot to actually be created, or there are seldom any "
1059 "changes to replicate or monitor (e.g. a snapshot is only created every day and/or deleted every day).\n\n"
1060 "*Note:* This flag only has an effect on OpenZFS ≥ 2.2.\n\n"
1061 "*Note:* This flag is only relevant for snapshot creation on the src if --create-src-snapshots-even-if-not-due "
1062 "is not specified.\n\n")
1063 parser.add_argument(
1064 "--dryrun", "-n", choices=["recv", "send"], default=None, const="send", nargs="?",
1065 help="Do a dry run (aka 'no-op') to print what operations would happen if the command were to be executed "
1066 "for real (optional). This option treats both the ZFS source and destination as read-only. "
1067 "Accepts an optional argument for fine tuning that is handled as follows:\n\n"
1068 "a) 'recv': Send snapshot data via 'zfs send' to the destination host and receive it there via "
1069 "'zfs receive -n', which discards the received data there.\n\n"
1070 "b) 'send': Do not execute 'zfs send' and do not execute 'zfs receive'. This is a less 'realistic' form "
1071 "of dry run, but much faster, especially for large snapshots and slow networks/disks, as no snapshot is "
1072 "actually transferred between source and destination. This is the default when specifying --dryrun.\n\n"
1073 "Examples: --dryrun, --dryrun=send, --dryrun=recv\n\n")
1074 parser.add_argument(
1075 "--verbose", "-v", action="count", default=0,
1076 help="Print verbose information. This option can be specified multiple times to increase the level of "
1077 "verbosity. To print what ZFS/SSH operation exactly is happening (or would happen), add the `-v -v -v` "
1078 "flag, maybe along with --dryrun. All ZFS and SSH commands (even with --dryrun) are logged such that "
1079 "they can be inspected, copy-and-pasted into a terminal shell and run manually to help anticipate or "
1080 "diagnose issues. ERROR, WARN, INFO, DEBUG, TRACE output lines are identified by [E], [W], [I], [D], [T] "
1081 "prefixes, respectively.\n\n")
1082 parser.add_argument(
1083 "--quiet", "-q", action="store_true",
1084 help="Suppress non-error, info, debug, and trace output.\n\n")
1085 parser.add_argument(
1086 "--no-privilege-elevation", "-p", action="store_true",
1087 help="Do not attempt to run state changing ZFS operations 'zfs create/rollback/destroy/send/receive/snapshot' as "
1088 "root (via 'sudo -u root' elevation granted by administrators appending the following to /etc/sudoers: "
1089 "`<NON_ROOT_USER_NAME> ALL=NOPASSWD:/path/to/zfs`\n\n"
1090 "Instead, the --no-privilege-elevation flag is for non-root users that have been granted corresponding "
1091 "ZFS permissions by administrators via 'zfs allow' delegation mechanism, like so: "
1092 "sudo zfs allow -u $SRC_NON_ROOT_USER_NAME snapshot,destroy,send,bookmark,hold $SRC_DATASET; "
1093 "sudo zfs allow -u $DST_NON_ROOT_USER_NAME mount,create,receive,rollback,destroy $DST_DATASET_OR_POOL.\n\n"
1094 "If you do not plan to use the --force* flags and --delete-* CLI options then ZFS permissions "
1095 "'rollback,destroy' can be omitted, arriving at the absolutely minimal set of required destination "
1096 "permissions: `mount,create,receive`.\n\n"
1097 "For extra security $SRC_NON_ROOT_USER_NAME should be different than $DST_NON_ROOT_USER_NAME, i.e. the "
1098 "sending Unix user on the source and the receiving Unix user at the destination should be separate Unix "
1099 "user accounts with separate private keys even if both accounts reside on the same machine, per the "
1100 "principle of least privilege.\n\n"
1101 "Also see https://openzfs.github.io/openzfs-docs/man/master/8/zfs-allow.8.html#EXAMPLES and "
1102 "https://tinyurl.com/9h97kh8n and "
1103 "https://youtu.be/o_jr13Z9f1k?si=7shzmIQJpzNJV6cq\n\n")
1104 parser.add_argument(
1105 "--no-stream", action="store_true",
1106 help="During replication, only replicate the most recent selected source snapshot of a dataset (using -i "
1107 "incrementals instead of -I incrementals), hence skip all intermediate source snapshots that may exist "
1108 "between that and the most recent common snapshot. If there is no common snapshot also skip all other "
1109 "source snapshots for the dataset, except for the most recent selected source snapshot. This option helps "
1110 "the destination to 'catch up' with the source ASAP, consuming a minimum of disk space, at the expense "
1111 "of reducing reliable options for rolling back to intermediate snapshots in the future.\n\n")
1112 parser.add_argument(
1113 "--no-resume-recv", action="store_true",
1114 help="Replication of snapshots via 'zfs send/receive' can be interrupted by intermittent network hiccups, "
1115 "reboots, hardware issues, etc. Interrupted 'zfs send/receive' operations are retried if the --retries "
1116 f"and --retry-* options enable it (see above). In normal operation {PROG_NAME} automatically retries "
1117 "such that only the portion of the snapshot is transmitted that has not yet been fully received on the "
1118 "destination. For example, this helps to progressively transfer a large individual snapshot over a "
1119 "wireless network in a timely manner despite frequent intermittent network hiccups. This optimization is "
1120 "called 'resume receive' and uses the 'zfs receive -s' and 'zfs send -t' feature.\n\n"
1121 "The --no-resume-recv option disables this optimization such that a retry now retransmits the entire "
1122 "snapshot from scratch, which could slow down or even prohibit progress in case of frequent network "
1123 f"hiccups. {PROG_NAME} automatically falls back to using the --no-resume-recv option if it is "
1124 "auto-detected that the ZFS pool does not reliably support the 'resume receive' optimization.\n\n"
1125 "*Note:* Snapshots that have already been fully transferred as part of the current 'zfs send/receive' "
1126 "operation need not be retransmitted regardless of the --no-resume-recv flag. For example, assume "
1127 "a single 'zfs send/receive' operation is transferring incremental snapshots 1 through 10 via "
1128 "'zfs send -I', but the operation fails while transferring snapshot 10, then snapshots 1 through 9 "
1129 "need not be retransmitted regardless of the --no-resume-recv flag, as these snapshots have already "
1130 "been successfully received at the destination either way.\n\n")
1131 parser.add_argument(
1132 "--create-bookmarks", choices=["all", "hourly", "minutely", "secondly", "none"], default="all",
1133 help=f"For increased safety, {PROG_NAME} replication behaves as follows wrt. ZFS bookmark creation, if it is "
1134 "autodetected that the source ZFS pool supports bookmarks:\n\n"
1135 "* `all` (default): Selects every source snapshot that will be sent during each 'zfs send' operation. "
1136 "This increases safety at the expense of a little performance.\n\n"
1137 "* `hourly`: Selects each hourly, daily, weekly, monthly and yearly source snapshot that will be sent.\n\n"
1138 "* `minutely` and `secondly`: Same as `hourly` except that it also selects minutely and secondly snapshots, "
1139 "respectively.\n\n"
1140 "* `none`: No bookmark is created.\n\n"
1141 "For every mode except `none`, the snapshot of a full send and the final snapshot of incremental "
1142 "replication are always selected as they establish the initial and latest common bases, respectively.\n\n"
1143 f"For each selected source snapshot, {PROG_NAME} creates a destination-specific temporary bookmark before "
1144 "starting its 'zfs send/receive' operation. After the operation succeeds, it renames the temporary bookmark "
1145 "to a finalized bookmark and deletes any obsolete temporary bookmarks for that destination. Both temporary "
1146 "and finalized bookmarks can serve as sources for future incremental replication once the corresponding "
1147 f"snapshot exists on the destination. This guarantees continuity even if the {PROG_NAME} process is killed "
1148 "after 'zfs send/receive' succeeds but before bookmark finalization.\n\n"
1149 "Bookmarks exist so an incremental stream can continue to be sent from the source dataset without having "
1150 "to keep the already replicated snapshot around on the source dataset until the next upcoming snapshot "
1151 "has been successfully replicated. This way you can bookmark a snapshot on the source dataset, send the "
1152 "snapshot to another host, then delete the snapshot from the source dataset to save disk space, and then "
1153 "still incrementally send the next upcoming snapshot from the source dataset to the other host by "
1154 "referring to the bookmark.\n\n"
1155 "The --create-bookmarks=none option disables this safety feature but is discouraged, because bookmarks "
1156 "are tiny and relatively cheap and help to ensure that ZFS replication can continue even if source and "
1157 "destination dataset somehow have no common snapshot anymore. "
1158 "For example, if a pruning script has accidentally deleted too many (or even all) snapshots on the "
1159 "source dataset in an effort to reclaim disk space, replication can still proceed because it can use "
1160 "the info in the bookmark (the bookmark must still exist in the source dataset) instead of the info in "
1161 "the metadata of the (now missing) source snapshot.\n\n"
1162 "A ZFS bookmark is a tiny bit of metadata extracted from a ZFS snapshot by the 'zfs bookmark' CLI, and "
1163 "attached to a dataset, much like a ZFS snapshot. Note that a ZFS bookmark does not contain user data; "
1164 "instead a ZFS bookmark is essentially a tiny pointer in the form of the GUID of the snapshot and 64-bit "
1165 "transaction group number of the snapshot and creation time of the snapshot, which is sufficient to tell "
1166 "the destination ZFS pool how to find the destination snapshot corresponding to the source bookmark "
1167 "and (potentially already deleted) source snapshot. A bookmark can be fed into 'zfs send' as the "
1168 "source of an incremental send. Note that while a bookmark allows for its snapshot "
1169 "to be deleted on the source after successful replication, it still requires that its snapshot is not "
1170 "somehow deleted prematurely on the destination dataset, so be mindful of that. "
1171 "Also see https://www.youtube.com/watch?v=LaNgoAZeTww&t=316s.\n\n"
1172 f"By convention, a finalized bookmark created by {PROG_NAME} has the same name as its corresponding "
1173 "snapshot, except the name also contains the snapshot GUID for uniqueness. Destination-specific temporary "
1174 "bookmarks use names that begin with `.TMPBZFS.`; this namespace is reserved for internal use. Do not create "
1175 f"or delete such temporary bookmarks because {PROG_NAME} automatically manages and garbage collects them.\n\n"
1176 "You can list bookmarks, like so: "
1177 "`zfs list -t bookmark -o name,guid,createtxg,creation -d 1 $SRC_DATASET`, and you can (and should) "
1178 "periodically prune obsolete bookmarks just like snapshots, like so: "
1179 "`zfs destroy $SRC_DATASET#$BOOKMARK`. Typically, bookmarks should be pruned less aggressively "
1180 "than snapshots, and destination snapshots should be pruned less aggressively than source snapshots. "
1181 "As an example starting point, here is a command that deletes all non-temporary bookmarks older than "
1182 "90 days, but retains the latest 200 non-temporary bookmarks (per dataset) regardless of creation time: "
1183 f"`{PROG_NAME} {DUMMY_DATASET} tank2/boo/bar --dryrun --recursive --skip-replication "
1184 "--delete-dst-snapshots=bookmarks --include-snapshot-times-and-ranks notime 'all except latest 200' "
1185 "--include-snapshot-times-and-ranks 'anytime..90 days ago'`\n\n")
1186 parser.add_argument(
1187 "--no-use-bookmark", action="store_true",
1188 help=f"For increased safety, in normal replication operation {PROG_NAME} replication also looks for bookmarks "
1189 "(in addition to snapshots) on the source dataset in order to find the most recent common snapshot wrt. the "
1190 "destination dataset, if it is auto-detected that the source ZFS pool supports bookmarks. "
1191 "The --no-use-bookmark option disables this safety feature but is discouraged, because bookmarks help "
1192 "to ensure that ZFS replication can continue even if source and destination dataset somehow have no "
1193 "common snapshot anymore.\n\n"
1194 f"Note that it does not matter whether a bookmark was created by {PROG_NAME} or a third party script, "
1195 "as only the GUID of the bookmark and the GUID of the snapshot is considered for comparison, and ZFS "
1196 "guarantees that any bookmark of a given snapshot automatically has the same GUID, transaction group "
1197 "number and creation time as the snapshot. Apart from the internal `.TMPBZFS.` namespace described above, "
1198 "you can create, delete and prune bookmarks any way you like, as "
1199 f"{PROG_NAME} (without --no-use-bookmark) will happily work with whatever bookmarks currently exist, if any.\n\n")
1201 ssh_cipher_default = "^aes256-gcm@openssh.com"
1202 # ^aes256-gcm@openssh.com cipher: for speed with confidentiality and integrity
1203 # measure cipher perf like so: count=5000; for i in $(seq 1 3); do echo "iteration $i:"; for cipher in $(ssh -Q cipher); do dd if=/dev/zero bs=1M count=$count 2> /dev/null | ssh -c $cipher -p 40999 127.0.0.1 "(time -p cat) > /dev/null" 2>&1 | grep real | awk -v count=$count -v cipher=$cipher '{print cipher ": " count / $2 " MB/s"}'; done; done
1204 # see https://web.archive.org/web/20251011105141if_/https://gbe0.com/posts/linux/server/benchmark-ssh-ciphers/
1205 # and https://crypto.stackexchange.com/questions/43287/what-are-the-differences-between-these-aes-ciphers
1206 parser.add_argument(
1207 "--ssh-cipher", type=str, default=ssh_cipher_default, metavar="STRING",
1208 help="SSH cipher specification for encrypting the session (optional); will be passed into ssh -c CLI. "
1209 "--ssh-cipher is a comma-separated list of ciphers listed in order of preference. See the 'Ciphers' "
1210 "keyword in ssh_config(5) for more information: "
1211 "https://manpages.ubuntu.com/manpages/latest/man5/ssh_config.5.html. Default: `%(default)s`\n\n")
1213 locations = ["src", "dst"]
1214 for loc in locations:
1215 parser.add_argument(
1216 f"--ssh-{loc}-user", type=str, metavar="STRING",
1217 help=f"Remote SSH username on {loc} host to connect to (optional). Overrides username given in "
1218 f"{loc.upper()}_DATASET.\n\n")
1219 for loc in locations:
1220 parser.add_argument(
1221 f"--ssh-{loc}-host", type=str, metavar="STRING",
1222 help=f"Remote SSH hostname of {loc} host to connect to (optional). Can also be an IPv4 or IPv6 address. "
1223 f"Overrides hostname given in {loc.upper()}_DATASET.\n\n")
1224 for loc in locations:
1225 parser.add_argument(
1226 f"--ssh-{loc}-port", type=int, min=1, max=65535, action=CheckRange, metavar="INT",
1227 help=f"Remote SSH port on {loc} host to connect to (optional).\n\n")
1228 for loc in locations:
1229 parser.add_argument(
1230 f"--ssh-{loc}-config-file", type=str, action=SSHConfigFileNameAction, metavar="FILE",
1231 help=f"Path to SSH ssh_config(5) file to connect to {loc} (optional); will be passed into ssh -F CLI. "
1232 "The basename must contain the substring 'bzfs_ssh_config'.\n\n")
1233 control_persist_secs_dflt: int = 600
1234 parser.add_argument(
1235 "--ssh-exit-on-shutdown", action="store_true",
1236 # help="On process shutdown, ask the SSH ControlMaster to exit immediately via 'ssh -O exit'. By default, masters "
1237 # f"persist for {control_persist_secs_dflt} idle seconds and are reused across {PROG_NAME} processes to improve "
1238 # f"startup latency when safe. A master is never used simultaneously by multiple {PROG_NAME} processes.")
1239 help=argparse.SUPPRESS)
1240 parser.add_argument(
1241 "--ssh-control-persist-secs", type=int, min=1, default=control_persist_secs_dflt, action=CheckRange, metavar="INT",
1242 help="The number of seconds an idle SSH connection will stay alive to improve latency on subsequent reuse (default: "
1243 "%(default)s, min: %(min)s).\n\n")
1244 parser.add_argument(
1245 "--timeout", default=None, metavar="DURATION",
1246 # help="Exit the program (or current task with non-zero --daemon-lifetime) with an error after this much time has "
1247 # "elapsed. Default is to never timeout. Examples: '600 seconds', '90 minutes', '10years'\n\n")
1248 help=argparse.SUPPRESS)
1249 threads_default = 100 # percent
1250 parser.add_argument(
1251 "--threads", min=1, max=1600, default=(threads_default, True), action=CheckPercentRange, metavar="INT[%]",
1252 help="The maximum number of threads to use for parallel operations; can be given as a positive integer, "
1253 f"optionally followed by the %% percent character (min: %(min)s, default: {threads_default}%%). Percentages "
1254 "are relative to the number of CPU cores on the machine. Example: 200%% uses twice as many threads as "
1255 "there are cores on the machine; 75%% uses num_threads = num_cores * 0.75. Currently this option only "
1256 "applies to dataset and snapshot replication, --create-src-snapshots, --delete-dst-snapshots, "
1257 "--delete-empty-dst-datasets, --monitor-snapshots and --compare-snapshot-lists. The ideal value for this "
1258 "parameter depends on the use case and its performance requirements, as well as the number of available CPU "
1259 "cores and the parallelism offered by SSDs vs. HDDs, ZFS topology and configuration, as well as the network "
1260 "bandwidth and other workloads simultaneously running on the system. The current default is geared towards a "
1261 "high degree of parallelism, and as such may perform poorly on HDDs. Examples: 1, 4, 75%%, 150%%\n\n")
1262 parser.add_argument(
1263 "--max-concurrent-ssh-sessions-per-tcp-connection", type=int, min=1, default=8, action=CheckRange, metavar="INT",
1264 help=f"For best throughput, {PROG_NAME} uses multiple SSH TCP connections in parallel, as indicated by "
1265 "--threads (see above). For best startup latency, each such parallel TCP connection can carry a "
1266 "maximum of S concurrent SSH sessions, where "
1267 "S=--max-concurrent-ssh-sessions-per-tcp-connection (default: %(default)s, min: %(min)s). "
1268 "Concurrent SSH sessions are mostly used for metadata operations such as listing ZFS datasets and their "
1269 "snapshots. This client-side max sessions parameter must not be higher than the server-side "
1270 "sshd_config(5) MaxSessions parameter (which defaults to 10, see "
1271 "https://manpages.ubuntu.com/manpages/latest/man5/sshd_config.5.html).\n\n"
1272 f"*Note:* For better throughput, {PROG_NAME} uses one dedicated TCP connection per ZFS "
1273 "send/receive operation such that the dedicated connection is never used by any other "
1274 "concurrent SSH session, effectively ignoring the value of the "
1275 "--max-concurrent-ssh-sessions-per-tcp-connection parameter in the ZFS send/receive case.\n\n")
1276 parser.add_argument(
1277 "--r2r", choices=["off", "pull", "push"], default="off",
1278 help="For remote-to-remote replication, controls whether the `zfs send` stream is relayed by the initiator "
1279 "or transferred directly between source and destination in order to improve the throughput of bulk data "
1280 "transfers (default: %(default)s). This option has no effect unless both replication endpoints are remote.\n\n"
1281 "* `off`: Keeps existing pull-push behavior where the initiator acts as an intermediary that relays the "
1282 "`zfs send` stream between source and destination, which can become a central bandwidth bottleneck.\n\n"
1283 "Example: ssh alice@srchost 'zfs send ...' | ssh bob@dsthost 'zfs receive ...'\n\n"
1284 "* `pull`: Tells the destination host to pull the `zfs send` stream directly from the source host. Requires "
1285 "`sh` and `ssh` on the destination host, plus SSH setup such that the destination user@host can `ssh` into "
1286 "the source host.\n\n"
1287 "Example: ssh bob@dsthost \"sh -c 'ssh alice@srchost zfs send ... | zfs receive ...'\"\n\n"
1288 "* `push`: Tells the source host to push the `zfs send` stream directly to the destination host. Requires "
1289 "`sh` and `ssh` on the source host, plus SSH setup such that the source user@host can `ssh` into the "
1290 "destination host.\n\n"
1291 "Example: ssh alice@srchost \"sh -c 'zfs send ... | ssh bob@dsthost zfs receive ...'\"\n\n"
1292 "*Note:* Orchestration still runs on the initiator; only the bulk data path changes. It is recommended to "
1293 "also set `--ssh-src-user` and `--ssh-dst-user` explicitly in order to avoid potential confusion about which "
1294 "SSH user account performs the nested remote-to-remote operation.\n\n"
1295 f"*Note:* If the required nested `sh`/`ssh` do not exist, {PROG_NAME} falls back to `--r2r=off`. "
1296 "`--r2r=pull` falls back to `--r2r=off` if `--ssh-src-config-file` is set to a non-empty value other than "
1297 "`none`, and `--r2r=push` falls back to `--r2r=off` if `--ssh-dst-config-file` is set to a non-empty value "
1298 "other than `none`.\n\n"
1299 "*Note:* `--pv*` progress reporting options have no effect in r2r modes; progress reporting is disabled.\n\n")
1300 parser.add_argument(
1301 "--bwlimit", default=None, action=NonEmptyStringAction, metavar="STRING",
1302 help="Sets `pv` and `mbuffer` bandwidth rate limit for zfs send/receive data transfer (optional). "
1303 "Example: `100m` to cap throughput at 100 MB/sec. Default is unlimited. Also see "
1304 "https://manpages.ubuntu.com/manpages/latest/man1/pv.1.html\n\n")
1305 parser.add_argument(
1306 "--daemon-lifetime", default="0 seconds", metavar="DURATION",
1307 # help="Exit the daemon after this much time has elapsed. Default is '0 seconds', i.e. no daemon mode. "
1308 # "Examples: '600 seconds', '86400 seconds', '1000years'\n\n")
1309 help=argparse.SUPPRESS)
1310 parser.add_argument(
1311 "--daemon-frequency", default="minutely", metavar="STRING",
1312 # help="Run a daemon iteration every N time units. Default is '%(default)s'. "
1313 # "Examples: '100 millisecondly', '10secondly, 'minutely' to request the daemon to run every 100 milliseconds, "
1314 # "or every 10 seconds, or every minute, respectively. Only has an effect if --daemon-lifetime is nonzero.\n\n")
1315 help=argparse.SUPPRESS)
1316 parser.add_argument(
1317 "--daemon-remote-conf-cache-ttl", default="300 seconds", metavar="DURATION",
1318 # help="The Time-To-Live for the remote host configuration cache, which stores available programs and "
1319 # f"ZFS features. After this duration, {prog_name} will re-detect the remote environment. Set to '0 seconds' "
1320 # "to re-detect on every daemon iteration. Default: %(default)s.\n\n")
1321 help=argparse.SUPPRESS)
1322 parser.add_argument(
1323 "--no-estimate-send-size", action="store_true",
1324 help="Skip 'zfs send -n -v'. This can improve performance if replicating small snapshots at high frequency.\n\n")
1326 def hlp(program: str) -> str:
1327 return f"The name of the '{program}' executable (optional). Default is '{program}'. "
1329 msg: str = f"Use '{DISABLE_PRG}' to disable the use of this program.\n\n"
1330 parser.add_argument(
1331 "--compression-program", default="zstd", choices=["zstd", "lz4", "pzstd", "pigz", "gzip", DISABLE_PRG],
1332 help=hlp("zstd") + msg.rstrip() + " The use is auto-disabled if data is transferred locally instead of via the "
1333 "network. This option is about transparent compression-on-the-wire, not about "
1334 "compression-at-rest.\n\n")
1335 parser.add_argument(
1336 "--compression-program-opts", default="-1", metavar="STRING",
1337 help="The options to be passed to the compression program on the compression step (optional). "
1338 "Default is '%(default)s' (fastest).\n\n")
1339 parser.add_argument(
1340 "--mbuffer-program", default="mbuffer", choices=["mbuffer", DISABLE_PRG],
1341 help=hlp("mbuffer") + msg.rstrip() + " The use is auto-disabled if data is transferred locally "
1342 "instead of via the network. This tool is used to smooth out the rate "
1343 "of data flow and prevent bottlenecks caused by network latency or "
1344 "speed fluctuation.\n\n")
1345 parser.add_argument(
1346 "--mbuffer-program-opts", default="-q -m 128M", metavar="STRING",
1347 help="Options to be passed to 'mbuffer' program (optional). Default: '%(default)s'.\n\n")
1348 parser.add_argument(
1349 "--ps-program", default="ps", choices=["ps", DISABLE_PRG],
1350 help=hlp("ps") + msg)
1351 parser.add_argument(
1352 "--pv-program", default="pv", choices=["pv", DISABLE_PRG],
1353 help=hlp("pv") + msg.rstrip() + " This is used for bandwidth rate-limiting and progress monitoring.\n\n")
1354 parser.add_argument(
1355 "--pv-program-opts", metavar="STRING",
1356 default="--progress --timer --eta --fineta --rate --average-rate --bytes --interval=1 --width=120 --buffer-size=2M",
1357 help="The options to be passed to the 'pv' program (optional). Default: '%(default)s'.\n\n")
1358 parser.add_argument(
1359 "--shell-program", default="sh", choices=["sh", DISABLE_PRG],
1360 help=hlp("sh") + msg)
1361 parser.add_argument(
1362 "--ssh-program", default="ssh", choices=["ssh", "hpnssh", DISABLE_PRG],
1363 help=hlp("ssh") + msg)
1364 parser.add_argument(
1365 "--sudo-program", default="sudo", choices=["sudo", "doas", DISABLE_PRG],
1366 help=hlp("sudo") + msg)
1367 parser.add_argument(
1368 "--zpool-program", default="zpool", choices=["zpool", DISABLE_PRG],
1369 help=hlp("zpool") + msg)
1370 parser.add_argument(
1371 "--log-dir", type=str, action=SafeDirectoryNameAction, metavar="DIR",
1372 help=f"Path to the log output directory on local host (optional). Default: $HOME/{LOG_DIR_DEFAULT}. The logger "
1373 "that is used by default writes log files there, in addition to the console. The basename of --log-dir must "
1374 f"contain the substring '{LOG_DIR_DEFAULT}' as this helps prevent accidents. The current.dir symlink "
1375 "always points to the subdirectory containing the most recent log file. The current.log symlink "
1376 "always points to the most recent log file. The current.pv symlink always points to the most recent "
1377 "data transfer monitoring log. Run `tail --follow=name --max-unchanged-stats=1` on both symlinks to "
1378 "follow what's currently going on. Parallel replication generates a separate .pv file per thread. To "
1379 "monitor these, run something like "
1380 "`while true; do clear; for f in $(realpath $HOME/bzfs-logs/current/current.pv)*; "
1381 "do tac -s $(printf '\\r') $f | tr '\\r' '\\n' | grep -m1 -v '^$'; done; sleep 1; done`\n\n")
1382 h_fix = ("The path name of the log file on local host is "
1383 "`${--log-dir}/${--log-file-prefix}<timestamp>${--log-file-infix}${--log-file-suffix}-<random>.log`. "
1384 "Example: `--log-file-prefix=zrun_us-west_ --log-file-suffix=_daily` will generate log "
1385 "file names such as `zrun_us-west_2024-09-03_12:26:15_daily-bl4i1fth.log`\n\n")
1386 parser.add_argument(
1387 "--log-file-prefix", default="zrun_", action=SafeFileNameAction, metavar="STRING",
1388 help="Default is %(default)s. " + h_fix)
1389 parser.add_argument(
1390 "--log-file-infix", default="", action=SafeFileNameAction, metavar="STRING",
1391 help="Default is the empty string. " + h_fix)
1392 parser.add_argument(
1393 "--log-file-suffix", default="", action=SafeFileNameAction, metavar="STRING",
1394 help="Default is the empty string. " + h_fix)
1395 parser.add_argument(
1396 "--log-subdir", choices=["daily", "hourly", "minutely"], default="daily",
1397 help="Make a new subdirectory in --log-dir every day, hour or minute; write log files there. "
1398 "Default is '%(default)s'.")
1399 parser.add_argument(
1400 "--log-syslog-address", default=None, action=NonEmptyStringAction, metavar="STRING",
1401 help="Host:port of the syslog machine to send messages to (e.g. 'foo.example.com:514' or '127.0.0.1:514'), or "
1402 "the file system path to the syslog socket file on localhost (e.g. '/dev/log'). The default is no "
1403 "address, i.e. do not log anything to syslog by default. See "
1404 "https://docs.python.org/3/library/logging.handlers.html#sysloghandler\n\n")
1405 parser.add_argument(
1406 "--log-syslog-socktype", choices=["UDP", "TCP"], default="UDP",
1407 help="The socket type to use to connect if no local socket file system path is used. Default is '%(default)s'.\n\n")
1408 parser.add_argument(
1409 "--log-syslog-facility", type=int, min=0, max=7, default=1, action=CheckRange, metavar="INT",
1410 help="The local facility aka category that identifies msg sources in syslog "
1411 "(default: %(default)s, min=%(min)s, max=%(max)s).\n\n")
1412 parser.add_argument(
1413 "--log-syslog-prefix", default=PROG_NAME, action=NonEmptyStringAction, metavar="STRING",
1414 help=f"The name to prepend to each message that is sent to syslog; identifies {PROG_NAME} messages as opposed "
1415 "to messages from other sources. Default is '%(default)s'.\n\n")
1416 parser.add_argument(
1417 "--log-syslog-level", choices=["CRITICAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"],
1418 default="ERROR",
1419 help="Only send messages with equal or higher priority than this log level to syslog. Default is '%(default)s'.\n\n")
1420 parser.add_argument(
1421 "--include-envvar-regex", action=FileOrLiteralAction, nargs="+", default=[], metavar="REGEX",
1422 help="On program startup, unset all Unix environment variables for which the full environment variable "
1423 "name matches at least one of the excludes but none of the includes. If an environment variable is "
1424 "included this decision is never reconsidered because include takes precedence over exclude. "
1425 "The purpose is to tighten security and help guard against accidental inheritance or malicious "
1426 "injection of environment variable values that may have unintended effects.\n\n"
1427 "This option can be specified multiple times. "
1428 "A leading `!` character indicates logical negation, i.e. the regex matches if the regex with the "
1429 "leading `!` character removed does not match. "
1430 "The default is to include no environment variables, i.e. to make no exceptions to --exclude-envvar-regex. "
1431 "Example that retains at least these two env vars: "
1432 "`--include-envvar-regex PATH "
1433 f"--include-envvar-regex {ENV_VAR_PREFIX}min_pipe_transfer_size`. "
1434 "Example that retains all environment variables without tightened security: `'.*'`\n\n")
1435 parser.add_argument(
1436 "--exclude-envvar-regex", action=FileOrLiteralAction, nargs="+", default=[], metavar="REGEX",
1437 help="Same syntax as --include-envvar-regex (see above) except that the default is to exclude no "
1438 f"environment variables. Example: `{ENV_VAR_PREFIX}.*`\n\n")
1440 for period, label in {"yearly": "years", "monthly": "months", "weekly": "weeks", "daily": "days", "hourly": "hours",
1441 "minutely": "minutes", "secondly": "seconds", "millisecondly": "milliseconds"}.items():
1442 anchor_group = parser.add_argument_group(
1443 f"{period.title()} Period Anchors", "Use these options to customize when snapshots that happen "
1444 f"every N {label} are scheduled to be created on the source by the --create-src-snapshots option.")
1445 for f in [f for f in dataclasses.fields(PeriodAnchors) if f.name.startswith(period + "_")]:
1446 min_ = f.metadata.get("min")
1447 max_ = f.metadata.get("max")
1448 anchor_group.add_argument(
1449 "--" + f.name, type=int, min=min_, max=max_, default=f.default, action=CheckRange, metavar="INT",
1450 help=f"{f.metadata.get('help')} ({min_} ≤ x ≤ {max_}, default: %(default)s).\n\n")
1452 for option_name, flag in ZFS_RECV_GROUPS.items():
1453 grup: str = option_name.replace("_", "-") # one of zfs_recv_o, zfs_recv_x
1454 flag = "'" + flag + "'" # one of -o or -x
1456 def h(text: str, option_name: str=option_name) -> str:
1457 return argparse.SUPPRESS if option_name not in (ZFS_RECV_O, ZFS_RECV_X) else text
1459 argument_group = parser.add_argument_group(
1460 grup,
1461 description=h(f"The following group of parameters specifies additional zfs receive {flag} options that "
1462 "can be used to configure copying of ZFS dataset properties from the source dataset to "
1463 "its corresponding destination dataset. The 'zfs-recv-o' group of parameters is applied "
1464 "before the 'zfs-recv-x' group."))
1465 target_choices = ["full", "incremental", "full+incremental"]
1466 target_choices_default = "full+incremental" if option_name == ZFS_RECV_X else "full"
1467 qq = "'"
1468 argument_group.add_argument(
1469 f"--{grup}-targets", choices=target_choices, default=target_choices_default,
1470 help=h(f"The zfs send phase or phases during which the extra {flag} options are passed to 'zfs receive'. "
1471 "This can be one of the following choices: "
1472 f"{', '.join([f'{qq}{x}{qq}' for x in target_choices])}. "
1473 "Default is '%(default)s'. "
1474 "A 'full' send is sometimes also known as an 'initial' send.\n\n"))
1475 msg = "Thus, -x opts do not benefit from source != 'local' (which is the default already)." \
1476 if flag == "'-x'" else ""
1477 argument_group.add_argument(
1478 f"--{grup}-sources", action=NonEmptyStringAction, default="local", metavar="STRING",
1479 help=h("The ZFS sources to provide to the 'zfs get -s' CLI in order to fetch the ZFS dataset properties "
1480 f"that will be fed into the --{grup}-include/exclude-regex filter (see below). The sources are in "
1481 "the form of a comma-separated list (no spaces) containing one or more of the following choices: "
1482 "'local', 'default', 'inherited', 'temporary', 'received', 'none', with the default being '%(default)s'. "
1483 f"Uses 'zfs get -p -s ${grup}-sources all $SRC_DATASET' to fetch the "
1484 "properties to copy - https://openzfs.github.io/openzfs-docs/man/master/8/zfs-get.8.html. P.S: Note "
1485 "that the existing 'zfs send --props' option does not filter and that --props only reads properties "
1486 f"from the 'local' ZFS property source (https://github.com/openzfs/zfs/issues/13024). {msg}\n\n"))
1487 if option_name == ZFS_RECV_O:
1488 group_include_regex_default_help: str = f"The default regex is '{ZFS_RECV_O_INCLUDE_REGEX_DEFAULT}'."
1489 else:
1490 group_include_regex_default_help = ("The default is to include no properties, thus by default no extra "
1491 f"{flag} option is appended. ")
1492 argument_group.add_argument(
1493 f"--{grup}-include-regex", action=FileOrLiteralAction, default=None, const=[], nargs="*", metavar="REGEX",
1494 help=h(f"Take the output properties of --{grup}-sources (see above) and filter them such that we only "
1495 "retain the properties whose name matches at least one of the --include regexes but none of the "
1496 "--exclude regexes. If a property is excluded this decision is never reconsidered because exclude "
1497 f"takes precedence over include. Append each retained property to the list of {flag} options in "
1498 "--zfs-recv-program-opt(s), unless another '-o' or '-x' option with the same name already exists "
1499 "therein. In other words, --zfs-recv-program-opt(s) takes precedence.\n\n"
1500 f"Zero or more regexes can be specified. Specify zero regexes to append no extra {flag} option. "
1501 "A leading `!` character indicates logical negation, i.e. the regex matches if the regex with the "
1502 "leading `!` character removed does not match. "
1503 "If the option starts with a `+` prefix then regexes are read from the newline-separated "
1504 "UTF-8 text file given after the `+` prefix, one regex per line inside of the text file. The basename "
1505 "must contain the substring 'bzfs_argument_file'.\n\n"
1506 f"{group_include_regex_default_help} "
1507 f"Example: `--{grup}-include-regex compression recordsize`. "
1508 "More examples: `.*` (include all properties), `foo bar myapp:.*` (include three regexes) "
1509 f"`+{grup}_regexes_bzfs_argument_file.txt`, `+/path/to/{grup}_regexes_bzfs_argument_file.txt`\n\n"
1510 "See https://openzfs.github.io/openzfs-docs/man/master/7/zfsprops.7.html\n\n"))
1511 argument_group.add_argument(
1512 f"--{grup}-exclude-regex", action=FileOrLiteralAction, nargs="+", default=[], metavar="REGEX",
1513 help=h(f"Same syntax as --{grup}-include-regex (see above), and the default is to exclude no properties. "
1514 f"Example: --{grup}-exclude-regex encryptionroot keystatus origin volblocksize volsize\n\n"))
1515 parser.add_argument(
1516 "--version", action="version", version=f"{PROG_NAME}-{__version__}, by {PROG_AUTHOR}",
1517 help="Display version information and exit.\n\n")
1518 return parser
1519 # fmt: on