fix mistake from recent commit
[distro-setup] / btrfsmaint
1 #!/bin/bash
2 set -eE -o pipefail
3 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
4
5 # inspired from
6 # https://github.com/kdave/btrfsmaintenance
7
8
9 # Man page says we could also use a range, i suppose it would be
10 # logical to use a pattern like 5..10 10..20,
11 # but I don't know if this would help us at all.
12 dusage="1 5 10 20 30 40 50"
13 musage="1 5 10 20 30"
14
15 e() { echo "cron: $*"; "$@"; }
16
17 check-idle() {
18 export DISPLAY=:0
19 # 3 hours, assume a movie might run that long.
20 idle_limit=$((1000 * 60 * 60 * 3))
21 idle_time=$idle_limit
22 id=999
23 while id $((++id)) &>/dev/null; do
24 new_idle_time=$(sudo -u \#$id xprintidle 2>/dev/null) ||:
25 if [[ $new_idle_time && $new_idle_time -lt $idle_time ]]; then
26 idle_time=$new_idle_time
27 fi
28 done
29 if (( idle_time < idle_limit )); then
30 idle=false
31 else
32 idle=true
33 fi
34 }
35
36 if [[ $1 == check ]]; then
37 check=true
38 else
39 check=false
40 fi
41
42 check-idle
43
44 fnd="findmnt --types btrfs --noheading"
45 for x in $($fnd --output "SOURCE" --nofsroot | sort -u); do
46 mnt=$($fnd --output "TARGET" --first-only --source $x)
47 [[ $mnt ]] || continue
48
49 if ! $idle; then
50 btrfs scrub cancel $mnt &>/dev/null ||:
51 continue
52 fi
53 if $check; then
54 continue
55 fi
56
57 # for comparing before and after balance.
58 # the log is already fairly verbose, so commented.
59 # e btrfs filesystem df $mnt
60 # e df -H $mnt
61 if btrfs filesystem df $mnt | grep -q "Data+Metadata"; then
62 for usage in $dusage; do
63 e btrfs balance start -dusage=$usage -musage=$usage $mnt
64 done
65 else
66 e btrfs balance start -dusage=0 $mnt
67 for usage in $dusage; do
68 e btrfs balance start -dusage=$usage $mnt
69 done
70 e btrfs balance start -musage=0 $mnt
71 for usage in $musage; do
72 e btrfs balance start -musage=$usage $mnt
73 done
74 fi
75 # e btrfs filesystem df $mnt
76 # e df -H $mnt
77 date=$(
78 btrfs scrub status $mnt | \
79 sed -rn 's/^\s*scrub started at (.*) and finished.*/\1/p'
80 )
81 if [[ $date ]]; then
82 date=$(date --date="$date" +%s)
83 # if date is sooner than 90 days ago
84 # the wiki recommends 30 days or so, but
85 # it makes the comp lag like shit for a day,
86 # so I'm going with 90 days.
87 if (( $date > `date +%s` - 60*60*24*30 )); then
88 echo "cron: skiping scrub of $mnt"
89 continue
90 fi
91 fi
92 e btrfs scrub start -Bd $mnt
93 done