#!/bin/bash
#====================================================================
# Description: Kernel optimization for 4 Core 8GB Memory CDN Node
#             4核8G内存 CDN节点的内核优化配置
#
# Features:
# - Network optimization / 网络优化
# - TCP/IP stack tuning / TCP/IP 协议栈调优
# - Memory management / 内存管理
# - File system settings / 文件系统设置
#
# Author: Liu YanHao
# Create Time: 2025-01-06
# Last Modified: 2025-01-06
# Version: 1.0
# Usage: ./4c8g.sh
# Example: ./4c8g.sh
#====================================================================
set -e

# 内核版本4.9+
[ ! -f /etc/sysctl.conf.bak ] && mv /etc/sysctl.conf{,.bak}
cat >/etc/sysctl.conf <<'EOF'
# 基础网络设置
net.ipv4.ip_forward=1
net.ipv4.tcp_slow_start_after_idle=0
net.ipv4.tcp_no_metrics_save=1
net.ipv4.tcp_rfc1337=1
net.ipv4.tcp_timestamps=1
net.ipv4.tcp_sack=1
net.ipv4.tcp_dsack=1
net.ipv4.tcp_window_scaling=1

# TCP 内存和缓冲区设置
net.ipv4.tcp_rmem=4096 102400 8388608
net.ipv4.tcp_wmem=4096 102400 8388608
net.ipv4.tcp_mem=393216 524288 786432

# TCP 连接设置
net.ipv4.tcp_syncookies=1
net.ipv4.tcp_syn_retries=3
net.ipv4.tcp_synack_retries=3
net.ipv4.tcp_retries1=3
net.ipv4.tcp_retries2=12
net.ipv4.tcp_fin_timeout=30
net.ipv4.tcp_max_syn_backlog=131072
net.ipv4.tcp_max_orphans=131072

# TCP 优化设置
net.ipv4.tcp_tw_reuse=1
net.ipv4.tcp_keepalive_time=400
net.ipv4.tcp_keepalive_intvl=20
net.ipv4.tcp_keepalive_probes=3
net.ipv4.tcp_max_tw_buckets=450000

# 拥塞控制
net.ipv4.tcp_congestion_control=bbr
net.ipv4.tcp_fastopen=3
net.ipv4.tcp_mtu_probing=1
net.core.default_qdisc=fq

# 核心网络设置
net.core.somaxconn=4096
net.core.rmem_default=98304
net.core.wmem_default=98304
net.core.rmem_max=16777216
net.core.wmem_max=16777216
net.core.dev_weight=384
net.core.optmem_max=131072
net.core.netdev_budget=800
net.core.netdev_max_backlog=131072

# 虚拟内存设置
vm.swappiness=0
vm.dirty_writeback_centisecs=6000
vm.dirty_expire_centisecs=12000
vm.dirty_background_ratio=7
vm.dirty_ratio=15
vm.overcommit_memory=1
vm.overcommit_ratio=50
vm.max_map_count=150000

# 文件系统和内核设置
fs.aio-max-nr=1048576
fs.file-max=6553500
fs.nr_open=1048576
kernel.pid_max=1048576
EOF
