update: bbr函数增加"测容器环境"

This commit is contained in:
Olia Lisa
2026-05-28 09:05:03 +08:00
parent 4bd898a067
commit 30a50c0292
+34 -4
View File
@@ -141,15 +141,31 @@ enable_kernel_bbr(){
return 1
fi
# 检测容器环境
local virt_type=""
if command -v systemd-detect-virt >/dev/null 2>&1; then
virt_type=$(systemd-detect-virt 2>/dev/null)
fi
case "$virt_type" in
lxc|openvz|docker|podman|container-other)
echo "检测到当前运行于容器环境: $virt_type"
echo "请在宿主机开启 BBR"
return 1
;;
esac
if [ "$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null)" = "bbr" ]; then
echo "BBR加速 已经开启,无需重复操作"
return 0
fi
# 尝试加载 bbr 模块(新内核可能已内建)
if command -v modprobe >/dev/null 2>&1; then
modprobe tcp_bbr 2>/dev/null || true
fi
# 检查内核是否支持 BBR
if ! sysctl net.ipv4.tcp_available_congestion_control 2>/dev/null | grep -qw bbr; then
echo "当前系统内核不支持 BBR"
return 1
@@ -161,22 +177,36 @@ enable_kernel_bbr(){
local file="/etc/sysctl.conf"
touch "$file"
if grep -qE "^[[:space:]]*#?[[:space:]]*$key[[:space:]]*=" "$file"; then
sed -i "s|^[[:space:]]*#\?[[:space:]]*$key[[:space:]]*=.*|$key = $value|" "$file"
# 转义 key,避免 . 被 grep/sed 当作正则
local escaped_key
escaped_key=$(printf '%s\n' "$key" | sed 's/[.[\*^$()+?{|]/\\&/g')
if grep -qE "^[[:space:]]*#?[[:space:]]*$escaped_key[[:space:]]*=" "$file"; then
sed -i "s|^[[:space:]]*#\?[[:space:]]*$escaped_key[[:space:]]*=.*|$key = $value|" "$file"
else
echo "$key = $value" >> "$file"
fi
}
# 写入配置
set_sysctl_conf "net.core.default_qdisc" "fq"
set_sysctl_conf "net.ipv4.tcp_congestion_control" "bbr"
sysctl -w net.core.default_qdisc=fq >/dev/null
sysctl -w net.ipv4.tcp_congestion_control=bbr >/dev/null
# 立即生效
sysctl -w net.core.default_qdisc=fq >/dev/null 2>&1
sysctl -w net.ipv4.tcp_congestion_control=bbr >/dev/null 2>&1
# 验证是否成功
if [ "$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null)" = "bbr" ]; then
echo "BBR加速 已开启"
else
echo "BBR开启失败"
return 1
fi
}
main(){
local container_status=$(check_container_status)
# 显示菜单