### run_task error handling example Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Example showing how to check the exit status of run_task and handle failure, e.g., for btrfs balance start. ```sh if ! run_task btrfs balance start -dusage=0 "$MM"; then echo "balance failed on $MM" exit 1 fi ``` -------------------------------- ### Module instantiation Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Creates a BtrfsDefragPlugin instance and calls main() to start the protocol loop. ```python plugin = BtrfsDefragPlugin() plugin.main() ``` -------------------------------- ### run_task usage example (fstrim) Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Example invocation of run_task as used in btrfs-trim.sh, passing the command and mountpoint as arguments. ```sh run_task fstrim --verbose "$MNT" ``` -------------------------------- ### Install operations performed by dist-install.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/dist-install.md With $sysconfdir resolved, the script installs the configuration template, task scripts, and shared function library with root ownership. The glob btrfs-*.sh installs the four task scripts, not btrfsmaintenance-refresh-cron.sh. ```sh install -oroot -groot -m644 sysconfig.btrfsmaintenance "$sysconfdir"/btrfsmaintenance install -d -oroot -groot -m755 /usr/share/btrfsmaintenance install -oroot -groot -m755 btrfs-*.sh /usr/share/btrfsmaintenance/ install -oroot -groot -m644 btrfsmaintenance-functions /usr/share/btrfsmaintenance/ ``` -------------------------------- ### Invoke dist-install.sh with optional sysconfdir Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/dist-install.md Run the installer as root. The optional sysconfdir argument overrides the autodetected sysconfig directory; common values are /etc/sysconfig and /etc/default. ```sh ./dist-install.sh [sysconfdir] ``` -------------------------------- ### Usage example for expand_auto_mountpoint in btrfs-balance.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Shows how the function is called with a configuration variable, assigning the result back to the same variable. Used in btrfs-balance.sh. ```sh BTRFS_BALANCE_MOUNTPOINTS=$(expand_auto_mountpoint "$BTRFS_BALANCE_MOUNTPOINTS") ``` -------------------------------- ### Load btrfsmaintenance-functions library Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Sources the shared library after configuration files are loaded. The task scripts use a relative path resolved from the script location, but this example shows the absolute system path. ```sh . /usr/share/btrfsmaintenance/btrfsmaintenance-functions ``` -------------------------------- ### Constants and setup in btrfs-defrag-plugin.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Defines DEBUG, EXTENT_SIZE, RPMDIR, and SCRIPTNAME constants. RPMDIR is resolved via rpm --eval, SCRIPTNAME is the basename of $0. cleanup() removes a temp dir and is wired to EXIT via trap cleanup EXIT. ```sh DEBUG="false" EXTENT_SIZE="32M" RPMDIR=$(rpm --eval "%_dbpath") SCRIPTNAME="$(basename "$0")" ``` -------------------------------- ### Usage example for detect_mixed_bg Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Shows how to conditionally use shared usage filter values when mixed block groups are detected. The ellipsis represents omitted code. ```sh if detect_mixed_bg "$MM"; then # use shared usage filter (musage/dusage) values ... fi ``` -------------------------------- ### btrfs-scrub.sh: Scrub cancelled message and exit 1 Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/errors.md When a `btrfs scrub start` invocation returns non-zero, the script prints `Scrub cancelled at $MNT` and exits with code 1. The RAID-5/6 device loop polls `btrfs scrub status` forever with `sleep 5` because no timeout is defined in source. ```shell Scrub cancelled at $MNT ``` -------------------------------- ### refresh_timer function (btrfsmaintenance-refresh-cron.sh:66) Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-refresh-cron.md Manages systemd timer drop-ins. For 'uninstall' or 'none', it stops, disables, and removes the timer's drop-in directory. Otherwise, it writes a schedule.conf with a [Timer] section containing an empty OnCalendar= line (to clear compiled-in schedules) followed by OnCalendar=$PERIOD, then enables and starts the timer. ```sh refresh_timer() { local PERIOD="$1" local SERVICE="$2" echo "Refresh timer $SERVICE for $PERIOD" case "$PERIOD" in uninstall|none) systemctl stop "$SERVICE".timer &> /dev/null systemctl disable "$SERVICE".timer &> /dev/null rm -rf /etc/systemd/system/"$SERVICE".timer.d ;; *) mkdir -p /etc/systemd/system/"$SERVICE".timer.d/ cat << EOF > /etc/systemd/system/"$SERVICE".timer.d/schedule.conf [Timer] OnCalendar= OnCalendar=$PERIOD EOF systemctl enable "$SERVICE".timer &> /dev/null systemctl start "$SERVICE".timer &> /dev/null ;; esac } ``` -------------------------------- ### PLUGINBEGIN callback Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Initializes plugin state and acknowledges the begin event. ```python def PLUGINBEGIN(self, headers, body): self.actions = [] self.commit_hook_supported = False dbg('--- Btrfs defrag plugin begin') self.ack() ``` -------------------------------- ### Invocation: update-balance-usage-defaults.sh [target file] Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/update-balance-usage-defaults.md Command to run the migration script. The target file is optional and autodetected if not provided. ```sh /usr/share/btrfsmaintenance/update-balance-usage-defaults.sh [target file] ``` -------------------------------- ### Invoke btrfs-balance.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-balance.md Run the balance task entry point. Takes no arguments; all behavior is driven by sysconfig environment variables. ```sh /usr/share/btrfsmaintenance/btrfs-balance.sh ``` -------------------------------- ### btrfs-balance.sh environment preamble Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-balance.md Fixed preamble executed by the script: sets umask and PATH, sources both config locations (later file wins), sets the log identifier, and loads the shared library. ```sh umask 022 PATH=/sbin:/bin:/usr/sbin:/usr/bin export PATH if [ -f /etc/sysconfig/btrfsmaintenance ] ; then . /etc/sysconfig/btrfsmaintenance fi if [ -f /etc/default/btrfsmaintenance ] ; then . /etc/default/btrfsmaintenance fi LOGIDENTIFIER='btrfs-balance' . $(dirname $(realpath "$0"))/btrfsmaintenance-functions ``` -------------------------------- ### Invoke btrfs-scrub.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-scrub.md Run the scrub task entry point directly. It takes no arguments; all behavior is driven by sysconfig environment variables. ```sh /usr/share/btrfsmaintenance/btrfs-scrub.sh ``` -------------------------------- ### Detect sysconfig directory in dist-install.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/dist-install.md When no argument is given, the script checks for /etc/sysconfig first, then /etc/default. If neither exists, it prints an error and exits with code 1. ```sh if [ -d /etc/sysconfig ]; then sysconfdir=/etc/sysconfig elif [ -d /etc/default ]; then sysconfdir=/etc/default else echo "Cannot detect sysconfig directory, please specify manually" exit 1 fi ``` -------------------------------- ### Rolling distro TIMELINE_LIMIT configuration Source: https://github.com/kdave/btrfsmaintenance/blob/master/README.md Suggested TIMELINE_LIMIT_* values for a rolling distro with high update frequency and high data change. Root partition should be at least 30GiB. ```bash TIMELINE_LIMIT_HOURLY="12" TIMELINE_LIMIT_DAILY="5" TIMELINE_LIMIT_WEEKLY="2" TIMELINE_LIMIT_MONTHLY="1" TIMELINE_LIMIT_YEARLY="0" ``` -------------------------------- ### Target resolution logic in update-balance-usage-defaults.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/update-balance-usage-defaults.md Shell script that determines the config file path. It checks /etc/sysconfig/btrfsmaintenance, then /etc/default/btrfsmaintenance, then the provided argument. If none exist, it prints an error and exits with status 1. ```sh if [ -f /etc/sysconfig/btrfsmaintenance ] ; then file=/etc/sysconfig/btrfsmaintenance fi if [ -f /etc/default/btrfsmaintenance ] ; then file=/etc/default/btrfsmaintenance fi if [ -f "$1" ]; then file="$1" fi if ! [ -f "$file" ]; then echo "ERROR: config file for btrfsmaintenance not found: $file" exit 1 fi ``` -------------------------------- ### Uninstall path check Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-refresh-cron.md Checks if the first argument is 'uninstall' to remove all four tasks and exit 0. ```sh if [ "$1" = 'uninstall' ]; then ``` -------------------------------- ### Iterate BTRFS_TRIM_MOUNTPOINTS in btrfs-trim.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-trim.md Loops over the colon-separated BTRFS_TRIM_MOUNTPOINTS, first expanded through expand_auto_mountpoint, and runs the trim workload for each mountpoint. ```sh for MNT in $BTRFS_TRIM_MOUNTPOINTS; do ... done ``` -------------------------------- ### Python plugin: import zypp_plugin framework Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/endpoints.md The Python implementation delegates transport to the external zypp_plugin module, which is not part of this repository. Only the callback contract is documented. ```python from zypp_plugin import Plugin ``` -------------------------------- ### Main protocol loop in btrfs-defrag-plugin.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Reads NUL-delimited frames from stdin, extracts the command, and responds: COMMITEND proceeds to defrag work, _DISCONNECT replies ACK and breaks, other commands reply _ENOMETHOD and continue. ```sh ret=0 # The frames are terminated with NUL. Use that as the delimeter and get # the whole frame in one go. while IFS= read -r -d $'\0' FRAME; do echo ">>" $FRAME | debug # We only want the command, which is the first word read COMMAND <<<$FRAME ... case "$COMMAND" in COMMITEND) ;; _DISCONNECT) respond "ACK" break ;; *) respond "_ENOMETHOD" continue ;; esac ... ``` -------------------------------- ### Invoke btrfs-defrag.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag.md Run the defrag task entry point. Takes no arguments; all behavior is driven by sysconfig environment variables. ```sh /usr/share/btrfsmaintenance/btrfs-defrag.sh ``` -------------------------------- ### qx function Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Runs a shell command and returns its stdout as a string. Uses shell=True. ```python def qx(args): out=subprocess.Popen(args, shell=True, stdout=subprocess.PIPE, **popen_kwargs).stdout outstr="".join(out.readlines()) out.close() return outstr ``` -------------------------------- ### Regular/enterprise distro timeline limits Source: https://github.com/kdave/btrfsmaintenance/blob/master/README.md Suggested TIMELINE_LIMIT_* values for a regular or enterprise distro with low update frequency and low to moderate data changes, mostly from package updates in the range of hundreds of megabytes per update. ```bash TIMELINE_LIMIT_HOURLY="12" TIMELINE_LIMIT_DAILY="7" TIMELINE_LIMIT_WEEKLY="4" TIMELINE_LIMIT_MONTHLY="6" TIMELINE_LIMIT_YEARLY="1" ``` -------------------------------- ### Invocation: btrfsmaintenance-refresh-cron.sh [cron|systemd-timer|timer] [uninstall] Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-refresh-cron.md Shows the command-line usage of the script. The first optional argument selects the scheduling implementation (cron or systemd-timer/timer), and the second optional argument 'uninstall' removes all cron links and timer drop-ins. ```sh btrfsmaintenance-refresh-cron.sh [cron|systemd-timer|timer] [uninstall] ``` -------------------------------- ### PLUGINEND callback Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Runs at end of package commit. If RPM database is not on btrfs, acknowledges and returns. Otherwise runs btrfs filesystem defragment with -v -f -r -t options, logging before/after filefrag when DEBUG is set. ```python def PLUGINEND(self, headers, body): dbg('--- Btrfs defrag plugin end: %s %s\n' % (str(headers), str(body))) dbg('--- fstype(%s) = |%s|' % (PATH, fstype(PATH))) if fstype(PATH) != 'btrfs': self.ack() return if DEBUG: dbg('--- Fragmentation before') dbg(qx('filefrag %s/*' % (PATH))) # defrag options: # - verbose # - recursive # - flush each file before going to the next one # - set the extent target hint ret = qx('btrfs filesystem defragment -v -f -r -t %s "%s"' % \ (str(EXTENT_SIZE), PATH)) if DEBUG: dbg(ret) dbg('--- Fragmentation after') dbg(qx('filefrag %s/*' % (PATH))) self.ack() ``` -------------------------------- ### btrfsmaintenance-refresh.path Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/systemd-units.md Path watcher that triggers btrfsmaintenance-refresh.service whenever /etc/sysconfig/btrfsmaintenance changes, keeping the timer schedule in sync without manual intervention. ```ini [Path] PathChanged=/etc/sysconfig/btrfsmaintenance [Install] WantedBy=multi-user.target ``` -------------------------------- ### check_scrub_running Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Checks if a scrub is currently running on a btrfs filesystem by running `btrfs scrub status` and grepping for 'scrub.*running for'. ```APIDOC ## check_scrub_running ### Description Checks if a scrub is currently running on a btrfs filesystem by running `btrfs scrub status` and grepping for 'scrub.*running for'. ### Function Signature ```sh check_scrub_running() { btrfs scrub status "$1" | grep -q "scrub.*running for" } ``` ### Parameters - **$1** (string) - Required - Path to a mounted btrfs filesystem. ### Return Exit status `0` if a scrub is currently in progress on the given filesystem, non-zero otherwise. ``` -------------------------------- ### Invoke btrfs-trim.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-trim.md Runs the TRIM/discard operation on the configured mountpoints. Takes no arguments; all behavior is driven by sysconfig environment variables. ```sh /usr/share/btrfsmaintenance/btrfs-trim.sh ``` -------------------------------- ### Module-level constants Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Defines DEBUG, EXTENT_SIZE, LOGFILE, and PATH constants. PATH is resolved at import using rpm --eval %_dbpath. ```python DEBUG=False EXTENT_SIZE=32*1024*1024 LOGFILE='/tmp/btrfs-defrag-plugin.log' PATH=subprocess.check_output(["rpm", "--eval", "%_dbpath"], **popen_kwargs).strip() ``` -------------------------------- ### Common [Timer] section for task timers Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/systemd-units.md Defines the common timer configuration for all four task timers. Uses monthly schedule by default, Persistent=true to catch up after boot/suspend, and a 1-hour accuracy window. ```ini [Timer] OnCalendar=monthly AccuracySec=1h Persistent=true [Install] WantedBy=timers.target ``` -------------------------------- ### check_balance_running Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Checks if a balance is currently running on a btrfs filesystem by running `btrfs balance status`. Returns 0 if not in progress, 1 if in progress, and 2 for other errors. ```APIDOC ## check_balance_running ### Description Checks if a balance is currently running on a btrfs filesystem by running `btrfs balance status`. Returns 0 if not in progress, 1 if in progress, and 2 for other errors. ### Function Signature ```sh check_balance_running() { # 0: not in progress # 1: in progress # 2: other error (EPERM) if btrfs balance status "$1" >& /dev/null; then return 1 fi return 0 } ``` ### Parameters - **$1** (string) - Required - Path to a mounted btrfs filesystem. ### Return Exit status `0` if a balance is **not** in progress; exit status `1` if it is in progress (the `btrfs balance status` command succeeded, which in btrfs-progs indicates an active balance); exit status `2` for other errors such as `EPERM` (the source comment documents this convention; the function does not itself set `2` — it is the status propagated from `btrfs balance status` when that command fails for a reason other than "no balance in progress"). ``` -------------------------------- ### Check journal and filesystem state for failed maintenance runs Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/errors.md Use journalctl with the task's tag (btrfs-scrub, btrfs-balance, btrfs-trim, btrfs-defrag) or inspect the underlying filesystem state to detect failed maintenance runs. Do not rely on the exit code because the task scripts mostly exit 0. ```sh # Check the journal for the task's tag (journal sink): journalctl -t btrfs-scrub journalctl -t btrfs-balance journalctl -t btrfs-trim journalctl -t btrfs-defrag # Or check the underlying filesystem state directly: btrfs scrub status /path # last scrub status/cancellation btrfs balance status /path # in-progress/failed balance btrfs filesystem df /path # space reclaimed check ``` -------------------------------- ### run_task function Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Executes a command, optionally wrapping it with /usr/bin/flock to serialize maintenance jobs per filesystem. If BTRFS_ALLOW_CONCURRENCY is 'true', runs directly. Otherwise locks on /run/btrfs-maintenance-running. where UUID is from the last argument (mountpoint). Passes --verbose to flock only if supported (util-linux >= 2.27). ```sh run_task() { local MNT="${@:$#}" local UUID=$(btrfs_fsid "$MNT") local verbose if test "$BTRFS_ALLOW_CONCURRENCY" = "true"; then "$@" else # Flock older than 2.27 does not support --verbose option, check # if it's available as we'd like to log the information if /usr/bin/flock --help 2>&1 | grep -q -- --verbose; then verbose="--verbose" fi /usr/bin/flock $verbose /run/btrfs-maintenance-running."$UUID" "$@" fi } ``` -------------------------------- ### btrfs-balance.sh log output sink Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-balance.md The whole workload is piped through a case statement that routes output to stdout, journal, syslog, or none based on BTRFS_LOG_OUTPUT. Always exits 0. ```sh { ... } | \ case "$BTRFS_LOG_OUTPUT" in stdout) cat;; journal) systemd-cat -t "$LOGIDENTIFIER";; syslog) logger -t "$LOGIDENTIFIER";; none) cat >/dev/null;; *) cat;; esac exit 0 ``` -------------------------------- ### Common [Service] section for task services Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/systemd-units.md Defines the common service configuration for btrfs-balance, btrfs-defrag, btrfs-scrub, and btrfs-trim. Sets Type=simple, runs the task script, and sets idle IO and CPU scheduling to avoid competing with interactive work. ```ini [Service] Type=simple ExecStart=/usr/share/btrfsmaintenance/.sh IOSchedulingClass=idle CPUSchedulingPolicy=idle ``` -------------------------------- ### execute function in btrfs-defrag-plugin.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Runs a command, captures stderr to $tmpdir/cmd-output, and returns the exit status. In debug mode, logs the output on failure or success. ```sh execute() { debug -- "Executing: $@" $@ 2> $tmpdir/cmd-output ret=$? if $DEBUG; then if test $ret -ne 0; then log -- "Command failed, output follows:" log -f $tmpdir/cmd-output log -- "End output" else log -- "Command succeeded" fi fi return $ret } ``` -------------------------------- ### respond function in btrfs-defrag-plugin.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Writes a response frame: \n\n\x00 to stdout. The response word is passed as $1. ```sh respond() { debug "<< [$1]" echo -ne "$1\n\n\x00" } ``` -------------------------------- ### btrfsmaintenance-refresh.service Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/systemd-units.md Runs the scheduler refresh in systemd-timer mode, rewriting timer drop-ins to match sysconfig values. Type=oneshot so it runs once and exits. Can be restarted manually with systemctl restart btrfsmaintenance-refresh. ```ini [Service] ExecStart=/usr/share/btrfsmaintenance/btrfsmaintenance-refresh-cron.sh systemd-timer Type=oneshot ``` -------------------------------- ### Balance strategy for split block groups Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-balance.md Default branch for filesystems without mixed block groups. Balances data and metadata separately using BTRFS_BALANCE_DUSAGE and BTRFS_BALANCE_MUSAGE. ```sh run_task btrfs balance start -dusage=0 "$MM" for BB in $BTRFS_BALANCE_DUSAGE; do run_task btrfs balance start -v -dusage=$BB "$MM" done run_task btrfs balance start -musage=0 "$MM" for BB in $BTRFS_BALANCE_MUSAGE; do run_task btrfs balance start -v -musage="$BB" "$MM" done ``` -------------------------------- ### Defrag loop over BTRFS_DEFRAG_PATHS Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag.md Iterates over colon-separated paths, skips non-btrfs paths, and runs btrfs filesystem defrag on regular files larger than BTRFS_DEFRAG_MIN_SIZE. Uses -xdev to avoid descending into other mount points, subvolumes, or snapshots. ```sh for P in $BTRFS_DEFRAG_PATHS; do IFS="$OIFS" if ! is_btrfs "$P"; then echo "Path $P is not btrfs, skipping" continue fi find "$P" -xdev -size "$BTRFS_DEFRAG_MIN_SIZE" -type f \ -exec btrfs filesystem defrag -t 32m -f $BTRFS_VERBOSITY '{}' \; done ``` -------------------------------- ### Shell plugin: read NUL-delimited frames from stdin Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/endpoints.md Reads whole protocol frames from stdin using NUL as the delimiter. The first word of each frame is the command, extracted with read COMMAND <<<$FRAME. ```shell read -r -d $'\0' ``` -------------------------------- ### Precompute scrub option flags from config Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-scrub.md Sets the readonly flag when BTRFS_SCRUB_READ_ONLY is true, and sets the ionice best-effort level 4 flag when BTRFS_SCRUB_PRIORITY is normal. ```sh readonly= if [ "$BTRFS_SCRUB_READ_ONLY" = "true" ]; then readonly=-r fi ioprio= if [ "$BTRFS_SCRUB_PRIORITY" = "normal" ]; then # ionice(3) best-effort, level 4 ioprio="-c 2 -n 4" fi ``` -------------------------------- ### expand_auto_mountpoint Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Expands the literal word 'auto' into a colon-separated list of mountpoints for all mounted btrfs filesystems. If the input is not 'auto', it echoes the input unchanged. ```APIDOC ## expand_auto_mountpoint ### Description Expands the literal word 'auto' into a colon-separated list of mountpoints for all mounted btrfs filesystems. If the input is not 'auto', it echoes the input unchanged. ### Function Signature ```sh expand_auto_mountpoint() { local MNTLIST="$1" if [ "$MNTLIST" = "auto" ]; then local BTRFS_DEVICES local DEVICE local MNT # find all mounted btrfs filesystems, print their device nodes, sort them # and remove identical entries BTRFS_DEVICES=$(findmnt --types btrfs --output "SOURCE" --nofsroot --noheading | sort | uniq) # find one (and only one) corresponding mountpoint for each btrfs device node MNTLIST="" for DEVICE in $BTRFS_DEVICES; do MNT=$(findmnt --types btrfs --first-only --noheadings --output "TARGET" --source "$DEVICE") if [ -n "$MNTLIST" ]; then MNTLIST="$MNTLIST:$MNT" else MNTLIST="$MNT" fi done fi echo -n "$MNTLIST" } ``` ### Parameters - **$1** (string) - Required - A colon-separated path list from a `_MOUNTPOINTS` config variable, or the literal word `auto`. ### Return Prints a colon-separated mountpoint list to stdout. If the input is `auto`, all mounted btrfs filesystems are enumerated with `findmnt --types btrfs`, deduplicated by device node, and the first mount target per device is used. Any other input is echoed back unchanged. ### Usage Example ```sh BTRFS_BALANCE_MOUNTPOINTS=$(expand_auto_mountpoint "$BTRFS_BALANCE_MOUNTPOINTS") ``` ``` -------------------------------- ### expand_auto_mountpoint function definition Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Expands the literal 'auto' into a colon-separated list of mountpoints for all mounted btrfs filesystems. Uses findmnt to enumerate devices and their first mount target, deduplicating by device node. Any other input is echoed back unchanged. ```sh expand_auto_mountpoint() { local MNTLIST="$1" if [ "$MNTLIST" = "auto" ]; then local BTRFS_DEVICES local DEVICE local MNT # find all mounted btrfs filesystems, print their device nodes, sort them # and remove identical entries BTRFS_DEVICES=$(findmnt --types btrfs --output "SOURCE" --nofsroot --noheading | sort | uniq) # find one (and only one) corresponding mountpoint for each btrfs device node MNTLIST="" for DEVICE in $BTRFS_DEVICES; do MNT=$(findmnt --types btrfs --first-only --noheadings --output "TARGET" --source "$DEVICE") if [ -n "$MNTLIST" ]; then MNTLIST="$MNTLIST:$MNT" else MNTLIST="$MNT" fi done fi echo -n "$MNTLIST" } ``` -------------------------------- ### Balance strategy for mixed block groups Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-balance.md Used when detect_mixed_bg returns true. Reuses BTRFS_BALANCE_MUSAGE values for both data and metadata because on a mixed-bg filesystem data and metadata share space. ```sh run_task btrfs balance start -musage=0 -dusage=0 "$MM" for BB in $BTRFS_BALANCE_MUSAGE; do run_task btrfs balance start -v -musage=$BB -dusage=$BB "$MM" done ``` -------------------------------- ### refresh_cron function (btrfsmaintenance-refresh-cron.sh:33) Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-refresh-cron.md Creates or removes cron symlinks for a given period. Validates the period against daily, weekly, monthly, none, and uninstall; prints an error and returns early on invalid input. For each of daily/weekly/monthly, it creates a symlink in /etc/cron./ when the period matches, otherwise removes it. The link name strips the extension because Debian does not allow dots in /etc/cron.* filenames. ```sh refresh_cron() { local EXPECTED="$1" local SCRIPT="$2" local VALID=false local PERIOD local LINK local FILE echo "Refresh script $SCRIPT for $EXPECTED" for PERIOD in daily weekly monthly none uninstall; do if [ "$PERIOD" = "$EXPECTED" ]; then VALID=true fi done if ! $VALID; then echo "$EXPECTED is not a valid period for cron. Not changing." return fi for PERIOD in daily weekly monthly; do # NOTE: debian does not allow filenames with dots in /etc/cron.* LINK="${SCRIPT%.*}" FILE="/etc/cron.$PERIOD/$LINK" if [ "$PERIOD" = "$EXPECTED" ]; then ln -sf "$SCRIPTS/$SCRIPT" "$FILE" else rm -f "$FILE" fi done } ``` -------------------------------- ### Shell plugin: extract command from frame Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/endpoints.md Reads the first word of the frame into the COMMAND variable. The first word of the frame content is the command. ```shell read COMMAND <<<$FRAME ``` -------------------------------- ### btrfs_defrag function in btrfs-defrag-plugin.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Runs the defrag command: btrfs filesystem defragment -v -f -r -t "$EXTENT_SIZE" "$RPMDIR". ```sh btrfs_defrag() { execute btrfs filesystem defragment -v -f -r -t "$EXTENT_SIZE" "$RPMDIR" } ``` -------------------------------- ### fstype function Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Returns the filesystem type of a path using stat -f --format=%T, with trailing whitespace stripped. ```python def fstype(path): ret=qx('stat -f --format=%T "'+path+'"') return ret.rstrip() ``` -------------------------------- ### cron implementation refresh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-refresh-cron.md Default branch when implementation is cron, refreshes cron jobs for each task. ```sh refresh_cron "$BTRFS_SCRUB_PERIOD" btrfs-scrub.sh refresh_cron "$BTRFS_DEFRAG_PERIOD" btrfs-defrag.sh refresh_cron "$BTRFS_BALANCE_PERIOD" btrfs-balance.sh refresh_cron "$BTRFS_TRIM_PERIOD" btrfs-trim.sh ``` -------------------------------- ### check_scrub_running function definition Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Checks if a scrub is currently running on the given filesystem by grepping for 'scrub.*running for' in the output of 'btrfs scrub status'. Returns exit status 0 if running, non-zero otherwise. ```sh check_scrub_running() { btrfs scrub status "$1" | grep -q "scrub.*running for" } ``` -------------------------------- ### fixup function in update-balance-usage-defaults.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/update-balance-usage-defaults.md Function that either greps for the old line (dry-run) or uses sed -i to replace it. In dry-run mode (dryrun=true) it only greps; otherwise it edits the file. ```sh fixup() { if $dryrun; then grep "^$1\$" "$file" else sed -i -e "s,$1,$2," "$file" fi } ``` -------------------------------- ### is_btrfs Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Checks if a given path is on a btrfs filesystem by using `stat -f --format=%T` and comparing the filesystem type to 'btrfs'. ```APIDOC ## is_btrfs ### Description Checks if a given path is on a btrfs filesystem by using `stat -f --format=%T` and comparing the filesystem type to 'btrfs'. ### Function Signature ```sh is_btrfs() { local FS=$(stat -f --format=%T "$1") [ "$FS" = "btrfs" ] && return 0 return 1 } ``` ### Parameters - **$1** (string) - Required - Path to a mounted filesystem. ### Return Exit status `0` if the filesystem type of `$1` (from `stat -f --format=%T`) is `btrfs`, `1` otherwise. This is the gate used by every task script before running a task. ``` -------------------------------- ### check_balance_running function definition Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Checks if a balance is in progress. Returns 0 if not in progress, 1 if in progress (when 'btrfs balance status' succeeds), and propagates other errors like EPERM as status 2. ```sh check_balance_running() { # 0: not in progress # 1: in progress # 2: other error (EPERM) if btrfs balance status "$1" >& /dev/null; then return 1 fi return 0 } ``` -------------------------------- ### log function in btrfs-defrag-plugin.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Logs a message via logger at info priority, tagged with SCRIPTNAME and process id $$. ```sh log() { logger -p info -t $SCRIPTNAME --id=$$ "$@" } ``` -------------------------------- ### btrfs_fsid function Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Prints the filesystem UUID to stdout by parsing the 'uuid:' field from 'btrfs filesystem show'. Used by run_task to build a per-filesystem lock file name. ```sh btrfs_fsid() { btrfs filesystem show "$1" | sed -n -e '/uuid:/ {s/^.*uuid: //;p }' } ``` -------------------------------- ### systemd-timer implementation refresh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-refresh-cron.md When BTRFS_TIMER_IMPLEMENTATION is systemd-timer, first uninstalls cron jobs then refreshes timers for each task. ```sh for SCRIPT in btrfs-scrub btrfs-defrag btrfs-balance btrfs-trim; do refresh_cron uninstall "${SCRIPT}.sh" done refresh_timer "$BTRFS_SCRUB_PERIOD" btrfs-scrub refresh_timer "$BTRFS_DEFRAG_PERIOD" btrfs-defrag refresh_timer "$BTRFS_BALANCE_PERIOD" btrfs-balance refresh_timer "$BTRFS_TRIM_PERIOD" btrfs-trim ``` -------------------------------- ### Shell plugin: write NUL-terminated response frame Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/endpoints.md Writes a response frame to stdout, terminated by a NUL byte. The response is echoed with a trailing newline pair before the NUL delimiter. ```shell echo -ne "$1 \x00" ``` -------------------------------- ### detect_mixed_bg Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Checks if a btrfs filesystem contains mixed block groups by running `btrfs filesystem df` and grepping for 'Data+Metadata'. ```APIDOC ## detect_mixed_bg ### Description Checks if a btrfs filesystem contains mixed block groups by running `btrfs filesystem df` and grepping for 'Data+Metadata'. ### Function Signature ```sh detect_mixed_bg() { btrfs filesystem df "$1" | grep -q "Data+Metadata" } ``` ### Parameters - **$1** (string) - Required - Path to a mounted btrfs filesystem. ### Return Exit status `0` if the filesystem contains mixed block groups (`btrfs filesystem df` reports a `Data+Metadata` line), non-zero otherwise. ### Usage Example ```sh if detect_mixed_bg "$MM"; then # use shared usage filter (musage/dusage) values ... fi ``` ``` -------------------------------- ### debug_fragmentation function in btrfs-defrag-plugin.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Debug-only: logs filefrag output of the RPM database files. Failures are logged as non-fatal. ```sh debug_fragmentation() { if $DEBUG; then log -- "Fragmentation $1" execute filefrag $RPMDIR/* > $tmpdir/filefrag-output if test $? -eq 0; then log -f $tmpdir/filefrag-output log -- "End output" else log "Non-fatal error ignored." fi fi } ``` -------------------------------- ### detect_mixed_bg function definition Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Checks if a btrfs filesystem has mixed block groups by grepping for 'Data+Metadata' in the output of 'btrfs filesystem df'. Returns exit status 0 if found, non-zero otherwise. ```sh detect_mixed_bg() { btrfs filesystem df "$1" | grep -q "Data+Metadata" } ``` -------------------------------- ### BtrfsDefragPlugin class declaration Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Declares the BtrfsDefragPlugin class inheriting from Plugin (zypp_plugin.Plugin). ```python class BtrfsDefragPlugin(Plugin): ``` -------------------------------- ### dbg function Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Writes a message to LOGFILE if DEBUG is true. No-op otherwise. ```python def dbg(args): if not DEBUG: return f=open(LOGFILE, "a+") f.write(args) f.write("\n") f.close() ``` -------------------------------- ### debug function in btrfs-defrag-plugin.sh Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfs-defrag-plugin.md Logs a message only when DEBUG is set to true. ```sh debug() { $DEBUG && log "$@" } ``` -------------------------------- ### is_btrfs function definition Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Checks if the filesystem type of the given path is btrfs using 'stat -f --format=%T'. Returns 0 if btrfs, 1 otherwise. Used as a gate by every task script. ```sh is_btrfs() { local FS=$(stat -f --format=%T "$1") [ "$FS" = "btrfs" ] && return 0 return 1 } ``` -------------------------------- ### is_raid56 function Source: https://github.com/kdave/btrfsmaintenance/blob/master/_autodocs/api-reference/btrfsmaintenance-functions.md Checks if the data profile of a btrfs filesystem is RAID-5 or RAID-6 by grepping the output of 'btrfs filesystem usage'. Returns 0 if either is found, 1 otherwise. Used by btrfs-scrub.sh to choose sequential per-device scrubbing. ```sh is_raid56() { btrfs filesystem usage "$1" | grep Data,RAID5 && return 0 btrfs filesystem usage "$1" | grep Data,RAID6 && return 0 return 1 } ```