├── .gitignore ├── CHANGELOG.md ├── CHANGELOG_FA.md ├── LICENCE ├── README.md ├── README_FA.md └── bbr.sh /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGELOG 2 | ## v0.7 - 2025-02-16 3 | 4 | ### Fixed 5 | 6 | - Minor bugs and stability improvements. 7 | - Optimizations for lossy and unstable network 8 | 9 | ## v0.6 - 2024-11-30 10 | 11 | ### Fixed 12 | 13 | - Removed tcp optimization based on speedtest due to instability 14 | - Optimization to set force apt to use IPv4 by default 15 | 16 | ## v0.5 - 2024-11-01 17 | 18 | ### Fixed 19 | 20 | - Removed `fq` queuing algorithm and replaced `cake` with that for better performance 21 | 22 | ## v0.4 - 2024-10-31 23 | 24 | ### Added 25 | 26 | - Configure and fix server hosts and DNS settings. 27 | - Implement function to find the optimal MTU size for improved network performance. 28 | 29 | ### Fixed 30 | 31 | - Enforce `apt update` and `apt upgrade` commands to use IPv4 to prevent connectivity issues on IPv6. 32 | 33 | ## v0.3 - 2024-10-24 34 | 35 | ### Added 36 | 37 | - Added logic to check for existing or incompatible versions of `speedtest-cli` and remove them before installing the Ookla Speedtest CLI. 38 | - Added failure handling for cases where Ookla Speedtest CLI installation via `apt` fails, logging the error and exiting the script instead of assuming a default speed. 39 | - Provided manual installation instructions for Ookla Speedtest CLI in the README file. 40 | - The script now ensures a full system update and upgrade before installing required dependencies to avoid package conflicts or outdated software. 41 | 42 | ## v0.2 - 2024-10-23 43 | 44 | ### Added 45 | 46 | - Introduced dynamic selection of queuing disciplines (`fq`, `fq_codel`, `cake`) based on system resources (RAM and CPU): 47 | - **Low-end systems**: Uses `fq_codel` for reduced latency. 48 | - **Medium-end systems**: Uses `fq` for balanced performance. 49 | - **High-end systems**: Uses `cake` for advanced queue management and optimal performance in high-traffic scenarios. 50 | - Improved TCP memory buffer and backlog settings: 51 | - Dynamically adjusts `rmem_max`, `wmem_max`, and `netdev_max_backlog` based on system resources (RAM and CPU). 52 | - Enhanced network tuning based on network speed: 53 | - Automatically configures `tcp_rmem` and `tcp_wmem` for different network speeds to optimize throughput and reduce latency. 54 | 55 | ### Changed 56 | 57 | - Set default queuing discipline via `net.core.default_qdisc` dynamically based on system benchmarks. 58 | - Retained `bbr` as the default TCP congestion control algorithm for optimal throughput and low latency. 59 | - Updated sysctl logging mechanism to capture queuing discipline choices and dynamically tuned network settings. 60 | 61 | ### Fixed 62 | 63 | - Prevented redundant backup creation of `/sysctl.conf` if a backup already exists, streamlining the configuration process. 64 | 65 | ### Other 66 | 67 | - Improved inline comments and log messaging for better readability and tracking of dynamic system adjustments. 68 | -------------------------------------------------------------------------------- /CHANGELOG_FA.md: -------------------------------------------------------------------------------- 1 | # تغییرات 2 | 3 | ## نسخه 0.7 - 16-02-2025 4 | 5 | ### رفع شده 6 | 7 | #### بهینه سازی و رفع باگ‌ها 8 | 9 | #### تغییرات در مقادیر برای بهبود عملکرد در شرایط ناپایدار و شبکه ضعیف 10 | 11 | ## نسخه 0.6 - 2024-11-30 12 | 13 | ### رفع شده 14 | 15 | #### حذف بهینه‌سازی بر اساس speedtest به دلیل عدم پایداری در شرایط مختلف 16 | 17 | #### بهینه‌سازی کد و تنظیم استفاده از IPv4 برای apt به صورت پیش‌فرض 18 | 19 | ## نسخه 0.5 - 2024-11-01 20 | 21 | ### رفع شده 22 | 23 | #### حذف الگوریتم صف‌‌بندی `fq` و استفاده از `cake` به دلیل بازدهی بهتر 24 | 25 | ## نسخه 0.4 - 2024-10-31 26 | 27 | ### اضافه شده 28 | 29 | #### تنظیم و رفع مشکلات هاست و تنظیمات DNS سرور 30 | 31 | #### پیاده‌سازی تابعی برای یافتن بهترین اندازه MTU به منظور بهبود عملکرد شبکه 32 | 33 | ### رفع شده 34 | 35 | #### الزام دستورات `apt update` و `apt upgrade` به استفاده از IPv4 برای جلوگیری از مشکلات اتصال در پیکربندی‌های IPv6 36 | 37 | ## نسخه 0.3 - 2024-10-24 38 | 39 | ### اضافه شده 40 | 41 | #### اضافه شدن منطق بررسی نسخه‌های موجود یا ناسازگار از `speedtest-cli` و حذف آن‌ها قبل از نصب Speedtest CLI از Ookla 42 | 43 | #### اضافه شدن مدیریت شکست در مواردی که نصب Ookla Speedtest CLI از طریق `apt` شکست می‌خورد، با ثبت خطا و خروج از اسکریپت به جای فرض کردن سرعت پیش‌فرض ۲۰۰ مگابیت 44 | 45 | #### ارائه دستورالعمل‌های نصب دستی برای Ookla Speedtest CLI در فایل README 46 | 47 | #### اسکریپت اکنون قبل از نصب وابستگی‌های مورد نیاز، سیستم را به طور کامل به‌روزرسانی و ارتقاء می‌دهد تا از بروز تداخل بسته‌ها یا نرم‌افزارهای قدیمی جلوگیری شود 48 | 49 | ## نسخه 0.2 - 2024-10-23 50 | 51 | ### اضافه شده 52 | 53 | #### معرفی انتخاب پویا برای انواع صف‌بندی (`fq`، `fq_codel`، `cake`) بر اساس منابع سیستم (RAM و CPU) 54 | 55 | 1- **سیستم‌های کم‌قدرت**: استفاده از `fq_codel` برای کاهش تأخیر 56 | 57 | 2- **سیستم‌های متوسط**: استفاده از `fq` برای تعادل عملکرد 58 | 59 | 3- **سیستم‌های پرقدرت**: استفاده از `cake` برای مدیریت پیشرفته صف و عملکرد بهینه در سناریوهای ترافیک بالا 60 | 61 | #### بهبود تنظیمات حافظه بافر TCP و ظرفیت صف پشتیبان 62 | 63 | 1- تنظیم پویا `rmem_max`، `wmem_max` و `netdev_max_backlog` بر اساس منابع سیستم (RAM و CPU). 64 | 65 | #### بهینه‌سازی تنظیمات شبکه بر اساس سرعت شبکه 66 | 67 | 1- تنظیم خودکار `tcp_rmem` و `tcp_wmem` برای سرعت‌های مختلف شبکه جهت بهبود گذردهی و کاهش تأخیر. 68 | 69 | ### تغییرات 70 | 71 | #### تنظیم پیش‌فرض نوع صف‌بندی از طریق `net.core.default_qdisc` به صورت پویا بر اساس نتایج بنچمارک سیستم 72 | 73 | #### حفظ `bbr` به عنوان الگوریتم کنترل تراکم TCP پیش‌فرض برای گذردهی بهینه و تأخیر کم 74 | 75 | #### به‌روزرسانی مکانیسم ثبت لاگ sysctl برای ثبت انتخاب نوع صف‌بندی و تنظیمات شبکه پویا 76 | 77 | ### رفع مشکلات 78 | 79 | #### جلوگیری از ایجاد پشتیبان تکراری از `/sysctl.conf` در صورتی که یک پشتیبان موجود باشد، به منظور ساده‌سازی فرآیند پیکربندی 80 | 81 | ### سایر 82 | 83 | #### بهبود توضیحات داخلی و پیام‌های لاگ برای خوانایی بهتر و ردیابی تنظیمات پویا سیستم 84 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | Copyright (c) 2024 DevELF 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Linux Network Optimizer v0.7 2 | 3 | This repository contains a **Bash script** designed to enhance network performance on Linux systems 4 | 5 | The script intelligently optimizes network settings based on your **system's hardware specifications** (**CPU**, **RAM**) 6 | 7 | It dynamically selects and implements the most suitable queuing discipline from **fq_codel** or **cake**, and uses the **BBR** (Bottleneck Bandwidth and Round-trip propagation time) congestion control algorithm for optimal performance 8 | 9 | - If you prefer, you can refer to the [Persian Readme](./README_FA.md) 10 | 11 | - Additionally, the [Changelog](./CHANGELOG.md) is available at the provided link. 12 | 13 | ## Key Features 14 | 15 | - Dynamically selects and configures queuing disciplines (`fq_codel`, `cake`) based on system resources to minimize latency 16 | - Implements `BBR` congestion control for optimal throughput and low latency 17 | - Adjusts TCP buffer sizes (`tcp_rmem`, `tcp_wmem`) based on system CPU and RAM 18 | - Optimizes `netdev_max_backlog` and memory buffers for handling high volumes of TCP connections 19 | - Find the optimal `MTU` size for improved network performance 20 | - Provides automatic backup and restoration of original network settings 21 | 22 | ## Prerequisites 23 | 24 | ### The script requires root privileges. If you're not logged in as root, use the following command 25 | 26 | ```bash 27 | sudo -i 28 | ``` 29 | 30 | #### 31 | 32 | ## How to Use 33 | 34 | Run the following command to update your system, install required packages, and execute the optimization script 35 | 36 | ```bash 37 | sudo apt-get -o Acquire::ForceIPv4=true update && \ 38 | sudo apt-get -o Acquire::ForceIPv4=true install -y sudo curl jq && \ 39 | bash <(curl -Ls --ipv4 https://raw.githubusercontent.com/develfishere/Linux_NetworkOptimizer/main/bbr.sh) 40 | ``` 41 | 42 | ## Support 43 | 44 | If you encounter any issues or have suggestions, feel free to open an issue in the [GitHub Issues section](https://github.com/develfishere/Linux_NetworkOptimizer/issues) 45 | 46 | ## Disclaimer 47 | 48 | This script is provided "as is," without any guarantees or warranties. Use it at your own risk. 49 | 50 | ## License 51 | 52 | This project is licensed under the MIT License. 53 | -------------------------------------------------------------------------------- /README_FA.md: -------------------------------------------------------------------------------- 1 | # بهینه‌ساز شبکه لینوکس نسخه 0.7 2 | 3 | این مخزن شامل یک **اسکریپت Bash** است که برای بهبود خودکار سرعت و عملکرد شبکه در سیستم‌های لینوکس ساخته شده است 4 | 5 | این اسکریپت با استفاده از الگوریتم **BBR**، تنظیمات شبکه را **به‌طور هوشمند** بر اساس ویژگی‌های سخت‌افزاری سیستم مانند **پردازنده** و حافظه **رم** بهینه‌سازی می‌کند 6 | 7 | در این فرآیند، مناسب‌ترین الگوریتم صف‌بندی از میان **fq_codel** و **cake** به‌طور پویا انتخاب و پیاده‌سازی می‌شود تا بهترین عملکرد و کمترین تاخیر حاصل شود 8 | 9 | **اگر ترجیح می‌دهید، می‌توانید به [راهنمای انگلیسی](./README.md) مراجعه کنید** 10 | 11 | **همچنین، [فهرست تغییرات](./CHANGELOG_FA.md) در لینک ارائه شده در دسترس است** 12 | 13 | ## ویژگی‌های کلیدی 14 | 15 | 1- انتخاب و پیکربندی هوشمند الگوریتم صف‌بندی‌ها (`fq_codel`, `cake`) بر اساس منابع سیستم 16 | 17 | 2- پیاده‌سازی کنترل ازدحام `BBR` برای دستیابی به پهنای باند بهینه و تأخیر کم 18 | 19 | 3- تنظیم اندازه بافرهای TCP (`tcp_rmem`, `tcp_wmem`) بر اساس CPU و RAM 20 | 21 | 4- بهینه‌سازی `netdev_max_backlog` و بافرهای حافظه برای مدیریت حجم بالای اتصالات TCP 22 | 23 | 5- یافتن بهترین اندازه `MTU` به منظور بهبود عملکرد شبکه 24 | 25 | 6- ارائه پشتیبان‌گیری خودکار و بازیابی تنظیمات اصلی شبکه 26 | 27 | ## پیش‌نیازها 28 | 29 | ### این اسکریپت نیاز به دسترسی روت (Sudo) دارد اگر به عنوان روت وارد سیستم نشده‌اید، از دستور زیر استفاده کنید 30 | 31 | ```bash 32 | sudo -i 33 | ``` 34 | 35 | ## نحوه استفاده 36 | 37 | برای به‌روزرسانی سیستم و اجرای اسکریپت از دستور زیر استفاده کنید 38 | 39 | ```bash 40 | sudo apt-get -o Acquire::ForceIPv4=true update && \ 41 | sudo apt-get -o Acquire::ForceIPv4=true install -y sudo curl jq && \ 42 | bash <(curl -Ls --ipv4 https://raw.githubusercontent.com/develfishere/Linux_NetworkOptimizer/main/bbr.sh) 43 | ``` 44 | 45 | ## پشتیبانی 46 | 47 | اگر با مشکلی مواجه شدید یا پیشنهادی دارید، می‌توانید آن را در [بخش مشکلات GitHub](https://github.com/develfishere/Linux_NetworkOptimizer/issues) مطرح کنید 48 | 49 | ## نکته مهم 50 | 51 | این اسکریپت به صورت "همان‌گونه که هست" ارائه شده است و هیچ ضمانتی بابت آن ارائه نمی‌شود. استفاده از آن به عهده خود شماست 52 | 53 | ## مجوز 54 | 55 | این پروژه تحت مجوز MIT ارائه شده است 56 | -------------------------------------------------------------------------------- /bbr.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | RED='\033[0;31m' 4 | GREEN='\033[0;32m' 5 | YELLOW='\033[1;33m' 6 | BLUE='\033[0;34m' 7 | CYAN='\033[0;36m' 8 | NC='\033[0m' # No Color 9 | 10 | # Ensure the script is run as root 11 | if [ "$EUID" -ne 0 ]; then 12 | echo -e "${RED}Please run as root.${NC}" 13 | exit 1 14 | fi 15 | 16 | # Function to display the logo and system information 17 | function show_header() { 18 | print_logo 19 | echo -e "\n${BLUE}==========================================${NC}" 20 | echo -e "${CYAN} Network Optimizer Script V0.7${NC}" 21 | echo -e "${BLUE}==========================================${NC}" 22 | 23 | echo -e "${GREEN}Hostname : $(hostname)${NC}" 24 | 25 | # Get OS description using lsb_release; fallback to /etc/os-release if needed 26 | os_info=$(lsb_release -d 2>/dev/null | cut -f2) 27 | if [ -z "$os_info" ]; then 28 | os_info=$(grep '^PRETTY_NAME=' /etc/os-release | cut -d '=' -f2 | tr -d '"') 29 | fi 30 | echo -e "${GREEN}OS : $os_info${NC}" 31 | 32 | echo -e "${GREEN}Kernel Version : $(uname -r)${NC}" 33 | echo -e "${GREEN}Uptime : $(uptime -p)${NC}" 34 | echo -e "${GREEN}IP Address : $(hostname -I | awk '{print $1}')${NC}" 35 | 36 | # Get CPU model information 37 | cpu_model=$(grep -m1 'model name' /proc/cpuinfo | cut -d ':' -f2 | xargs) 38 | echo -e "${GREEN}CPU : $cpu_model${NC}" 39 | 40 | echo -e "${GREEN}Architecture : $(uname -m)${NC}" 41 | 42 | # Display memory usage in a human-readable format 43 | mem_usage=$(free -h | awk '/^Mem:/{print $3 " / " $2}') 44 | echo -e "${GREEN}Memory Usage : $mem_usage${NC}" 45 | 46 | # Extract load average from uptime output and trim leading space 47 | load_avg=$(uptime | awk -F'load average:' '{print $2}' | sed 's/^ //') 48 | echo -e "${GREEN}Load Average : $load_avg${NC}" 49 | 50 | echo -e "${BLUE}==========================================${NC}\n" 51 | } 52 | 53 | 54 | # Function to print the DevElf logo 55 | print_logo() { 56 | echo -e "\n${CYAN}" 57 | echo " ______ _______ _______ _ _______ " 58 | echo "( __ \ ( ____ \|\ /|( ____ \( \ ( ____ \\" 59 | echo "| ( \ )| ( \/| ) ( || ( \/| ( | ( \/" 60 | echo "| | ) || (__ | | | || (__ | | | (__ " 61 | echo "| | | || __) ( ( ) )| __) | | | __) " 62 | echo "| | ) || ( \ \_/ / | ( | | | ( " 63 | echo "| (__/ )| (____/\ \ / | (____/\| (____/\| ) " 64 | echo "(______/ (_______/ \_/ (_______/(_______/|/ " 65 | echo -e "${NC}" 66 | echo -e "\n${BLUE}Developed by DevElf.${NC}" 67 | echo -e "${CYAN}GitHub: https://github.com/develfishere${NC}\n" 68 | } 69 | 70 | 71 | # Fix /etc/hosts file 72 | function fix_etc_hosts() { 73 | local host_path=${1:-/etc/hosts} 74 | 75 | echo -e "${YELLOW}Starting to fix the hosts file...${NC}" 76 | 77 | # Backup current hosts file 78 | if cp "$host_path" "${host_path}.bak"; then 79 | echo -e "${YELLOW}Hosts file backed up as ${host_path}.bak${NC}" 80 | else 81 | echo -e "${RED}Backup failed. Cannot proceed.${NC}" 82 | return 1 83 | fi 84 | 85 | # Check if hostname is in hosts file; add if missing 86 | if ! grep -q "$(hostname)" "$host_path"; then 87 | if echo "127.0.1.1 $(hostname)" | sudo tee -a "$host_path" > /dev/null; then 88 | echo -e "${GREEN}Hostname entry added to hosts file.${NC}" 89 | else 90 | echo -e "${RED}Failed to add hostname entry.${NC}" 91 | return 1 92 | fi 93 | else 94 | echo -e "${GREEN}Hostname entry already present. No changes needed.${NC}" 95 | fi 96 | } 97 | 98 | # Temporarily fix DNS by modifying /etc/resolv.conf 99 | function fix_dns() { 100 | local dns_path=${1:-/etc/resolv.conf} 101 | 102 | echo -e "${YELLOW}Starting to update DNS configuration...${NC}" 103 | 104 | # Backup current DNS settings 105 | if cp "$dns_path" "${dns_path}.bak"; then 106 | echo -e "${YELLOW}DNS configuration backed up as ${dns_path}.bak${NC}" 107 | else 108 | echo -e "${RED}Backup failed. Cannot proceed.${NC}" 109 | return 1 110 | fi 111 | 112 | # Clear current nameservers and add temporary ones 113 | if sed -i '/nameserver/d' "$dns_path" && { 114 | echo "nameserver 1.1.1.2" | sudo tee -a "$dns_path" > /dev/null 115 | echo "nameserver 1.0.0.2" | sudo tee -a "$dns_path" > /dev/null 116 | }; then 117 | echo -e "${GREEN}Temporary DNS servers set successfully.${NC}" 118 | else 119 | echo -e "${RED}Failed to update DNS configuration.${NC}" 120 | return 1 121 | fi 122 | } 123 | 124 | 125 | force_ipv4_apt() { 126 | local config_file="/etc/apt/apt.conf.d/99force-ipv4" 127 | local config_line='Acquire::ForceIPv4 "true";' 128 | 129 | # Check if the configuration already exists 130 | if [[ -f "$config_file" && "$(grep -Fx "$config_line" "$config_file")" == "$config_line" ]]; then 131 | echo "Configuration is already set in $config_file." 132 | return 0 133 | fi 134 | 135 | # Add the configuration 136 | echo "$config_line" | sudo tee "$config_file" >/dev/null 137 | if [[ $? -eq 0 ]]; then 138 | echo "Configuration set successfully in $config_file." 139 | else 140 | echo "Failed to set configuration." 141 | return 1 142 | fi 143 | } 144 | 145 | 146 | # Function to fully update and upgrade the server 147 | function full_update_upgrade() { 148 | echo -e "\n${YELLOW}Updating package list...${NC}" 149 | sudo apt -o Acquire::ForceIPv4=true update 150 | 151 | echo -e "\n${YELLOW}Upgrading installed packages...${NC}" 152 | sudo apt -o Acquire::ForceIPv4=true upgrade -y 153 | 154 | echo -e "\n${YELLOW}Performing full distribution upgrade...${NC}" 155 | sudo apt -o Acquire::ForceIPv4=true dist-upgrade -y 156 | 157 | echo -e "\n${YELLOW}Removing unnecessary packages...${NC}" 158 | sudo apt -o Acquire::ForceIPv4=true autoremove -y 159 | 160 | echo -e "\n${YELLOW}Cleaning up any cached packages...${NC}" 161 | sudo apt -o Acquire::ForceIPv4=true autoclean 162 | 163 | echo -e "\n${GREEN}Server update and upgrade complete.${NC}\n" 164 | } 165 | 166 | 167 | # Function to gather system information 168 | function gather_system_info() { 169 | CPU_CORES=$(nproc) 170 | TOTAL_RAM=$(free -m | awk '/Mem:/ { print $2 }') 171 | echo -e "\n${GREEN}Detected CPU cores: $CPU_CORES${NC}" 172 | echo -e "${GREEN}Detected Total RAM: ${TOTAL_RAM}MB${NC}\n" 173 | } 174 | # Function to intelligently set buffer sizes and sysctl settings 175 | function intelligent_settings() { 176 | echo -e "\n${YELLOW}Starting intelligent network optimizations...${NC}\n" 177 | 178 | echo -e "\n${YELLOW}Fixing /etc/hosts file...${NC}\n" 179 | fix_etc_hosts 180 | sleep 2 181 | 182 | echo -e "\n${YELLOW}Waiting for DNS to propagate...${NC}\n" 183 | fix_dns 184 | sleep 2 185 | 186 | echo -e "\n${YELLOW}Forcing IPv4 for APT...${NC}\n" 187 | force_ipv4_apt 188 | sleep 2 189 | 190 | echo -e "\n${YELLOW}Performing full system update and upgrade...${NC}\n" 191 | full_update_upgrade 192 | sleep 2 193 | 194 | echo -e "\n${YELLOW}Gathering system information...${NC}\n" 195 | gather_system_info 196 | sleep 2 197 | 198 | echo -e "\n$(date): Starting sysctl configuration..." 199 | sleep 2 200 | 201 | echo -e "\n${YELLOW}Backing up current sysctl.conf...${NC}\n" 202 | if [ -f /etc/sysctl.conf.bak ]; then 203 | echo -e "\n${YELLOW}Backup already exists. Skipping backup...${NC}\n" 204 | else 205 | cp /etc/sysctl.conf /etc/sysctl.conf.bak 206 | fi 207 | 208 | ############################################################################ 209 | # Dynamic tuning based on hardware resources with values adjusted for 210 | # serving clients with low internet speed and lossy networks. 211 | # 212 | # These values have been set more conservatively while still optimizing for 213 | # high TCP connection counts and efficiency. 214 | ############################################################################ 215 | if [ "$TOTAL_RAM" -lt 2000000 ] && [ "$CPU_CORES" -le 2 ]; then 216 | rmem_max=2097152 # 2 MB 217 | wmem_max=2097152 # 2 MB 218 | netdev_max_backlog=100000 219 | queuing_disc="fq_codel" 220 | tcp_mem="2097152 4194304 8388608" 221 | elif [ "$TOTAL_RAM" -lt 4000000 ] && [ "$CPU_CORES" -le 4 ]; then 222 | rmem_max=4194304 # 4 MB 223 | wmem_max=4194304 # 4 MB 224 | netdev_max_backlog=200000 225 | queuing_disc="fq_codel" 226 | tcp_mem="4194304 8388608 16777216" 227 | else 228 | rmem_max=8388608 # 8 MB 229 | wmem_max=8388608 # 8 MB 230 | netdev_max_backlog=300000 231 | queuing_disc="cake" 232 | tcp_mem="8388608 16777216 33554432" 233 | fi 234 | 235 | tcp_rmem="4096 87380 $rmem_max" 236 | tcp_wmem="4096 65536 $wmem_max" 237 | tcp_congestion_control="bbr" 238 | tcp_retries2=8 239 | 240 | echo "$(date): Set rmem_max=$rmem_max, wmem_max=$wmem_max, netdev_max_backlog=$netdev_max_backlog. Queuing discipline: $queuing_disc" 241 | echo "$(date): Set tcp_rmem=$tcp_rmem, tcp_wmem=$tcp_wmem." 242 | echo "$(date): Using TCP congestion control: $tcp_congestion_control, tcp_retries2: $tcp_retries2." 243 | 244 | ############################################################################ 245 | # Overwrite /etc/sysctl.conf with the new configuration including 246 | # additional parameters for high TCP connection handling and efficiency. 247 | ############################################################################ 248 | cat < /etc/sysctl.conf 249 | 250 | ## File system settings 251 | fs.file-max = 67108864 252 | 253 | ## Network core settings 254 | net.core.default_qdisc = $queuing_disc 255 | net.core.netdev_max_backlog = $netdev_max_backlog 256 | net.core.optmem_max = 65536 257 | net.core.somaxconn = 65536 258 | net.core.rmem_max = $rmem_max 259 | net.core.rmem_default = 524288 # 512 KB tuned for low-speed links 260 | net.core.wmem_max = $wmem_max 261 | net.core.wmem_default = 524288 # 512 KB tuned for low-speed links 262 | 263 | ## TCP settings 264 | net.ipv4.tcp_rmem = $tcp_rmem 265 | net.ipv4.tcp_wmem = $tcp_wmem 266 | net.ipv4.tcp_congestion_control = $tcp_congestion_control 267 | net.ipv4.tcp_fin_timeout = 15 268 | net.ipv4.tcp_keepalive_time = 600 269 | net.ipv4.tcp_keepalive_probes = 7 270 | net.ipv4.tcp_keepalive_intvl = 30 271 | net.ipv4.tcp_max_orphans = 1048576 272 | net.ipv4.tcp_max_syn_backlog = 262144 273 | net.ipv4.tcp_max_tw_buckets = 1440000 274 | net.ipv4.tcp_mem = $tcp_mem 275 | net.ipv4.tcp_mtu_probing = 1 276 | net.ipv4.tcp_notsent_lowat = 16384 277 | net.ipv4.tcp_retries2 = $tcp_retries2 278 | net.ipv4.tcp_sack = 1 279 | net.ipv4.tcp_dsack = 1 280 | net.ipv4.tcp_slow_start_after_idle = 0 281 | net.ipv4.tcp_window_scaling = 1 282 | net.ipv4.tcp_adv_win_scale = -2 283 | net.ipv4.tcp_ecn = 1 284 | net.ipv4.tcp_ecn_fallback = 1 285 | net.ipv4.tcp_syncookies = 1 286 | 287 | # Additional TCP tuning for high connection loads and efficiency: 288 | net.ipv4.tcp_tw_reuse = 1 # Reuse TIME_WAIT sockets for new connections 289 | net.ipv4.tcp_fastopen = 3 # Enable TCP Fast Open on both client and server sides 290 | net.ipv4.ip_local_port_range = 1024 65535 # Expand ephemeral port range 291 | net.ipv4.tcp_rfc1337 = 1 # Improve behavior for port exhaustion 292 | 293 | ## UDP settings 294 | net.ipv4.udp_mem = 65536 131072 262144 295 | 296 | ## IPv6 settings 297 | #net.ipv6.conf.all.disable_ipv6 = 0 298 | #net.ipv6.conf.default.disable_ipv6 = 0 299 | #net.ipv6.conf.lo.disable_ipv6 = 0 300 | 301 | ## UNIX domain sockets 302 | net.unix.max_dgram_qlen = 256 303 | 304 | ## Virtual memory (VM) settings 305 | vm.min_free_kbytes = 131072 306 | vm.swappiness = 10 307 | vm.vfs_cache_pressure = 250 308 | 309 | ## Network configuration 310 | net.ipv4.conf.default.rp_filter = 2 311 | net.ipv4.conf.all.rp_filter = 2 312 | net.ipv4.conf.all.accept_source_route = 0 313 | net.ipv4.conf.default.accept_source_route = 0 314 | net.ipv4.neigh.default.gc_thresh1 = 512 315 | net.ipv4.neigh.default.gc_thresh2 = 2048 316 | net.ipv4.neigh.default.gc_thresh3 = 16384 317 | net.ipv4.neigh.default.gc_stale_time = 60 318 | net.ipv4.conf.default.arp_announce = 2 319 | net.ipv4.conf.lo.arp_announce = 2 320 | net.ipv4.conf.all.arp_announce = 2 321 | 322 | kernel.panic = 1 323 | vm.dirty_ratio = 10 324 | EOL 325 | 326 | echo "$(date): Network optimizations written to /etc/sysctl.conf." 327 | 328 | sysctl -p > /dev/null 2>&1 && echo -e "\n${GREEN}Network settings applied successfully!${NC}\n" 329 | 330 | # Log the final dynamic values for reference 331 | echo -e "\n${YELLOW}Logging dynamic values...${NC}\n\n" 332 | echo "$(date): Final settings applied." 333 | echo "Total RAM: $TOTAL_RAM MB, CPU Cores: $CPU_CORES" 334 | echo "rmem_max: $rmem_max, wmem_max: $wmem_max, netdev_max_backlog: $netdev_max_backlog" 335 | echo "tcp_rmem: $tcp_rmem, tcp_wmem: $tcp_wmem" 336 | echo "TCP Congestion Control: $tcp_congestion_control, tcp_retries2: $tcp_retries2" 337 | echo "Queuing discipline: $queuing_disc" 338 | echo "" 339 | prompt_reboot 340 | } 341 | 342 | 343 | # Function to restore the original sysctl settings 344 | function restore_original() { 345 | if [ -f /etc/sysctl.conf.bak ]; then 346 | echo -e "\n${YELLOW}Restoring original network settings from backup...${NC}\n" 347 | cp /etc/sysctl.conf.bak /etc/sysctl.conf 348 | rm /etc/sysctl.conf.bak 349 | 350 | sysctl -p > /dev/null 2>&1 && echo -e "\n${GREEN}Network settings restored successfully!${NC}\n" 351 | 352 | prompt_reboot 353 | else 354 | echo -e "\n${RED}No backup found. Please manually restore sysctl.conf.${NC}\n" 355 | 356 | # Prompt user to press any key to continue 357 | read -n 1 -s -r -p "Press any key to continue..." 358 | echo # for a new line 359 | fi 360 | } 361 | 362 | find_best_mtu() { 363 | local server_ip=8.8.8.8 # Google DNS server 364 | local low=1200 # Lower bound MTU 365 | local high=1500 # Standard MTU 366 | local optimal=0 367 | 368 | echo "[MTU LOG] Starting MTU search for server: $server_ip" 369 | 370 | # Check if the server is reachable 371 | if ! ping -c 1 -W 1 "$server_ip" &>/dev/null; then 372 | echo "[MTU LOG] ERROR: Server $server_ip unreachable." 373 | return 1 374 | fi 375 | 376 | # Verify that the minimum MTU works 377 | if ! ping -M do -s $((low - 28)) -c 1 "$server_ip" &>/dev/null; then 378 | echo "[MTU LOG] ERROR: Minimum MTU of $low bytes not viable." 379 | return 1 380 | fi 381 | 382 | optimal=$low 383 | # Use binary search to find the highest MTU that works 384 | while [ $low -le $high ]; do 385 | local mid=$(( (low + high) / 2 )) 386 | if ping -M do -s $((mid - 28)) -c 1 "$server_ip" &>/dev/null; then 387 | optimal=$mid 388 | low=$(( mid + 1 )) 389 | else 390 | high=$(( mid - 1 )) 391 | fi 392 | done 393 | 394 | echo "[MTU LOG] Optimal MTU found: ${optimal} bytes" 395 | 396 | # Ask user if they want to set the current MTU to the found value 397 | read -p "[MTU LOG] Do you want to set the optimal MTU on a network interface? (Y/n): " set_mtu_choice 398 | if [[ -z "$set_mtu_choice" || "$set_mtu_choice" =~ ^[Yy] ]]; then 399 | read -p "[MTU LOG] Enter the network interface name: " iface 400 | if [[ -z "$iface" ]]; then 401 | echo "[MTU LOG] ERROR: No interface provided." 402 | return 1 403 | fi 404 | 405 | # Attempt to set the MTU using the ip command 406 | if ip link set dev "$iface" mtu "$optimal"; then 407 | echo "[MTU LOG] MTU set to ${optimal} bytes on interface $iface" 408 | else 409 | echo "[MTU LOG] ERROR: Failed to set MTU on interface $iface" 410 | return 1 411 | fi 412 | else 413 | echo "[MTU LOG] MTU setting skipped by user." 414 | fi 415 | 416 | return 0 417 | } 418 | 419 | # Function to prompt the user for a reboot 420 | function prompt_reboot() { 421 | read -p "It is recommended to reboot for changes to take effect. Reboot now? (y/[default=n]): " reboot_choice 422 | 423 | if [[ "$reboot_choice" == "y" || "$reboot_choice" == "Y" ]]; then 424 | echo -e "\n${YELLOW}Rebooting now...${NC}\n" 425 | reboot 426 | else 427 | echo -e "\n${YELLOW}Reboot skipped. Please remember to reboot manually for all changes to take effect.${NC}\n" 428 | fi 429 | 430 | # Prompt user to press any key to continue 431 | read -n 1 -s -r -p "Press any key to continue..." 432 | echo # for a new line 433 | } 434 | 435 | # Function to display the menu 436 | function show_menu() { 437 | while true; do 438 | clear 439 | show_header 440 | echo -e "${CYAN}Menu:${NC}" 441 | echo -e "${GREEN}1. Apply BBR and Intelligent Optimizations${NC}" 442 | echo -e "${GREEN}2. Find Best MTU for Server${NC}" 443 | echo -e "${GREEN}3. Restore Original Settings${NC}" 444 | echo -e "${GREEN}0. Exit${NC}" 445 | echo 446 | read -p "Enter your choice: " choice 447 | 448 | case $choice in 449 | 1) intelligent_settings ;; 450 | 2) find_best_mtu ;; 451 | 3) restore_original ;; 452 | 0) echo -e "\n${YELLOW}Exiting...${NC}" ; exit 0 ;; 453 | *) echo -e "\n${RED}Invalid option. Please try again.${NC}\n" ; sleep 2 ;; 454 | esac 455 | done 456 | } 457 | 458 | # Run the menu 459 | show_menu --------------------------------------------------------------------------------