Last active
August 23, 2022 04:22
-
-
Save Snawoot/9fdc348a8539cc74f80734180bd64290 to your computer and use it in GitHub Desktop.
Halves old logs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -euo pipefail | |
treshold=${HIGH_WATER_PCT:-85} | |
cleanup_dir=${DIR:-/var/log/remote/} | |
fraction=${DELETE_FRACTION:-0.5} | |
( | |
if ! flock -n 9 ; then | |
>&2 echo "Unable to acquire lock!" | |
exit 3 | |
fi | |
if [[ "$(df --output=pcent "$cleanup_dir" | tail -1 | grep -o '[0-9]*')" -lt "$treshold" ]] ; then | |
logger -p syslog.info "tanos.sh: cleanup is not needed" | |
exit 0 | |
fi | |
tmpfile=$(mktemp) | |
function cleanup { | |
rm -f "$tmpfile" | |
} | |
trap cleanup EXIT | |
find -L "$cleanup_dir" -type f -printf '%C@\t%b\t%p\0' | sort -z -s -k 1n -k 2rn -t $'\t' > "$tmpfile" | |
total="$(awk -F $'\t' -v RS='\0' '{s+=$2} END {print s;}' "$tmpfile")" | |
awk -F $'\t' -v RS='\0' -vORS='\0' -vs="$total" -vfr="$fraction" '{if (deleted < (s*fr)) {deleted += $2; print;}}' "$tmpfile" | \ | |
cut -zf3- | xargs -r -0 rm -f | |
# just in case if some deleted files were used by syslog right now | |
systemctl reload syslog-ng || true | |
find -L "$cleanup_dir" -empty -mindepth 1 -delete | |
logger -p syslog.info "tanos.sh: cleanup succeeded" | |
) 9>/var/lock/log-gc.lock |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment