From 864fb097621df32df229e3192cf3a757437a9535 Mon Sep 17 00:00:00 2001 From: Logan G Date: Fri, 24 Feb 2023 21:55:28 -0700 Subject: [PATCH] First version (not tested) --- etc/systemd/system/btrfs-maintenance.service | 10 +++++++ etc/systemd/system/btrfs-maintenance.timer | 9 ++++++ usr/local/bin/btrfs-maintenance | 30 ++++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 etc/systemd/system/btrfs-maintenance.service create mode 100644 etc/systemd/system/btrfs-maintenance.timer create mode 100755 usr/local/bin/btrfs-maintenance diff --git a/etc/systemd/system/btrfs-maintenance.service b/etc/systemd/system/btrfs-maintenance.service new file mode 100644 index 0000000..763045f --- /dev/null +++ b/etc/systemd/system/btrfs-maintenance.service @@ -0,0 +1,10 @@ +[Unit] +Description=Run BTRFS maintenance (scrubs and rebalance) + +[Service] +Type=oneshot +ExecStart=/usr/local/bin/btrfs-maintenance +RemainAfterExit=yes + +[Install] +WantedBy=default.target diff --git a/etc/systemd/system/btrfs-maintenance.timer b/etc/systemd/system/btrfs-maintenance.timer new file mode 100644 index 0000000..1a9eb7e --- /dev/null +++ b/etc/systemd/system/btrfs-maintenance.timer @@ -0,0 +1,9 @@ +[Unit] +Description=Run BTRFS maintenance stuff (scrub and rebalance) monthly + +[Timer] +OnCalendar=*-*-01 02:00:00 +Persistent=true + +[Install] +WantedBy=timers.target \ No newline at end of file diff --git a/usr/local/bin/btrfs-maintenance b/usr/local/bin/btrfs-maintenance new file mode 100755 index 0000000..b7942c0 --- /dev/null +++ b/usr/local/bin/btrfs-maintenance @@ -0,0 +1,30 @@ +#!/bin/bash +set -e + +# Find all BTRFS formatted partitions +PARTITIONS=() +for i in $(lsblk -nrpo "name" -e 1,7,11); do + if [[ "$(lsblk -no FSTYPE "$i")" == "btrfs" ]]; then + PARTITIONS+=("$i") + fi +done + +# Reallocate blocks that are less than 95% used +for i in ${PARTITIONS[*]}; do + echo "Balance: $i" + btrfs balance start -dusage=95 "$i" & +done + +# Wait for balance operations to finish +wait + +# Scrub all partitions +for i in ${PARTITIONS[*]}; do + echo "Scrub: $i" + btrfs scrub start -B "$i" & +done + +# Wait for scrub operations to finish +wait + +exit 0