#!/bin/bash
# 清理pod节点内日志
pod_log_clean() {
# last_time=1440
# 3天前的直接删除
find /var/lib/docker/overlay2/ -type f -regextype 'posix-egrep' -regex '.*merged/home/admin/.*/*logs/.*log$' -mtime +3 -exec echo {} \; -exec rm -f {} \;
# 1天前带数字的直接删除
find /var/lib/docker/overlay2/ -type f -regextype 'posix-egrep' -regex '.*merged/home/admin/.*/*logs/.*log.*.[0-9\-]$' -mmin +${last_time} -exec echo {} \; -exec rm -f {} \;
find /var/lib/docker/overlay2/ -type f -regextype 'posix-egrep' -regex '.*merged/home/admin/.*/*logs/.*log.*[0-9].*log$' -mmin +${last_time} -exec echo {} \; -exec rm -f {} \;
# 1天前不带数字的echo清空
find /var/lib/docker/overlay2/ -type f -regextype 'posix-egrep' -regex '.*merged/home/admin/.*/*logs/.*log$' -mmin +${last_time} -size +5M | while read line
do
echo $line;
echo ''>$line;
done
}
# 清理标准输出日志
stdout_clean() {
find /var/lib/docker/containers/ -name "*-json.log" -size +100M | while read line
do
echo $line;
echo ''>$line;
done
}
# 清理无用image
image_clean() {
# This will remove all images without at least one container associated to them.
# 清理2天前拉取,未使用的镜像
docker image prune -a --filter "until=48h" -f
}
# 检查磁盘使用率是否低于标准
disk_clean=35
last_time=180
# 如果磁盘使用率大于disk_clean,执行pod内日志清理
disk_used=$(df -h | grep overlay | head -n 1 |awk '{ print $5 }' | sed 's/%//g')
if [[ ${disk_used} -ge ${disk_clean} ]]; then
pod_log_clean
disk_used=$(df -h | grep overlay | head -n 1 |awk '{ print $5 }' | sed 's/%//g')
echo "###pod_log_clean succeed! now disk_used = ${disk_used}%###"
fi
# 如果磁盘使用率还是大于disk_clean,清理标准输出日志
disk_used=$(df -h | grep overlay | head -n 1 |awk '{ print $5 }' | sed 's/%//g')
if [[ ${disk_used} -ge ${disk_clean} ]]; then
stdout_clean
disk_used=$(df -h | grep overlay | head -n 1 |awk '{ print $5 }' | sed 's/%//g')
echo "###stdout_clean succeed! now disk_used = ${disk_used}%###"
fi
# 如果磁盘使用率还是大于disk_clean,清理无用image
disk_used=$(df -h | grep overlay | head -n 1 |awk '{ print $5 }' | sed 's/%//g')
if [[ ${disk_used} -ge ${disk_clean} ]]; then
image_clean
disk_used=$(df -h | grep overlay | head -n 1 |awk '{ print $5 }' | sed 's/%//g')
echo "###image_clean succeed! now disk_used = ${disk_used}%###"
fi
disk_used=$(df -h | grep overlay | head -n 1 |awk '{ print $5 }' | sed 's/%//g')
echo "###disk_clean succeed! now disk_used = ${disk_used}%###"