package appstore import ( "bufio" "context" "encoding/json" "errors" "fmt" "io" "net/http" "os" "os/exec" "regexp" "runtime" "sort" "strings" "sync" "time" "github.com/miaopanel/miaopanel/internal/system" ) var versionRe = regexp.MustCompile(`^[0-9][0-9A-Za-z.+~-]*$`) // nginxFpmGroupSnippet fixes the mismatch between nginx.org packages (workers // run as "nginx") and distro PHP-FPM (sockets are www-data:www-data 0660). // Without the shared group every PHP site answers 502 right after install. const nginxFpmGroupSnippet = ` if id nginx >/dev/null 2>&1; then NGINX_GROUPS=$(id -nG nginx 2>/dev/null | tr ' ' '\n') if ! printf '%%s\n' "$NGINX_GROUPS" | grep -x www-data >/dev/null; then echo "==> 将 nginx 用户加入 www-data 组,否则 PHP-FPM socket 无法连接" usermod -aG www-data nginx systemctl restart nginx 2>/dev/null || true fi fi ` const scriptHeader = `set -euo pipefail export DEBIAN_FRONTEND=noninteractive export LANG=C.UTF-8 export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin # Surface the failing command in the task log; "exit status 1" alone leaves the # operator guessing. ERR does not change the exit code. trap 'echo "==> 第 $LINENO 行失败: $BASH_COMMAND"' ERR ` func (s *Service) installScript(ctx context.Context, def AppDef, ver Version) (string, error) { distro := system.Detect() switch def.ID { case "nginx": return nginxInstallScript(distro, ver.Version), nil case "mysql": if isLegacyMySQL(ver.Version) { return mysqlLegacyInstallScript(distro, ver.Version) } return mysqlInstallScript(distro, ver.Version), nil case "mariadb": return mariadbInstallScript(distro, ver.Version), nil case "go": return goInstallScript(distro, ver.Version), nil case "node": return nodeInstallScript(distro, ver.Version), nil case "python": resolved, url, err := resolvePython(ctx, ver.Version) if err != nil { return "", err } ver.Version = resolved return pythonInstallScript(distro, resolved, url), nil case "php": return phpInstallScript(distro, ver.Version), nil case "phpmyadmin": return s.phpMyAdminInstallScript(distro, ver.Version), nil case "git": return gitInstallScript(distro), nil case "docker": return dockerInstallScript(distro), nil } return "", fmt.Errorf("不支持的应用 %q", def.ID) } func pkgCommand(d system.Distro) string { if d.Family == "rhel" { if system.Lookup("dnf") { return "dnf" } return "yum" } return "apt-get" } func aptPreamble() string { return scriptHeader + `PKG=apt-get export DEBIAN_FRONTEND=noninteractive # Some minimal images ship /usr/local/share/fonts with restrictive metadata; # fontconfig's post-install chmod then fails and aborts the whole apt run. mkdir -p /usr/local/share/fonts chmod 755 /usr/local/share/fonts 2>/dev/null || true # Repair a transaction interrupted by a panel restart before the previous run. dpkg --configure -a >/dev/null 2>&1 || true if ! command -v curl >/dev/null 2>&1; then apt-get update -qq apt-get install -y --no-install-recommends curl ca-certificates fi ` } func pkgPreamble(d system.Distro) string { if d.Family != "rhel" { return aptPreamble() } return scriptHeader + `PKG=$(command -v dnf >/dev/null 2>&1 && echo dnf || echo yum) if ! command -v curl >/dev/null 2>&1 || ! command -v tar >/dev/null 2>&1 || ! command -v xz >/dev/null 2>&1; then $PKG install -y curl ca-certificates tar xz fi ` } // nginxVerifySnippet runs after the package is unpacked. Distro dynamic module // packages are compiled against the distro nginx ABI, so switching to // nginx.org makes "nginx -t" fail with "module ... is not binary compatible". // The panel itself only uses plain config, so disabling that include is the // least invasive repair; a genuine config error still aborts the install. const nginxVerifySnippet = ` if ! nginx -t; then if [ -d /etc/nginx/modules-enabled ] && ls /etc/nginx/modules-enabled/*.conf >/dev/null 2>&1; then echo "==> nginx -t 失败:发行版动态模块与 nginx.org 版本 ABI 不兼容,禁用 modules-enabled 后重试" mv /etc/nginx/modules-enabled /etc/nginx/modules-enabled.mp-disabled mkdir -p /etc/nginx/modules-enabled fi nginx -t fi systemctl enable nginx || true systemctl restart nginx nginx -v ` func nginxInstallScript(d system.Distro, version string) string { branch := version if i := strings.LastIndexByte(version, '.'); i > 0 { branch = version[:i] } if d.Family == "rhel" { return pkgPreamble(d) + fmt.Sprintf(` . /etc/os-release MAJOR=$(echo "${VERSION_ID:-9}" | cut -d. -f1) echo "==> 配置 nginx.org RHEL 源 (el$MAJOR)" cat > /etc/yum.repos.d/nginx.repo < 安装 nginx $VER" # The RPM release suffix (-1.el9.ngx) is not part of the catalog version, so # let dnf resolve it; the exact NEVRA is the fallback when name-version does # not match. if ! $PKG install -y "nginx-$VER"; then $PKG install -y "nginx-$VER-1.el$MAJOR.ngx" fi `+nginxVerifySnippet, version) } return aptPreamble() + fmt.Sprintf(` . /etc/os-release CODENAME="${VERSION_CODENAME:-bookworm}" if [ "${ID:-debian}" = "ubuntu" ]; then REPO="https://nginx.org/packages/ubuntu"; else REPO="https://nginx.org/packages/debian"; fi echo "==> 配置 nginx.org 软件源 ($REPO $CODENAME)" if ! curl -fsSL --max-time 20 -o /dev/null "$REPO/dists/$CODENAME/Release"; then echo "nginx.org 尚未提供 $CODENAME 的软件包;请使用受支持的 Debian/Ubuntu 版本,或改用发行版自带 nginx"; exit 1 fi apt-get install -y --no-install-recommends gnupg ca-certificates curl install -d -m 0755 /usr/share/keyrings # Fetch the key into a file first: piping curl into gpg turns a slow or broken # download into SIGPIPE (141) once gpg gives up, and pipefail then reports an # opaque "exit status 141" instead of a download error. KEYRING=/usr/share/keyrings/nginx-archive-keyring.gpg # Private temporary paths: a predictable name under /tmp let a local user # pre-create a symlink and make root's curl write through it. KEY=$(mktemp /tmp/mp-nginx-key.XXXXXX) if curl -fsSL --max-time 30 -o "$KEY" https://nginx.org/keys/nginx_signing.key; then if ! gpg --dearmor --yes -o "$KEYRING" "$KEY"; then echo "==> nginx.org 签名密钥格式异常,已停止安装"; rm -f "$KEY"; exit 1 fi rm -f "$KEY" elif [ -s "$KEYRING" ]; then echo "==> 下载 nginx.org 签名密钥失败,继续使用已有的 $KEYRING" else echo "==> 下载 nginx.org 签名密钥失败,请检查服务器能否访问 nginx.org"; exit 1 fi printf 'deb [signed-by=%%s] %%s %%s nginx\n' "$KEYRING" "$REPO" "$CODENAME" > /etc/apt/sources.list.d/nginx.list apt-get update -qq || echo "==> 警告:apt-get update 有源失败,继续尝试使用现有索引" # Never pipe apt-cache into a consumer that exits early (awk ... exit, head): # apt-cache keeps writing, gets SIGPIPE, and pipefail turns that into exit 141. MADISON=$(mktemp /tmp/mp-nginx-madison.XXXXXX) apt-cache madison nginx > "$MADISON" 2>/dev/null || true VER=$(awk -v v="%s" '$3 ~ "^" v "-" {print $3; exit}' "$MADISON") if [ -z "$VER" ]; then # Not every patch level is built for every Debian/Ubuntu release (for # example 1.30.6 has no bullseye package). Fall back to the newest patch in # the same minor branch instead of failing the whole install. VER=$(awk -v v="%s." '$3 ~ "^" v {print $3}' "$MADISON" | sort -V | tail -n 1) if [ -n "$VER" ]; then echo "==> 目标版本 %s 在当前发行版不可用,改用同分支最新 $VER" fi fi if [ -z "$VER" ]; then echo "软件源中未找到 nginx %s,可用版本:" awk '{print " " $3}' "$MADISON" | sort -u rm -f "$MADISON" exit 1 fi rm -f "$MADISON" echo "==> 安装 nginx $VER" # allow-downgrades is required when switching 1.30 -> 1.28; confold keeps the # operator's nginx.conf instead of prompting during an unattended install. apt-get install -y --allow-downgrades --allow-change-held-packages \ -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold \ --no-install-recommends nginx="$VER" `+nginxVerifySnippet, version, branch, version, version) } func phpInstallScript(d system.Distro, version string) string { if d.Family == "rhel" { return pkgPreamble(d) + fmt.Sprintf(` . /etc/os-release MAJOR="${VERSION_ID%%.*}" echo "==> 配置 Remi PHP 源 (el$MAJOR)" $PKG install -y "https://rpms.remirepo.net/enterprise/remi-release-${MAJOR}.rpm" $PKG module reset php -y || true $PKG module enable "php:remi-%s" -y $PKG install -y php php-fpm php-cli php-mysqlnd php-gd php-mbstring php-xml php-curl php-zip php-bcmath php-opcache systemctl enable --now php-fpm php -v `, version) } return aptPreamble() + fmt.Sprintf(` . /etc/os-release CODENAME="${VERSION_CODENAME:-bookworm}" echo "==> 配置 Sury PHP 源 ($CODENAME)" apt-get install -y --no-install-recommends gnupg ca-certificates if ! curl -fsSL --max-time 30 -o /usr/share/keyrings/sury-php.gpg https://packages.sury.org/php/apt.gpg; then echo "==> 下载 Sury PHP 源签名密钥失败,请检查服务器能否访问 packages.sury.org"; exit 1 fi printf 'deb [signed-by=/usr/share/keyrings/sury-php.gpg] https://packages.sury.org/php/ %%s main\n' "$CODENAME" > /etc/apt/sources.list.d/sury-php.list apt-get update -qq CORE="php%s-fpm php%s-cli php%s-common php%s-mysql" EXTRA="php%s-curl php%s-gd php%s-mbstring php%s-xml php%s-zip php%s-bcmath php%s-opcache" echo "==> 安装 PHP %s" if ! apt-get install -y --no-install-recommends $CORE; then echo "==> apt 被中断,修复 dpkg 状态后重试一次" chmod 755 /usr/local/share/fonts 2>/dev/null || true dpkg --configure -a || true apt-get install -y --no-install-recommends $CORE fi # Old branches (7.x) do not ship every extension for every Debian release; # the runtime stays usable even when an optional module is unavailable. apt-get install -y --no-install-recommends $EXTRA || echo "部分 PHP 扩展不可用,已跳过" systemctl enable --now php%s-fpm php%s -v `+nginxFpmGroupSnippet, version, version, version, version, version, version, version, version, version, version, version, version, version, version) } func mariadbInstallScript(d system.Distro, version string) string { if d.Family == "rhel" { return pkgPreamble(d) + fmt.Sprintf(` echo "==> 配置 MariaDB 官方源并安装 %s" if systemctl is-active --quiet mysql || systemctl is-active --quiet mysqld; then echo "检测到 MySQL 正在运行,请先在应用商店卸载 MySQL"; exit 1 fi MARIADB_SETUP=$(mktemp /tmp/mp-mariadb-setup.XXXXXX) if ! curl -fsSL --max-time 60 -o "$MARIADB_SETUP" https://r.mariadb.com/downloads/mariadb_repo_setup; then echo "==> 下载 MariaDB 源安装脚本失败,请检查服务器能否访问 r.mariadb.com"; rm -f "$MARIADB_SETUP"; exit 1 fi if ! bash "$MARIADB_SETUP" --mariadb-server-version="mariadb-%s" --skip-maxscale --skip-tools; then echo "==> 配置 MariaDB 官方源失败"; rm -f "$MARIADB_SETUP"; exit 1 fi rm -f "$MARIADB_SETUP" $PKG install -y mariadb-server mariadb-client systemctl enable --now mariadb mariadb --version `, version, version) } return aptPreamble() + fmt.Sprintf(` echo "==> 配置 MariaDB 官方源并安装 %s" if systemctl is-active --quiet mysql || systemctl is-active --quiet mysqld; then echo "检测到 MySQL 正在运行,请先在应用商店卸载 MySQL"; exit 1 fi MARIADB_SETUP=$(mktemp /tmp/mp-mariadb-setup.XXXXXX) if ! curl -fsSL --max-time 60 -o "$MARIADB_SETUP" https://r.mariadb.com/downloads/mariadb_repo_setup; then echo "==> 下载 MariaDB 源安装脚本失败,请检查服务器能否访问 r.mariadb.com"; rm -f "$MARIADB_SETUP"; exit 1 fi if ! bash "$MARIADB_SETUP" --mariadb-server-version="mariadb-%s" --skip-maxscale --skip-tools; then echo "==> 配置 MariaDB 官方源失败"; rm -f "$MARIADB_SETUP"; exit 1 fi rm -f "$MARIADB_SETUP" apt-get update -qq if ! apt-get install -y --no-install-recommends mariadb-server mariadb-client; then echo "==> apt 被中断,修复 dpkg 状态后重试一次" chmod 755 /var/log/mysql 2>/dev/null || true chmod 755 /usr/lib/mysql/plugin/auth_pam_tool_dir/auth_pam_tool 2>/dev/null || true dpkg --configure -a || true apt-get install -y --no-install-recommends mariadb-server mariadb-client fi systemctl enable --now mariadb mariadb --version `, version, version) } // mysqlInstallScript installs Oracle MySQL from the official APT/YUM // repository. The version selects the repository component (8.0 / 8.4 LTS). // legacyMySQLFiles maps the EOL MySQL versions to their Oracle generic // binary tarballs. The APT/YUM repositories only carry 8.x, so 5.5/5.6/5.7 // are installed side by side under /www/server/mysql and run as a unit. var legacyMySQLFiles = map[string]string{ "5.7.44": "mysql-5.7.44-linux-glibc2.12-x86_64.tar.gz", "5.6.51": "mysql-5.6.51-linux-glibc2.12-x86_64.tar.gz", "5.5.62": "mysql-5.5.62-linux-glibc2.12-x86_64.tar.gz", } func isLegacyMySQL(version string) bool { _, ok := legacyMySQLFiles[version] return ok } func legacyMySQLURL(version string) (string, bool) { file, ok := legacyMySQLFiles[version] if !ok { return "", false } parts := strings.Split(version, ".") if len(parts) < 2 { return "", false } return "https://cdn.mysql.com/Downloads/MySQL-" + parts[0] + "." + parts[1] + "/" + file, true } // mysqlLegacyScript is the installer for the EOL Oracle generic binaries. // They are built against glibc 2.12 and predate the ncurses5 -> ncurses6 and // libaio -> libaio1t64 transitions, so the script verifies the architecture, // installs the missing sonames, initializes into a clean datadir and prints the // server error log when startup fails. const mysqlLegacyScript = ` VER="__VER__" URL="__URL__" TAR="__TAR__" INIT_MODE="__INIT__" ROOT=/www/server/mysql BASE="$ROOT/$VER" DATA="$ROOT/data" SOCK=/run/mysqld/mysqld.sock case "$(uname -m)" in x86_64|amd64) ;; *) echo "MySQL $VER 的 Oracle 通用二进制只提供 x86_64,当前架构 $(uname -m) 无法原生安装。" echo "建议改用 MariaDB,或在 Docker 中以 --platform linux/amd64 运行官方 mysql:$VER 镜像。" exit 1 ;; esac echo "==> 检查现有 MySQL/MariaDB" APT_MYSQL=0 if command -v dpkg >/dev/null 2>&1; then for pkg in mysql-community-server mysql-community-server-core; do if dpkg -s "$pkg" 2>/dev/null | grep '^Status: install ok installed' >/dev/null; then APT_MYSQL=1 fi done elif command -v rpm >/dev/null 2>&1; then if rpm -q mysql-community-server >/dev/null 2>&1 || rpm -q mysql-community-server-core >/dev/null 2>&1; then APT_MYSQL=1 fi fi if [ "$APT_MYSQL" = "1" ]; then echo "检测到 APT/YUM 安装的 MySQL,请先在应用商店卸载后再安装旧版"; exit 1 fi if systemctl is-active --quiet mariadb; then echo "检测到 MariaDB 正在运行,请先在应用商店卸载 MariaDB"; exit 1 fi if systemctl is-active --quiet mysql || systemctl is-active --quiet mysqld; then if "$ROOT/current/bin/mysql" --version 2>/dev/null | grep "Ver $VER" >/dev/null && [ -d "$BASE" ]; then echo "MySQL $VER 已安装"; exit 0 fi echo "检测到其他 MySQL 实例正在运行,请先停止或卸载"; exit 1 fi DATA_EXISTS=0 if [ -d "$DATA" ] && [ -n "$(ls -A "$DATA" 2>/dev/null)" ]; then if ls "$DATA" | grep -E 'aria_log|debian-.*\.flag' >/dev/null; then echo "检测到 MariaDB 数据目录 $DATA,请先备份并移走"; exit 1 fi if [ ! -f "$DATA/.mp-version" ]; then echo "数据目录 $DATA 非空但缺少版本标记,可能来自一次中断的安装;请备份后移走再重试"; exit 1 fi if [ "$(cat "$DATA/.mp-version")" != "$VER" ]; then echo "数据目录属于 MySQL $(cat "$DATA/.mp-version"),与 $VER 不兼容;请用 mysqldump 备份后移走 $DATA"; exit 1 fi DATA_EXISTS=1 echo "==> 复用已有 MySQL 数据目录 $DATA(跳过初始化)" fi echo "==> 安装运行时依赖" if [ "$PKG" = "apt-get" ]; then apt-get install -y --no-install-recommends libnuma1 libtinfo6 libcrypt1 perl || true apt-get install -y --no-install-recommends libaio1t64 || apt-get install -y --no-install-recommends libaio1 || true # Real ncurses5 packages still exist on Ubuntu <= 22.04 and Debian <= 11; # on newer releases the soname links below are the fallback. apt-get install -y --no-install-recommends libtinfo5 >/dev/null 2>&1 || true apt-get install -y --no-install-recommends libncurses5 >/dev/null 2>&1 || true else $PKG install -y libaio numactl-libs perl || true $PKG install -y libxcrypt-compat >/dev/null 2>&1 || true $PKG install -y ncurses-compat-libs >/dev/null 2>&1 || true $PKG install -y perl-Data-Dumper >/dev/null 2>&1 || true fi ldconfig 2>/dev/null || true # Same ABI, renamed soname: linking is safe, guessing package names is not. ensure_compat_link() { OLD="$1"; NEW="$2" if ldconfig -p 2>/dev/null | awk -v n="$OLD" '$1 == n { found = 1 } END { exit !found }'; then return 0 fi # awk must drain stdin: exiting on the first match would let ldconfig take # SIGPIPE and, with pipefail, abort the install with exit status 141. SRC=$(ldconfig -p 2>/dev/null | awk -v n="$NEW" '$1 == n && !found { path = $NF; found = 1 } END { if (found) print path }') if [ -z "$SRC" ] || [ ! -e "$SRC" ]; then return 0 fi DIR=$(dirname "$SRC") ln -sf "$SRC" "$DIR/$OLD" echo "==> 兼容库 $DIR/$OLD -> $SRC" } ensure_compat_link libaio.so.1 libaio.so.1t64 ensure_compat_link libtinfo.so.5 libtinfo.so.6 ensure_compat_link libncurses.so.5 libncurses.so.6 ensure_compat_link libncursesw.so.5 libncursesw.so.6 ldconfig 2>/dev/null || true # ldconfig indexes SONAMEs, so a manually linked libaio.so.1 is not listed on # t64 systems; check the real paths as well. AIO_OK=0 if ldconfig -p 2>/dev/null | awk '$1 == "libaio.so.1" { found = 1 } END { exit !found }'; then AIO_OK=1 else for dir in /usr/lib/x86_64-linux-gnu /usr/lib64 /lib64 /lib/x86_64-linux-gnu; do if [ -e "$dir/libaio.so.1" ]; then AIO_OK=1; fi done fi if [ "$AIO_OK" != "1" ]; then echo "缺少 libaio.so.1,InnoDB 无法启动;请手动安装 libaio 后重试"; exit 1 fi if [ "$INIT_MODE" = "install_db" ] && ! command -v perl >/dev/null 2>&1; then echo "MySQL $VER 的初始化脚本依赖 Perl,请先安装 perl 后重试"; exit 1 fi id mysql >/dev/null 2>&1 || useradd -r -s /bin/false mysql mkdir -p "$ROOT" /run/mysqld /www/wwwlogs/mysql echo "==> 下载 MySQL $VER 通用二进制" TMP="$ROOT/.install-$VER" rm -rf "$TMP" "/tmp/mysql-$VER.tar.gz" mkdir -p "$TMP" # Extract into a staging directory first: a failed download or unpack must not # destroy a working previous installation. curl -fL --retry 3 --retry-delay 2 --connect-timeout 20 "$URL" -o "/tmp/mysql-$VER.tar.gz" tar -xzf "/tmp/mysql-$VER.tar.gz" -C "$TMP" rm -rf "$BASE" mv "$TMP/$TAR" "$BASE" rm -rf "$TMP" "/tmp/mysql-$VER.tar.gz" ln -sfn "$BASE" "$ROOT/current" for bin in mysql mysqld mysqladmin mysqldump; do ln -sfn "$ROOT/current/bin/$bin" "/usr/local/bin/$bin" done # Run the binaries once: this catches a missing soname (libaio, ncurses5) # before we touch the datadir, and reports exactly which library is missing. if ! "$BASE/bin/mysqld" --no-defaults --version >/dev/null 2>&1; then echo "mysqld 无法运行,缺失的库:" ldd "$BASE/bin/mysqld" 2>/dev/null | grep 'not found' || true exit 1 fi if ! "$BASE/bin/mysql" --no-defaults --version >/dev/null 2>&1; then echo "mysql 客户端无法运行,缺失的库:" ldd "$BASE/bin/mysql" 2>/dev/null | grep 'not found' || true exit 1 fi cat > "$ROOT/my.cnf" </dev/null || true # A custom basedir under /www is unlabeled; on enforcing systems mysqld_t is # denied access. Label the paths when semanage exists and warn otherwise. if command -v getenforce >/dev/null 2>&1 && [ "$(getenforce)" = "Enforcing" ]; then echo "==> SELinux 处于 Enforcing,尝试为 /www 下的路径写入标签" if command -v semanage >/dev/null 2>&1; then semanage fcontext -a -t usr_t "$BASE(/.*)?" 2>/dev/null || true semanage fcontext -a -t mysqld_exec_t "$BASE/bin/mysqld" 2>/dev/null || true semanage fcontext -a -t mysqld_etc_t "$ROOT/my.cnf" 2>/dev/null || true semanage fcontext -a -t mysqld_db_t "$DATA(/.*)?" 2>/dev/null || true semanage fcontext -a -t mysqld_log_t "/www/wwwlogs/mysql(/.*)?" 2>/dev/null || true restorecon -R "$BASE" "$DATA" "$ROOT/my.cnf" /www/wwwlogs/mysql >/dev/null 2>&1 || true else echo " 未安装 semanage;若启动失败请安装 policycoreutils-python-utils,或临时 setenforce 0" fi fi if [ "$DATA_EXISTS" = "0" ]; then echo "==> 初始化数据目录" INIT_LOG="/tmp/mysql-$VER-init.log" rm -f "$INIT_LOG" set +e if [ "$INIT_MODE" = "initialize" ]; then "$BASE/bin/mysqld" --defaults-file="$ROOT/my.cnf" --initialize-insecure --user=mysql >"$INIT_LOG" 2>&1 else "$BASE/scripts/mysql_install_db" --defaults-file="$ROOT/my.cnf" --user=mysql --basedir="$BASE" --datadir="$DATA" >"$INIT_LOG" 2>&1 fi INIT_RC=$? set -e if [ "$INIT_RC" -ne 0 ]; then echo "数据目录初始化失败(退出码 $INIT_RC),最后 40 行日志:" tail -n 40 "$INIT_LOG" 2>/dev/null || true tail -n 40 /www/wwwlogs/mysql/error.log 2>/dev/null || true rm -rf "$DATA" mkdir -p "$DATA" chown mysql:mysql "$DATA" echo "已清理不完整的数据目录,请修正上面的错误后重试" exit "$INIT_RC" fi printf '%s\n' "$VER" > "$DATA/.mp-version" chown mysql:mysql "$DATA/.mp-version" fi cat > /etc/systemd/system/mysql.service </dev/null 2>&1 || true if ! systemctl restart mysql; then echo "MySQL $VER 启动失败,错误日志:" tail -n 50 /www/wwwlogs/mysql/error.log 2>/dev/null || true journalctl -u mysql -n 50 --no-pager 2>/dev/null || true exit 1 fi echo "==> 等待 MySQL 就绪" # The socket check works even when root already has a password (reused datadir), # where "mysqladmin ping" would report access denied instead of success. OK=0 for i in $(seq 1 30); do if systemctl is-active --quiet mysql && [ -S "$SOCK" ]; then OK=1 break fi sleep 1 done if [ "$OK" != "1" ]; then echo "MySQL $VER 未能在 30 秒内就绪,错误日志:" tail -n 50 /www/wwwlogs/mysql/error.log 2>/dev/null || true journalctl -u mysql -n 50 --no-pager 2>/dev/null || true if command -v getenforce >/dev/null 2>&1 && [ "$(getenforce)" = "Enforcing" ]; then echo "提示:SELinux 仍为 Enforcing,可执行 ausearch -m avc -ts recent 查看是否被拒绝" fi exit 1 fi echo "==> MySQL $VER 已就绪(数据目录 $DATA,socket $SOCK)" "$ROOT/current/bin/mysql" --version ` func mysqlLegacyInstallScript(d system.Distro, version string) (string, error) { url, ok := legacyMySQLURL(version) if !ok { return "", fmt.Errorf("不支持的 MySQL 版本 %q", version) } // --initialize-insecure exists since 5.6.7; 5.5 still ships the Perl // mysql_install_db helper. initMode := "initialize" if strings.HasPrefix(version, "5.5.") { initMode = "install_db" } body := strings.NewReplacer( "__TAR__", "mysql-"+version+"-linux-glibc2.12-x86_64", "__VER__", version, "__URL__", url, "__INIT__", initMode, ).Replace(mysqlLegacyScript) return pkgPreamble(d) + body, nil } func mysqlLegacyUninstallScript(version string) (string, error) { if _, ok := legacyMySQLFiles[version]; !ok { return "", fmt.Errorf("不支持的 MySQL 版本 %q", version) } return scriptHeader + fmt.Sprintf(` VER="%s" ROOT=/www/server/mysql echo "==> 卸载 MySQL $VER(数据目录 $ROOT/data 保留)" systemctl disable --now mysql 2>/dev/null || true rm -f /etc/systemd/system/mysql.service systemctl daemon-reload rm -rf "$ROOT/$VER" if [ -L "$ROOT/current" ] && [ "$(readlink "$ROOT/current")" = "$ROOT/$VER" ]; then rm -f "$ROOT/current" fi for bin in mysql mysqld mysqladmin mysqldump; do if [ -L "/usr/local/bin/$bin" ] && readlink "/usr/local/bin/$bin" | grep '^/www/server/mysql/' >/dev/null; then rm -f "/usr/local/bin/$bin" fi done `, version), nil } func mysqlInstallScript(d system.Distro, version string) string { major := version if i := strings.IndexByte(major, '.'); i > 0 { major = major[:i+2] } if d.Family == "rhel" { return pkgPreamble(d) + fmt.Sprintf(` . /etc/os-release MAJOR="${VERSION_ID%%.*}" if mysql --version 2>/dev/null | grep "Ver %s" >/dev/null && systemctl cat mysqld >/dev/null 2>&1; then echo "MySQL %s 已安装"; systemctl enable --now mysqld || true; mysql --version; exit 0 fi if systemctl is-active --quiet mariadb; then echo "检测到 MariaDB 正在运行,请先在应用商店卸载 MariaDB"; exit 1 fi if [ -d /var/lib/mysql ] && [ -n "$(ls -A /var/lib/mysql 2>/dev/null)" ]; then echo "检测到 /var/lib/mysql 已有数据(可能来自 MariaDB),请先备份并移走后再安装 MySQL"; exit 1 fi $PKG remove -y mariadb-server mariadb-server-core mariadb-common 2>/dev/null || true rm -f /etc/my.cnf.d/mariadb-server.cnf /etc/my.cnf.d/mariadb-client.cnf echo "==> 配置 MySQL 官方 YUM 源 (mysql-%s-community/el$MAJOR)" cat > /etc/yum.repos.d/mysql-community.repo < /www/server/panel/data/mysql_root_password.txt chmod 600 /www/server/panel/data/mysql_root_password.txt echo "MySQL root 初始密码已写入 /www/server/panel/data/mysql_root_password.txt" fi fi mysql --version `, major, major, major, major, major) } return aptPreamble() + fmt.Sprintf(` . /etc/os-release CODENAME="${VERSION_CODENAME:-bookworm}" COMP="mysql-8.4-lts" if [ "%s" = "8.0" ]; then COMP="mysql-8.0"; fi if mysql --version 2>/dev/null | grep "Ver %s" >/dev/null && systemctl cat mysql >/dev/null 2>&1; then echo "MySQL %s 已安装"; systemctl enable --now mysql || true; mysql --version; exit 0 fi if systemctl is-active --quiet mariadb; then echo "检测到 MariaDB 正在运行,请先在应用商店卸载 MariaDB"; exit 1 fi if [ -d /var/lib/mysql ] && [ -n "$(ls -A /var/lib/mysql 2>/dev/null)" ]; then if ls /var/lib/mysql | grep -E 'aria_log|debian-.*\.flag' >/dev/null; then echo "检测到 MariaDB 数据目录,请先备份并移走后再安装 MySQL"; exit 1 fi echo "检测到已有 MySQL 数据目录,安装后将直接复用 /var/lib/mysql" fi # MySQL packages conflict with the MariaDB core packages that a plain # "remove mariadb-server" leaves behind. apt-get remove -y mariadb-server-core mariadb-client-core mariadb-common galera-4 2>/dev/null || true # MariaDB's my.cnf includes options that MySQL 8.4 rejects (expire_logs_days) # and points at mariadb.conf.d; replace it with the MySQL default layout. rm -rf /etc/mysql/mariadb.conf.d if [ -f /etc/mysql/my.cnf ] && grep -q 'mariadb.conf.d' /etc/mysql/my.cnf; then cat > /etc/mysql/my.cnf <<'EOF' [client-server] socket=/run/mysqld/mysqld.sock !includedir /etc/mysql/conf.d/ !includedir /etc/mysql/mysql.conf.d/ EOF fi echo "==> 配置 MySQL 官方 APT 源 ($CODENAME $COMP)" apt-get install -y --no-install-recommends gnupg ca-certificates install -d -m 0755 /usr/share/keyrings # Fetch to a file first: piping curl into gpg reports SIGPIPE (exit 141) under # pipefail whenever the download fails, hiding the actual cause. MYSQL_KEY=$(mktemp /tmp/mp-mysql-key.XXXXXX) if ! curl -fsSL --max-time 30 -o "$MYSQL_KEY" https://repo.mysql.com/RPM-GPG-KEY-mysql-2025; then echo "==> 下载 MySQL 签名密钥失败,请检查服务器能否访问 repo.mysql.com"; rm -f "$MYSQL_KEY"; exit 1 fi if ! gpg --dearmor --yes -o /usr/share/keyrings/mysql.gpg "$MYSQL_KEY"; then echo "==> MySQL 签名密钥格式异常,已停止安装"; rm -f "$MYSQL_KEY"; exit 1 fi rm -f "$MYSQL_KEY" printf 'deb [signed-by=/usr/share/keyrings/mysql.gpg] http://repo.mysql.com/apt/debian/ %%s %%s\n' "$CODENAME" "$COMP" > /etc/apt/sources.list.d/mysql.list apt-get update -qq apt-get install -y mysql-community-server systemctl enable --now mysql mysql --version `, version, version, version) } func goInstallScript(d system.Distro, version string) string { return pkgPreamble(d) + fmt.Sprintf(` ARCH=amd64 case "$(uname -m)" in aarch64|arm64) ARCH=arm64 ;; esac DIR=/www/server/go/%s VER=%s echo "==> 下载 Go $VER ($ARCH)" TMPD=$(mktemp -d /tmp/mp-go.XXXXXX) trap 'rm -rf "$TMPD"' EXIT GOT=0 # go.dev is unreachable from many mainland networks; try the official mirror # and Aliyun before giving up, and always with a deadline so the task cannot # hang for the whole 45 minute budget. for BASE in https://go.dev/dl https://golang.google.cn/dl https://mirrors.aliyun.com/golang; do echo "==> 尝试 $BASE" if curl -fSL --no-progress-meter --max-time 180 --connect-timeout 15 --speed-limit 1024 --speed-time 30 --retry 2 -o "$TMPD/go.tar.gz" "$BASE/go${VER}.linux-$ARCH.tar.gz"; then GOT=1; break; fi rm -f "$TMPD/go.tar.gz" done if [ "$GOT" != "1" ]; then echo "==> 所有 Go 下载源均不可用(go.dev / golang.google.cn / mirrors.aliyun.com),请检查服务器网络"; exit 1 fi rm -rf "$DIR" mkdir -p "$DIR" tar -xzf "$TMPD/go.tar.gz" -C "$DIR" --strip-components=1 ln -sfn "$DIR" /www/server/go/current if [ ! -e /usr/local/bin/go ]; then ln -s /www/server/go/current/bin/go /usr/local/bin/go; fi /www/server/go/current/bin/go version `, version, version) } func nodeInstallScript(d system.Distro, version string) string { return pkgPreamble(d) + fmt.Sprintf(` ARCH=x64 case "$(uname -m)" in aarch64|arm64) ARCH=arm64 ;; esac DIR=/www/server/node/%s echo "==> 下载 Node.js %s ($ARCH)" TMPD=$(mktemp -d /tmp/mp-node.XXXXXX) trap 'rm -rf "$TMPD"' EXIT if ! curl -fSL --no-progress-meter --max-time 180 --connect-timeout 15 --speed-limit 1024 --speed-time 30 --retry 2 -o "$TMPD/node.tar.xz" "https://nodejs.org/dist/v%s/node-v%s-linux-$ARCH.tar.xz"; then echo "==> 下载 Node.js 失败,请检查服务器能否访问 nodejs.org"; exit 1 fi rm -rf "$DIR" mkdir -p "$DIR" tar -xJf "$TMPD/node.tar.xz" -C "$DIR" --strip-components=1 ln -sfn "$DIR" /www/server/node/current for bin in node npm npx; do if [ ! -e "/usr/local/bin/$bin" ]; then ln -s "/www/server/node/current/bin/$bin" "/usr/local/bin/$bin"; fi done /www/server/node/current/bin/node -v `, version, version, version, version) } func pythonInstallScript(d system.Distro, version, url string) string { return pkgPreamble(d) + fmt.Sprintf(` DIR=/www/server/python/%s echo "==> 下载 Python %s" TMPD=$(mktemp -d /tmp/mp-python.XXXXXX) trap 'rm -rf "$TMPD"' EXIT # GitHub releases are slow or blocked on some networks: a deadline keeps the # task from hanging until the 45 minute job timeout. PY_URL=%s PY_OK=0 # The releases only live on GitHub, which is slow or unreachable from many # mainland networks. Try the public GitHub proxies first and fall back to the # origin, keeping a deadline on every attempt. for PREFIX in https://gh-proxy.com/ https://ghproxy.net/ ""; do if [ -z "$PREFIX" ]; then echo "==> 尝试 GitHub 直连" else echo "==> 尝试镜像 $PREFIX" fi if curl -fSL --no-progress-meter --max-time 600 --connect-timeout 15 --speed-limit 1024 --speed-time 30 --retry 1 -o "$TMPD/python.tar.gz" "${PREFIX}${PY_URL}"; then PY_OK=1; break fi rm -f "$TMPD/python.tar.gz" done if [ "$PY_OK" != "1" ]; then echo "==> 所有 Python 下载源均不可用(gh-proxy.com / ghproxy.net / GitHub),请检查服务器网络"; exit 1 fi rm -rf "$DIR" mkdir -p "$DIR" tar -xzf "$TMPD/python.tar.gz" -C "$DIR" --strip-components=1 ln -sfn "$DIR" /www/server/python/current for bin in python3 pip3; do if [ ! -e "/usr/local/bin/$bin" ] && [ -x "/www/server/python/current/bin/$bin" ]; then ln -s "/www/server/python/current/bin/$bin" "/usr/local/bin/$bin" fi done /www/server/python/current/bin/python3 -V `, version, version, shQuote(url)) } func (s *Service) phpMyAdminInstallScript(d system.Distro, version string) string { base := s.webRoot() + "/phpmyadmin" dir := base + "/" + version return pkgPreamble(d) + fmt.Sprintf(` BASE=%s DIR=%s echo "==> 下载 phpMyAdmin %s" TMPD=$(mktemp -d /tmp/mp-pma.XXXXXX) trap 'rm -rf "$TMPD"' EXIT if ! curl -fSL --no-progress-meter --max-time 180 --connect-timeout 15 --speed-limit 1024 --speed-time 30 --retry 2 -o "$TMPD/pma.tar.gz" "https://files.phpmyadmin.net/phpMyAdmin/%s/phpMyAdmin-%s-all-languages.tar.gz"; then echo "==> 下载 phpMyAdmin 失败,请检查服务器能否访问 files.phpmyadmin.net"; exit 1 fi mkdir -p "$BASE" rm -rf "$DIR" mkdir -p "$DIR" tar -xzf "$TMPD/pma.tar.gz" -C "$DIR" --strip-components=1 SECRET=$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n') mkdir -p "$DIR/tmp" # PHP-FPM runs as www-data on Debian and apache on RHEL, while panel sites # default to the www user. A sticky 1733 directory lets whichever PHP-FPM user # is active create session files without exposing them to other users. chmod 1733 "$DIR/tmp" cat > "$DIR/config.inc.php" </dev/null 2>&1; then WEBUSER="$candidate"; break; fi done chown -R "$WEBUSER:$WEBUSER" "$DIR" 2>/dev/null || true chmod 1733 "$DIR/tmp" ln -sfn "$DIR" "$BASE/current" echo "phpMyAdmin 已安装到 $DIR" `+nginxFpmGroupSnippet, shQuote(base), shQuote(dir), version, version, version) } func gitInstallScript(d system.Distro) string { return pkgPreamble(d) + `echo "==> 安装 Git" $PKG install -y git git --version ` } func dockerInstallScript(d system.Distro) string { base := "" if d.Family == "rhel" { base = pkgPreamble(d) + ` echo "==> 配置阿里云 Docker CE 源" . /etc/os-release MAJOR="${VERSION_ID%%.*}" cat > /etc/yum.repos.d/docker-ce.repo < 配置阿里云 Docker CE 源" . /etc/os-release DOCKER_DISTRO=debian if [ "${ID:-}" = "ubuntu" ]; then DOCKER_DISTRO=ubuntu; fi apt-get update -qq apt-get install -y --no-install-recommends gnupg ca-certificates install -d -m 0755 /usr/share/keyrings DOCKER_KEY=$(mktemp /tmp/mp-docker-key.XXXXXX) if ! curl -fsSL --max-time 30 -o "$DOCKER_KEY" "https://mirrors.aliyun.com/docker-ce/linux/${DOCKER_DISTRO}/gpg"; then echo "==> 下载 Docker CE 签名密钥失败,请检查服务器能否访问 mirrors.aliyun.com"; exit 1 fi if ! gpg --dearmor --yes -o /usr/share/keyrings/docker-archive-keyring.gpg "$DOCKER_KEY"; then echo "==> Docker CE 签名密钥格式异常,已停止安装"; rm -f "$DOCKER_KEY"; exit 1 fi rm -f "$DOCKER_KEY" printf 'deb [arch=%s signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://mirrors.aliyun.com/docker-ce/linux/%s %s stable\n' \ "$(dpkg --print-architecture)" "${DOCKER_DISTRO}" "${VERSION_CODENAME:-bookworm}" \ > /etc/apt/sources.list.d/docker.list apt-get update -qq if ! apt-get install -y --no-install-recommends docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin; then echo "==> apt 被中断,修复 dpkg 状态后重试一次" dpkg --configure -a || true apt-get install -y --no-install-recommends docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin fi ` } return base + ` echo "==> 配置国内镜像加速与日志轮转" mkdir -p /etc/docker if [ ! -f /etc/docker/daemon.json ]; then cat > /etc/docker/daemon.json <<'EOF' { "registry-mirrors": ["https://docker.m.daocloud.io", "https://docker.1ms.run"], "log-driver": "json-file", "log-opts": {"max-size": "100m", "max-file": "3"}, "live-restore": true } EOF fi systemctl enable --now docker sleep 2 docker version docker compose version ` } func (s *Service) uninstallScript(def AppDef, ver Version) (string, error) { if !versionRe.MatchString(ver.Version) && ver.Version != "system" { return "", errors.New("版本号不合法") } distro := system.Detect() base := scriptHeader + "PKG=" + pkgCommand(distro) + "\n" switch def.ID { case "nginx": return base + `echo "==> 卸载 nginx" $PKG remove -y nginx || true `, nil case "php": return base + fmt.Sprintf(`echo "==> 卸载 PHP %s" systemctl disable --now php-fpm 2>/dev/null || true systemctl disable --now php%s-fpm 2>/dev/null || true if command -v apt-get >/dev/null 2>&1; then apt-get remove -y php%s-fpm php%s-cli php%s-common php%s-mysql php%s-curl php%s-gd php%s-mbstring php%s-xml php%s-zip php%s-bcmath php%s-opcache else $PKG remove -y php php-fpm php-cli php-mysqlnd php-gd php-mbstring php-xml php-curl php-zip php-bcmath php-opcache fi `, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version), nil case "mysql": if isLegacyMySQL(ver.Version) { return mysqlLegacyUninstallScript(ver.Version) } return base + `echo "==> 卸载 MySQL(数据目录 /var/lib/mysql 保留)" systemctl disable --now mysql mysqld 2>/dev/null || true # mysql-community-server-core owns /usr/sbin/mysqld. Removing only the # meta-package leaves it (and the running service) behind, which made the # store keep reporting MySQL as installed. $PKG remove -y mysql-community-server mysql-community-server-core mysql-community-client mysql-community-client-core mysql-community-client-plugins mysql-client mysql-common || true if command -v dpkg >/dev/null 2>&1; then if dpkg -l mysql-community-server-core 2>/dev/null | grep '^ii' >/dev/null; then echo "MySQL 核心包仍然存在,卸载未完成"; exit 1 fi elif command -v rpm >/dev/null 2>&1; then if rpm -q mysql-community-server-core >/dev/null 2>&1; then echo "MySQL 核心包仍然存在,卸载未完成"; exit 1 fi fi if [ -x /usr/sbin/mysqld ] && [ ! -e /www/server/mysql/current ]; then echo "检测到 /usr/sbin/mysqld 残留,卸载未完成"; exit 1 fi `, nil case "mariadb": return base + `echo "==> 卸载 MariaDB(数据目录 /var/lib/mysql 保留)" systemctl stop mariadb 2>/dev/null || true $PKG remove -y mariadb-server mariadb-client mariadb-server-core mariadb-client-core mariadb-common galera-4 || true rm -rf /etc/mysql/mariadb.conf.d `, nil case "git": return base + "echo \"==> 卸载 Git\"\n$PKG remove -y git || true\n", nil case "docker": return base + `echo "==> 卸载 Docker(/var/lib/docker 与 daemon.json 保留)" systemctl disable --now docker docker.socket containerd 2>/dev/null || true $PKG remove -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin || true `, nil case "go": return removeDirScript("/www/server/go", ver.Version, "go"), nil case "node": return removeDirScript("/www/server/node", ver.Version, "node"), nil case "python": return removeDirScript("/www/server/python", ver.Version, "python3"), nil case "phpmyadmin": return removeDirScript(s.webRoot()+"/phpmyadmin", ver.Version, ""), nil } return "", fmt.Errorf("不支持的应用 %q", def.ID) } func removeDirScript(root, version, bin string) string { return scriptHeader + fmt.Sprintf(` ROOT=%s VER=%s echo "==> 删除 $ROOT/$VER" rm -rf "$ROOT/$VER" if [ -L "$ROOT/current" ] && [ "$(readlink "$ROOT/current")" = "$ROOT/$VER" ]; then rm -f "$ROOT/current"; fi `, shQuote(root), shQuote(version)) } // resolvePython maps a catalog minor (3.12) to the newest standalone build // release and its download URL. func resolvePython(ctx context.Context, minor string) (string, string, error) { if !regexp.MustCompile(`^3\.[0-9]+$`).MatchString(minor) { return "", "", errors.New("Python 版本不合法") } reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second) defer cancel() req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, "https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest", nil) if err != nil { return "", "", err } req.Header.Set("User-Agent", "miaopanel-appstore") req.Header.Set("Accept", "application/vnd.github+json") resp, err := http.DefaultClient.Do(req) if err != nil { return "", "", fmt.Errorf("获取 Python 版本列表失败: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", "", fmt.Errorf("获取 Python 版本列表失败: HTTP %d", resp.StatusCode) } var release struct { Assets []struct { Name string `json:"name"` URL string `json:"browser_download_url"` } `json:"assets"` } if err := json.NewDecoder(io.LimitReader(resp.Body, 4<<20)).Decode(&release); err != nil { return "", "", err } arch := "x86_64" if runtime.GOARCH == "arm64" { arch = "aarch64" } pattern := regexp.MustCompile(`^cpython-(` + regexp.QuoteMeta(minor) + `\.[0-9]+)\+[0-9]+-` + arch + `-unknown-linux-gnu-install_only\.tar\.gz$`) type candidate struct { version string url string } var list []candidate for _, asset := range release.Assets { if m := pattern.FindStringSubmatch(asset.Name); m != nil { list = append(list, candidate{version: m[1], url: asset.URL}) } } if len(list) == 0 { return "", "", fmt.Errorf("未找到 Python %s 的 Linux 构建", minor) } sort.Slice(list, func(i, j int) bool { return compareVersion(list[i].version, list[j].version) > 0 }) return list[0].version, list[0].url, nil } func shQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" } func (s *Service) runScript(ctx context.Context, t *task, script string) error { cmd := exec.CommandContext(ctx, "/bin/bash", "-lc", script) cmd.Env = append(os.Environ(), "DEBIAN_FRONTEND=noninteractive", "LANG=C.UTF-8", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", ) stdout, err := cmd.StdoutPipe() if err != nil { return err } stderr, err := cmd.StderrPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } var wg sync.WaitGroup scan := func(r io.Reader) { defer wg.Done() buf := bufio.NewScanner(r) buf.Buffer(make([]byte, 0, 64*1024), 1024*1024) for buf.Scan() { t.append(buf.Text()) } } wg.Add(2) go scan(stdout) go scan(stderr) wg.Wait() err = cmd.Wait() if ctx.Err() == context.DeadlineExceeded { return errors.New("安装超时(45 分钟)") } return err }