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