miaopanel
1package appstore
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net/http"
11 "os"
12 "os/exec"
13 "regexp"
14 "runtime"
15 "sort"
16 "strings"
17 "sync"
18 "time"
19
20 "github.com/miaopanel/miaopanel/internal/system"
21)
22
23var versionRe = regexp.MustCompile(`^[0-9][0-9A-Za-z.+~-]*$`)
24
25// nginxFpmGroupSnippet fixes the mismatch between nginx.org packages (workers
26// run as "nginx") and distro PHP-FPM (sockets are www-data:www-data 0660).
27// Without the shared group every PHP site answers 502 right after install.
28const nginxFpmGroupSnippet = `
29if id nginx >/dev/null 2>&1; then
30 NGINX_GROUPS=$(id -nG nginx 2>/dev/null | tr ' ' '\n')
31 if ! printf '%%s\n' "$NGINX_GROUPS" | grep -x www-data >/dev/null; then
32 echo "==> 将 nginx 用户加入 www-data 组,否则 PHP-FPM socket 无法连接"
33 usermod -aG www-data nginx
34 systemctl restart nginx 2>/dev/null || true
35 fi
36fi
37`
38
39const scriptHeader = `set -euo pipefail
40export DEBIAN_FRONTEND=noninteractive
41export LANG=C.UTF-8
42export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
43# Surface the failing command in the task log; "exit status 1" alone leaves the
44# operator guessing. ERR does not change the exit code.
45trap 'echo "==> 第 $LINENO 行失败: $BASH_COMMAND"' ERR
46`
47
48func (s *Service) installScript(ctx context.Context, def AppDef, ver Version) (string, error) {
49 distro := system.Detect()
50 switch def.ID {
51 case "nginx":
52 return nginxInstallScript(distro, ver.Version), nil
53 case "mysql":
54 if isLegacyMySQL(ver.Version) {
55 return mysqlLegacyInstallScript(distro, ver.Version)
56 }
57 return mysqlInstallScript(distro, ver.Version), nil
58 case "mariadb":
59 return mariadbInstallScript(distro, ver.Version), nil
60 case "go":
61 return goInstallScript(distro, ver.Version), nil
62 case "node":
63 return nodeInstallScript(distro, ver.Version), nil
64 case "python":
65 resolved, url, err := resolvePython(ctx, ver.Version)
66 if err != nil {
67 return "", err
68 }
69 ver.Version = resolved
70 return pythonInstallScript(distro, resolved, url), nil
71 case "php":
72 return phpInstallScript(distro, ver.Version), nil
73 case "phpmyadmin":
74 return s.phpMyAdminInstallScript(distro, ver.Version), nil
75 case "git":
76 return gitInstallScript(distro), nil
77 case "docker":
78 return dockerInstallScript(distro), nil
79 }
80 return "", fmt.Errorf("不支持的应用 %q", def.ID)
81}
82
83func pkgCommand(d system.Distro) string {
84 if d.Family == "rhel" {
85 if system.Lookup("dnf") {
86 return "dnf"
87 }
88 return "yum"
89 }
90 return "apt-get"
91}
92
93func aptPreamble() string {
94 return scriptHeader + `PKG=apt-get
95export DEBIAN_FRONTEND=noninteractive
96# Some minimal images ship /usr/local/share/fonts with restrictive metadata;
97# fontconfig's post-install chmod then fails and aborts the whole apt run.
98mkdir -p /usr/local/share/fonts
99chmod 755 /usr/local/share/fonts 2>/dev/null || true
100# Repair a transaction interrupted by a panel restart before the previous run.
101dpkg --configure -a >/dev/null 2>&1 || true
102if ! command -v curl >/dev/null 2>&1; then
103 apt-get update -qq
104 apt-get install -y --no-install-recommends curl ca-certificates
105fi
106`
107}
108
109func pkgPreamble(d system.Distro) string {
110 if d.Family != "rhel" {
111 return aptPreamble()
112 }
113 return scriptHeader + `PKG=$(command -v dnf >/dev/null 2>&1 && echo dnf || echo yum)
114if ! command -v curl >/dev/null 2>&1 || ! command -v tar >/dev/null 2>&1 || ! command -v xz >/dev/null 2>&1; then
115 $PKG install -y curl ca-certificates tar xz
116fi
117`
118}
119
120// nginxVerifySnippet runs after the package is unpacked. Distro dynamic module
121// packages are compiled against the distro nginx ABI, so switching to
122// nginx.org makes "nginx -t" fail with "module ... is not binary compatible".
123// The panel itself only uses plain config, so disabling that include is the
124// least invasive repair; a genuine config error still aborts the install.
125const nginxVerifySnippet = `
126if ! nginx -t; then
127 if [ -d /etc/nginx/modules-enabled ] && ls /etc/nginx/modules-enabled/*.conf >/dev/null 2>&1; then
128 echo "==> nginx -t 失败:发行版动态模块与 nginx.org 版本 ABI 不兼容,禁用 modules-enabled 后重试"
129 mv /etc/nginx/modules-enabled /etc/nginx/modules-enabled.mp-disabled
130 mkdir -p /etc/nginx/modules-enabled
131 fi
132 nginx -t
133fi
134systemctl enable nginx || true
135systemctl restart nginx
136nginx -v
137`
138
139func nginxInstallScript(d system.Distro, version string) string {
140 branch := version
141 if i := strings.LastIndexByte(version, '.'); i > 0 {
142 branch = version[:i]
143 }
144 if d.Family == "rhel" {
145 return pkgPreamble(d) + fmt.Sprintf(`
146. /etc/os-release
147MAJOR=$(echo "${VERSION_ID:-9}" | cut -d. -f1)
148echo "==> 配置 nginx.org RHEL 源 (el$MAJOR)"
149cat > /etc/yum.repos.d/nginx.repo <<EOF
150[nginx-stable]
151name=nginx stable repo
152baseurl=https://nginx.org/packages/centos/$MAJOR/\$basearch/
153gpgcheck=1
154enabled=1
155gpgkey=https://nginx.org/keys/nginx_signing.key
156module_hotfixes=true
157EOF
158VER="%s"
159echo "==> 安装 nginx $VER"
160# The RPM release suffix (-1.el9.ngx) is not part of the catalog version, so
161# let dnf resolve it; the exact NEVRA is the fallback when name-version does
162# not match.
163if ! $PKG install -y "nginx-$VER"; then
164 $PKG install -y "nginx-$VER-1.el$MAJOR.ngx"
165fi
166`+nginxVerifySnippet, version)
167 }
168 return aptPreamble() + fmt.Sprintf(`
169. /etc/os-release
170CODENAME="${VERSION_CODENAME:-bookworm}"
171if [ "${ID:-debian}" = "ubuntu" ]; then REPO="https://nginx.org/packages/ubuntu"; else REPO="https://nginx.org/packages/debian"; fi
172echo "==> 配置 nginx.org 软件源 ($REPO $CODENAME)"
173if ! curl -fsSL --max-time 20 -o /dev/null "$REPO/dists/$CODENAME/Release"; then
174 echo "nginx.org 尚未提供 $CODENAME 的软件包;请使用受支持的 Debian/Ubuntu 版本,或改用发行版自带 nginx"; exit 1
175fi
176apt-get install -y --no-install-recommends gnupg ca-certificates curl
177install -d -m 0755 /usr/share/keyrings
178# Fetch the key into a file first: piping curl into gpg turns a slow or broken
179# download into SIGPIPE (141) once gpg gives up, and pipefail then reports an
180# opaque "exit status 141" instead of a download error.
181KEYRING=/usr/share/keyrings/nginx-archive-keyring.gpg
182# Private temporary paths: a predictable name under /tmp let a local user
183# pre-create a symlink and make root's curl write through it.
184KEY=$(mktemp /tmp/mp-nginx-key.XXXXXX)
185if curl -fsSL --max-time 30 -o "$KEY" https://nginx.org/keys/nginx_signing.key; then
186 if ! gpg --dearmor --yes -o "$KEYRING" "$KEY"; then
187 echo "==> nginx.org 签名密钥格式异常,已停止安装"; rm -f "$KEY"; exit 1
188 fi
189 rm -f "$KEY"
190elif [ -s "$KEYRING" ]; then
191 echo "==> 下载 nginx.org 签名密钥失败,继续使用已有的 $KEYRING"
192else
193 echo "==> 下载 nginx.org 签名密钥失败,请检查服务器能否访问 nginx.org"; exit 1
194fi
195printf 'deb [signed-by=%%s] %%s %%s nginx\n' "$KEYRING" "$REPO" "$CODENAME" > /etc/apt/sources.list.d/nginx.list
196apt-get update -qq || echo "==> 警告:apt-get update 有源失败,继续尝试使用现有索引"
197# Never pipe apt-cache into a consumer that exits early (awk ... exit, head):
198# apt-cache keeps writing, gets SIGPIPE, and pipefail turns that into exit 141.
199MADISON=$(mktemp /tmp/mp-nginx-madison.XXXXXX)
200apt-cache madison nginx > "$MADISON" 2>/dev/null || true
201VER=$(awk -v v="%s" '$3 ~ "^" v "-" {print $3; exit}' "$MADISON")
202if [ -z "$VER" ]; then
203 # Not every patch level is built for every Debian/Ubuntu release (for
204 # example 1.30.6 has no bullseye package). Fall back to the newest patch in
205 # the same minor branch instead of failing the whole install.
206 VER=$(awk -v v="%s." '$3 ~ "^" v {print $3}' "$MADISON" | sort -V | tail -n 1)
207 if [ -n "$VER" ]; then
208 echo "==> 目标版本 %s 在当前发行版不可用,改用同分支最新 $VER"
209 fi
210fi
211if [ -z "$VER" ]; then
212 echo "软件源中未找到 nginx %s,可用版本:"
213 awk '{print " " $3}' "$MADISON" | sort -u
214 rm -f "$MADISON"
215 exit 1
216fi
217rm -f "$MADISON"
218echo "==> 安装 nginx $VER"
219# allow-downgrades is required when switching 1.30 -> 1.28; confold keeps the
220# operator's nginx.conf instead of prompting during an unattended install.
221apt-get install -y --allow-downgrades --allow-change-held-packages \
222 -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold \
223 --no-install-recommends nginx="$VER"
224`+nginxVerifySnippet, version, branch, version, version)
225}
226
227func phpInstallScript(d system.Distro, version string) string {
228 if d.Family == "rhel" {
229 return pkgPreamble(d) + fmt.Sprintf(`
230. /etc/os-release
231MAJOR="${VERSION_ID%%.*}"
232echo "==> 配置 Remi PHP 源 (el$MAJOR)"
233$PKG install -y "https://rpms.remirepo.net/enterprise/remi-release-${MAJOR}.rpm"
234$PKG module reset php -y || true
235$PKG module enable "php:remi-%s" -y
236$PKG install -y php php-fpm php-cli php-mysqlnd php-gd php-mbstring php-xml php-curl php-zip php-bcmath php-opcache
237systemctl enable --now php-fpm
238php -v
239`, version)
240 }
241 return aptPreamble() + fmt.Sprintf(`
242. /etc/os-release
243CODENAME="${VERSION_CODENAME:-bookworm}"
244echo "==> 配置 Sury PHP 源 ($CODENAME)"
245apt-get install -y --no-install-recommends gnupg ca-certificates
246if ! curl -fsSL --max-time 30 -o /usr/share/keyrings/sury-php.gpg https://packages.sury.org/php/apt.gpg; then
247 echo "==> 下载 Sury PHP 源签名密钥失败,请检查服务器能否访问 packages.sury.org"; exit 1
248fi
249printf '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
250apt-get update -qq
251CORE="php%s-fpm php%s-cli php%s-common php%s-mysql"
252EXTRA="php%s-curl php%s-gd php%s-mbstring php%s-xml php%s-zip php%s-bcmath php%s-opcache"
253echo "==> 安装 PHP %s"
254if ! apt-get install -y --no-install-recommends $CORE; then
255 echo "==> apt 被中断,修复 dpkg 状态后重试一次"
256 chmod 755 /usr/local/share/fonts 2>/dev/null || true
257 dpkg --configure -a || true
258 apt-get install -y --no-install-recommends $CORE
259fi
260# Old branches (7.x) do not ship every extension for every Debian release;
261# the runtime stays usable even when an optional module is unavailable.
262apt-get install -y --no-install-recommends $EXTRA || echo "部分 PHP 扩展不可用,已跳过"
263systemctl enable --now php%s-fpm
264php%s -v
265`+nginxFpmGroupSnippet, version, version, version, version, version, version, version, version, version, version, version,
266 version, version, version)
267}
268
269func mariadbInstallScript(d system.Distro, version string) string {
270 if d.Family == "rhel" {
271 return pkgPreamble(d) + fmt.Sprintf(`
272echo "==> 配置 MariaDB 官方源并安装 %s"
273if systemctl is-active --quiet mysql || systemctl is-active --quiet mysqld; then
274 echo "检测到 MySQL 正在运行,请先在应用商店卸载 MySQL"; exit 1
275fi
276MARIADB_SETUP=$(mktemp /tmp/mp-mariadb-setup.XXXXXX)
277if ! curl -fsSL --max-time 60 -o "$MARIADB_SETUP" https://r.mariadb.com/downloads/mariadb_repo_setup; then
278 echo "==> 下载 MariaDB 源安装脚本失败,请检查服务器能否访问 r.mariadb.com"; rm -f "$MARIADB_SETUP"; exit 1
279fi
280if ! bash "$MARIADB_SETUP" --mariadb-server-version="mariadb-%s" --skip-maxscale --skip-tools; then
281 echo "==> 配置 MariaDB 官方源失败"; rm -f "$MARIADB_SETUP"; exit 1
282fi
283rm -f "$MARIADB_SETUP"
284$PKG install -y mariadb-server mariadb-client
285systemctl enable --now mariadb
286mariadb --version
287`, version, version)
288 }
289 return aptPreamble() + fmt.Sprintf(`
290echo "==> 配置 MariaDB 官方源并安装 %s"
291if systemctl is-active --quiet mysql || systemctl is-active --quiet mysqld; then
292 echo "检测到 MySQL 正在运行,请先在应用商店卸载 MySQL"; exit 1
293fi
294MARIADB_SETUP=$(mktemp /tmp/mp-mariadb-setup.XXXXXX)
295if ! curl -fsSL --max-time 60 -o "$MARIADB_SETUP" https://r.mariadb.com/downloads/mariadb_repo_setup; then
296 echo "==> 下载 MariaDB 源安装脚本失败,请检查服务器能否访问 r.mariadb.com"; rm -f "$MARIADB_SETUP"; exit 1
297fi
298if ! bash "$MARIADB_SETUP" --mariadb-server-version="mariadb-%s" --skip-maxscale --skip-tools; then
299 echo "==> 配置 MariaDB 官方源失败"; rm -f "$MARIADB_SETUP"; exit 1
300fi
301rm -f "$MARIADB_SETUP"
302apt-get update -qq
303if ! apt-get install -y --no-install-recommends mariadb-server mariadb-client; then
304 echo "==> apt 被中断,修复 dpkg 状态后重试一次"
305 chmod 755 /var/log/mysql 2>/dev/null || true
306 chmod 755 /usr/lib/mysql/plugin/auth_pam_tool_dir/auth_pam_tool 2>/dev/null || true
307 dpkg --configure -a || true
308 apt-get install -y --no-install-recommends mariadb-server mariadb-client
309fi
310systemctl enable --now mariadb
311mariadb --version
312`, version, version)
313}
314
315// mysqlInstallScript installs Oracle MySQL from the official APT/YUM
316// repository. The version selects the repository component (8.0 / 8.4 LTS).
317// legacyMySQLFiles maps the EOL MySQL versions to their Oracle generic
318// binary tarballs. The APT/YUM repositories only carry 8.x, so 5.5/5.6/5.7
319// are installed side by side under /www/server/mysql and run as a unit.
320var legacyMySQLFiles = map[string]string{
321 "5.7.44": "mysql-5.7.44-linux-glibc2.12-x86_64.tar.gz",
322 "5.6.51": "mysql-5.6.51-linux-glibc2.12-x86_64.tar.gz",
323 "5.5.62": "mysql-5.5.62-linux-glibc2.12-x86_64.tar.gz",
324}
325
326func isLegacyMySQL(version string) bool {
327 _, ok := legacyMySQLFiles[version]
328 return ok
329}
330
331func legacyMySQLURL(version string) (string, bool) {
332 file, ok := legacyMySQLFiles[version]
333 if !ok {
334 return "", false
335 }
336 parts := strings.Split(version, ".")
337 if len(parts) < 2 {
338 return "", false
339 }
340 return "https://cdn.mysql.com/Downloads/MySQL-" + parts[0] + "." + parts[1] + "/" + file, true
341}
342
343// mysqlLegacyScript is the installer for the EOL Oracle generic binaries.
344// They are built against glibc 2.12 and predate the ncurses5 -> ncurses6 and
345// libaio -> libaio1t64 transitions, so the script verifies the architecture,
346// installs the missing sonames, initializes into a clean datadir and prints the
347// server error log when startup fails.
348const mysqlLegacyScript = `
349VER="__VER__"
350URL="__URL__"
351TAR="__TAR__"
352INIT_MODE="__INIT__"
353ROOT=/www/server/mysql
354BASE="$ROOT/$VER"
355DATA="$ROOT/data"
356SOCK=/run/mysqld/mysqld.sock
357
358case "$(uname -m)" in
359 x86_64|amd64) ;;
360 *)
361 echo "MySQL $VER 的 Oracle 通用二进制只提供 x86_64,当前架构 $(uname -m) 无法原生安装。"
362 echo "建议改用 MariaDB,或在 Docker 中以 --platform linux/amd64 运行官方 mysql:$VER 镜像。"
363 exit 1
364 ;;
365esac
366
367echo "==> 检查现有 MySQL/MariaDB"
368APT_MYSQL=0
369if command -v dpkg >/dev/null 2>&1; then
370 for pkg in mysql-community-server mysql-community-server-core; do
371 if dpkg -s "$pkg" 2>/dev/null | grep '^Status: install ok installed' >/dev/null; then
372 APT_MYSQL=1
373 fi
374 done
375elif command -v rpm >/dev/null 2>&1; then
376 if rpm -q mysql-community-server >/dev/null 2>&1 || rpm -q mysql-community-server-core >/dev/null 2>&1; then
377 APT_MYSQL=1
378 fi
379fi
380if [ "$APT_MYSQL" = "1" ]; then
381 echo "检测到 APT/YUM 安装的 MySQL,请先在应用商店卸载后再安装旧版"; exit 1
382fi
383if systemctl is-active --quiet mariadb; then
384 echo "检测到 MariaDB 正在运行,请先在应用商店卸载 MariaDB"; exit 1
385fi
386if systemctl is-active --quiet mysql || systemctl is-active --quiet mysqld; then
387 if "$ROOT/current/bin/mysql" --version 2>/dev/null | grep "Ver $VER" >/dev/null && [ -d "$BASE" ]; then
388 echo "MySQL $VER 已安装"; exit 0
389 fi
390 echo "检测到其他 MySQL 实例正在运行,请先停止或卸载"; exit 1
391fi
392
393DATA_EXISTS=0
394if [ -d "$DATA" ] && [ -n "$(ls -A "$DATA" 2>/dev/null)" ]; then
395 if ls "$DATA" | grep -E 'aria_log|debian-.*\.flag' >/dev/null; then
396 echo "检测到 MariaDB 数据目录 $DATA,请先备份并移走"; exit 1
397 fi
398 if [ ! -f "$DATA/.mp-version" ]; then
399 echo "数据目录 $DATA 非空但缺少版本标记,可能来自一次中断的安装;请备份后移走再重试"; exit 1
400 fi
401 if [ "$(cat "$DATA/.mp-version")" != "$VER" ]; then
402 echo "数据目录属于 MySQL $(cat "$DATA/.mp-version"),与 $VER 不兼容;请用 mysqldump 备份后移走 $DATA"; exit 1
403 fi
404 DATA_EXISTS=1
405 echo "==> 复用已有 MySQL 数据目录 $DATA(跳过初始化)"
406fi
407
408echo "==> 安装运行时依赖"
409if [ "$PKG" = "apt-get" ]; then
410 apt-get install -y --no-install-recommends libnuma1 libtinfo6 libcrypt1 perl || true
411 apt-get install -y --no-install-recommends libaio1t64 || apt-get install -y --no-install-recommends libaio1 || true
412 # Real ncurses5 packages still exist on Ubuntu <= 22.04 and Debian <= 11;
413 # on newer releases the soname links below are the fallback.
414 apt-get install -y --no-install-recommends libtinfo5 >/dev/null 2>&1 || true
415 apt-get install -y --no-install-recommends libncurses5 >/dev/null 2>&1 || true
416else
417 $PKG install -y libaio numactl-libs perl || true
418 $PKG install -y libxcrypt-compat >/dev/null 2>&1 || true
419 $PKG install -y ncurses-compat-libs >/dev/null 2>&1 || true
420 $PKG install -y perl-Data-Dumper >/dev/null 2>&1 || true
421fi
422ldconfig 2>/dev/null || true
423
424# Same ABI, renamed soname: linking is safe, guessing package names is not.
425ensure_compat_link() {
426 OLD="$1"; NEW="$2"
427 if ldconfig -p 2>/dev/null | awk -v n="$OLD" '$1 == n { found = 1 } END { exit !found }'; then
428 return 0
429 fi
430 # awk must drain stdin: exiting on the first match would let ldconfig take
431 # SIGPIPE and, with pipefail, abort the install with exit status 141.
432 SRC=$(ldconfig -p 2>/dev/null | awk -v n="$NEW" '$1 == n && !found { path = $NF; found = 1 } END { if (found) print path }')
433 if [ -z "$SRC" ] || [ ! -e "$SRC" ]; then
434 return 0
435 fi
436 DIR=$(dirname "$SRC")
437 ln -sf "$SRC" "$DIR/$OLD"
438 echo "==> 兼容库 $DIR/$OLD -> $SRC"
439}
440ensure_compat_link libaio.so.1 libaio.so.1t64
441ensure_compat_link libtinfo.so.5 libtinfo.so.6
442ensure_compat_link libncurses.so.5 libncurses.so.6
443ensure_compat_link libncursesw.so.5 libncursesw.so.6
444ldconfig 2>/dev/null || true
445# ldconfig indexes SONAMEs, so a manually linked libaio.so.1 is not listed on
446# t64 systems; check the real paths as well.
447AIO_OK=0
448if ldconfig -p 2>/dev/null | awk '$1 == "libaio.so.1" { found = 1 } END { exit !found }'; then
449 AIO_OK=1
450else
451 for dir in /usr/lib/x86_64-linux-gnu /usr/lib64 /lib64 /lib/x86_64-linux-gnu; do
452 if [ -e "$dir/libaio.so.1" ]; then AIO_OK=1; fi
453 done
454fi
455if [ "$AIO_OK" != "1" ]; then
456 echo "缺少 libaio.so.1,InnoDB 无法启动;请手动安装 libaio 后重试"; exit 1
457fi
458if [ "$INIT_MODE" = "install_db" ] && ! command -v perl >/dev/null 2>&1; then
459 echo "MySQL $VER 的初始化脚本依赖 Perl,请先安装 perl 后重试"; exit 1
460fi
461
462id mysql >/dev/null 2>&1 || useradd -r -s /bin/false mysql
463mkdir -p "$ROOT" /run/mysqld /www/wwwlogs/mysql
464
465echo "==> 下载 MySQL $VER 通用二进制"
466TMP="$ROOT/.install-$VER"
467rm -rf "$TMP" "/tmp/mysql-$VER.tar.gz"
468mkdir -p "$TMP"
469# Extract into a staging directory first: a failed download or unpack must not
470# destroy a working previous installation.
471curl -fL --retry 3 --retry-delay 2 --connect-timeout 20 "$URL" -o "/tmp/mysql-$VER.tar.gz"
472tar -xzf "/tmp/mysql-$VER.tar.gz" -C "$TMP"
473rm -rf "$BASE"
474mv "$TMP/$TAR" "$BASE"
475rm -rf "$TMP" "/tmp/mysql-$VER.tar.gz"
476ln -sfn "$BASE" "$ROOT/current"
477for bin in mysql mysqld mysqladmin mysqldump; do
478 ln -sfn "$ROOT/current/bin/$bin" "/usr/local/bin/$bin"
479done
480
481# Run the binaries once: this catches a missing soname (libaio, ncurses5)
482# before we touch the datadir, and reports exactly which library is missing.
483if ! "$BASE/bin/mysqld" --no-defaults --version >/dev/null 2>&1; then
484 echo "mysqld 无法运行,缺失的库:"
485 ldd "$BASE/bin/mysqld" 2>/dev/null | grep 'not found' || true
486 exit 1
487fi
488if ! "$BASE/bin/mysql" --no-defaults --version >/dev/null 2>&1; then
489 echo "mysql 客户端无法运行,缺失的库:"
490 ldd "$BASE/bin/mysql" 2>/dev/null | grep 'not found' || true
491 exit 1
492fi
493
494cat > "$ROOT/my.cnf" <<EOF
495[mysqld]
496basedir=$BASE
497datadir=$DATA
498socket=$SOCK
499port=3306
500user=mysql
501pid-file=/run/mysqld/mysqld.pid
502log-error=/www/wwwlogs/mysql/error.log
503bind-address=127.0.0.1
504skip-name-resolve
505character-set-server=utf8mb4
506max_connections=200
507[client]
508socket=$SOCK
509default-character-set=utf8mb4
510EOF
511
512mkdir -p "$DATA"
513chown -R root:mysql "$BASE"
514chown -R mysql:mysql "$DATA" /run/mysqld /www/wwwlogs/mysql 2>/dev/null || true
515
516# A custom basedir under /www is unlabeled; on enforcing systems mysqld_t is
517# denied access. Label the paths when semanage exists and warn otherwise.
518if command -v getenforce >/dev/null 2>&1 && [ "$(getenforce)" = "Enforcing" ]; then
519 echo "==> SELinux 处于 Enforcing,尝试为 /www 下的路径写入标签"
520 if command -v semanage >/dev/null 2>&1; then
521 semanage fcontext -a -t usr_t "$BASE(/.*)?" 2>/dev/null || true
522 semanage fcontext -a -t mysqld_exec_t "$BASE/bin/mysqld" 2>/dev/null || true
523 semanage fcontext -a -t mysqld_etc_t "$ROOT/my.cnf" 2>/dev/null || true
524 semanage fcontext -a -t mysqld_db_t "$DATA(/.*)?" 2>/dev/null || true
525 semanage fcontext -a -t mysqld_log_t "/www/wwwlogs/mysql(/.*)?" 2>/dev/null || true
526 restorecon -R "$BASE" "$DATA" "$ROOT/my.cnf" /www/wwwlogs/mysql >/dev/null 2>&1 || true
527 else
528 echo " 未安装 semanage;若启动失败请安装 policycoreutils-python-utils,或临时 setenforce 0"
529 fi
530fi
531
532if [ "$DATA_EXISTS" = "0" ]; then
533 echo "==> 初始化数据目录"
534 INIT_LOG="/tmp/mysql-$VER-init.log"
535 rm -f "$INIT_LOG"
536 set +e
537 if [ "$INIT_MODE" = "initialize" ]; then
538 "$BASE/bin/mysqld" --defaults-file="$ROOT/my.cnf" --initialize-insecure --user=mysql >"$INIT_LOG" 2>&1
539 else
540 "$BASE/scripts/mysql_install_db" --defaults-file="$ROOT/my.cnf" --user=mysql --basedir="$BASE" --datadir="$DATA" >"$INIT_LOG" 2>&1
541 fi
542 INIT_RC=$?
543 set -e
544 if [ "$INIT_RC" -ne 0 ]; then
545 echo "数据目录初始化失败(退出码 $INIT_RC),最后 40 行日志:"
546 tail -n 40 "$INIT_LOG" 2>/dev/null || true
547 tail -n 40 /www/wwwlogs/mysql/error.log 2>/dev/null || true
548 rm -rf "$DATA"
549 mkdir -p "$DATA"
550 chown mysql:mysql "$DATA"
551 echo "已清理不完整的数据目录,请修正上面的错误后重试"
552 exit "$INIT_RC"
553 fi
554 printf '%s\n' "$VER" > "$DATA/.mp-version"
555 chown mysql:mysql "$DATA/.mp-version"
556fi
557
558cat > /etc/systemd/system/mysql.service <<EOF
559[Unit]
560Description=MySQL $VER (MiaoPanel)
561After=network.target
562
563[Service]
564User=mysql
565Group=mysql
566RuntimeDirectory=mysqld
567RuntimeDirectoryMode=0755
568Environment=LD_LIBRARY_PATH=$BASE/lib:$BASE/lib/private
569ExecStart=$ROOT/current/bin/mysqld --defaults-file=$ROOT/my.cnf
570Restart=on-failure
571RestartSec=3
572LimitNOFILE=65535
573TimeoutStartSec=300
574
575[Install]
576WantedBy=multi-user.target
577EOF
578systemctl daemon-reload
579systemctl enable mysql >/dev/null 2>&1 || true
580if ! systemctl restart mysql; then
581 echo "MySQL $VER 启动失败,错误日志:"
582 tail -n 50 /www/wwwlogs/mysql/error.log 2>/dev/null || true
583 journalctl -u mysql -n 50 --no-pager 2>/dev/null || true
584 exit 1
585fi
586
587echo "==> 等待 MySQL 就绪"
588# The socket check works even when root already has a password (reused datadir),
589# where "mysqladmin ping" would report access denied instead of success.
590OK=0
591for i in $(seq 1 30); do
592 if systemctl is-active --quiet mysql && [ -S "$SOCK" ]; then
593 OK=1
594 break
595 fi
596 sleep 1
597done
598if [ "$OK" != "1" ]; then
599 echo "MySQL $VER 未能在 30 秒内就绪,错误日志:"
600 tail -n 50 /www/wwwlogs/mysql/error.log 2>/dev/null || true
601 journalctl -u mysql -n 50 --no-pager 2>/dev/null || true
602 if command -v getenforce >/dev/null 2>&1 && [ "$(getenforce)" = "Enforcing" ]; then
603 echo "提示:SELinux 仍为 Enforcing,可执行 ausearch -m avc -ts recent 查看是否被拒绝"
604 fi
605 exit 1
606fi
607echo "==> MySQL $VER 已就绪(数据目录 $DATA,socket $SOCK)"
608"$ROOT/current/bin/mysql" --version
609`
610
611func mysqlLegacyInstallScript(d system.Distro, version string) (string, error) {
612 url, ok := legacyMySQLURL(version)
613 if !ok {
614 return "", fmt.Errorf("不支持的 MySQL 版本 %q", version)
615 }
616 // --initialize-insecure exists since 5.6.7; 5.5 still ships the Perl
617 // mysql_install_db helper.
618 initMode := "initialize"
619 if strings.HasPrefix(version, "5.5.") {
620 initMode = "install_db"
621 }
622 body := strings.NewReplacer(
623 "__TAR__", "mysql-"+version+"-linux-glibc2.12-x86_64",
624 "__VER__", version,
625 "__URL__", url,
626 "__INIT__", initMode,
627 ).Replace(mysqlLegacyScript)
628 return pkgPreamble(d) + body, nil
629}
630
631func mysqlLegacyUninstallScript(version string) (string, error) {
632 if _, ok := legacyMySQLFiles[version]; !ok {
633 return "", fmt.Errorf("不支持的 MySQL 版本 %q", version)
634 }
635 return scriptHeader + fmt.Sprintf(`
636VER="%s"
637ROOT=/www/server/mysql
638echo "==> 卸载 MySQL $VER(数据目录 $ROOT/data 保留)"
639systemctl disable --now mysql 2>/dev/null || true
640rm -f /etc/systemd/system/mysql.service
641systemctl daemon-reload
642rm -rf "$ROOT/$VER"
643if [ -L "$ROOT/current" ] && [ "$(readlink "$ROOT/current")" = "$ROOT/$VER" ]; then
644 rm -f "$ROOT/current"
645fi
646for bin in mysql mysqld mysqladmin mysqldump; do
647 if [ -L "/usr/local/bin/$bin" ] && readlink "/usr/local/bin/$bin" | grep '^/www/server/mysql/' >/dev/null; then
648 rm -f "/usr/local/bin/$bin"
649 fi
650done
651`, version), nil
652}
653
654func mysqlInstallScript(d system.Distro, version string) string {
655 major := version
656 if i := strings.IndexByte(major, '.'); i > 0 {
657 major = major[:i+2]
658 }
659 if d.Family == "rhel" {
660 return pkgPreamble(d) + fmt.Sprintf(`
661. /etc/os-release
662MAJOR="${VERSION_ID%%.*}"
663if mysql --version 2>/dev/null | grep "Ver %s" >/dev/null &&
664 systemctl cat mysqld >/dev/null 2>&1; then
665 echo "MySQL %s 已安装"; systemctl enable --now mysqld || true; mysql --version; exit 0
666fi
667if systemctl is-active --quiet mariadb; then
668 echo "检测到 MariaDB 正在运行,请先在应用商店卸载 MariaDB"; exit 1
669fi
670if [ -d /var/lib/mysql ] && [ -n "$(ls -A /var/lib/mysql 2>/dev/null)" ]; then
671 echo "检测到 /var/lib/mysql 已有数据(可能来自 MariaDB),请先备份并移走后再安装 MySQL"; exit 1
672fi
673$PKG remove -y mariadb-server mariadb-server-core mariadb-common 2>/dev/null || true
674rm -f /etc/my.cnf.d/mariadb-server.cnf /etc/my.cnf.d/mariadb-client.cnf
675echo "==> 配置 MySQL 官方 YUM 源 (mysql-%s-community/el$MAJOR)"
676cat > /etc/yum.repos.d/mysql-community.repo <<EOF
677[mysql-community]
678name=MySQL %s Community Server
679baseurl=http://repo.mysql.com/yum/mysql-%s-community/el/$MAJOR/\$basearch/
680enabled=1
681gpgcheck=1
682gpgkey=https://repo.mysql.com/RPM-GPG-KEY-mysql-2025
683module_hotfixes=1
684EOF
685$PKG install -y mysql-community-server
686systemctl enable --now mysqld
687if [ -f /var/log/mysqld.log ]; then
688 PASS=$(grep -o 'temporary password.*' /var/log/mysqld.log | tail -1 | sed 's/.*: //' || true)
689 if [ -n "$PASS" ]; then
690 install -d -m 0700 /www/server/panel/data
691 printf 'root: %%s\n' "$PASS" > /www/server/panel/data/mysql_root_password.txt
692 chmod 600 /www/server/panel/data/mysql_root_password.txt
693 echo "MySQL root 初始密码已写入 /www/server/panel/data/mysql_root_password.txt"
694 fi
695fi
696mysql --version
697`, major, major, major, major, major)
698 }
699 return aptPreamble() + fmt.Sprintf(`
700. /etc/os-release
701CODENAME="${VERSION_CODENAME:-bookworm}"
702COMP="mysql-8.4-lts"
703if [ "%s" = "8.0" ]; then COMP="mysql-8.0"; fi
704if mysql --version 2>/dev/null | grep "Ver %s" >/dev/null &&
705 systemctl cat mysql >/dev/null 2>&1; then
706 echo "MySQL %s 已安装"; systemctl enable --now mysql || true; mysql --version; exit 0
707fi
708if systemctl is-active --quiet mariadb; then
709 echo "检测到 MariaDB 正在运行,请先在应用商店卸载 MariaDB"; exit 1
710fi
711if [ -d /var/lib/mysql ] && [ -n "$(ls -A /var/lib/mysql 2>/dev/null)" ]; then
712 if ls /var/lib/mysql | grep -E 'aria_log|debian-.*\.flag' >/dev/null; then
713 echo "检测到 MariaDB 数据目录,请先备份并移走后再安装 MySQL"; exit 1
714 fi
715 echo "检测到已有 MySQL 数据目录,安装后将直接复用 /var/lib/mysql"
716fi
717# MySQL packages conflict with the MariaDB core packages that a plain
718# "remove mariadb-server" leaves behind.
719apt-get remove -y mariadb-server-core mariadb-client-core mariadb-common galera-4 2>/dev/null || true
720# MariaDB's my.cnf includes options that MySQL 8.4 rejects (expire_logs_days)
721# and points at mariadb.conf.d; replace it with the MySQL default layout.
722rm -rf /etc/mysql/mariadb.conf.d
723if [ -f /etc/mysql/my.cnf ] && grep -q 'mariadb.conf.d' /etc/mysql/my.cnf; then
724 cat > /etc/mysql/my.cnf <<'EOF'
725[client-server]
726socket=/run/mysqld/mysqld.sock
727!includedir /etc/mysql/conf.d/
728!includedir /etc/mysql/mysql.conf.d/
729EOF
730fi
731echo "==> 配置 MySQL 官方 APT 源 ($CODENAME $COMP)"
732apt-get install -y --no-install-recommends gnupg ca-certificates
733install -d -m 0755 /usr/share/keyrings
734# Fetch to a file first: piping curl into gpg reports SIGPIPE (exit 141) under
735# pipefail whenever the download fails, hiding the actual cause.
736MYSQL_KEY=$(mktemp /tmp/mp-mysql-key.XXXXXX)
737if ! curl -fsSL --max-time 30 -o "$MYSQL_KEY" https://repo.mysql.com/RPM-GPG-KEY-mysql-2025; then
738 echo "==> 下载 MySQL 签名密钥失败,请检查服务器能否访问 repo.mysql.com"; rm -f "$MYSQL_KEY"; exit 1
739fi
740if ! gpg --dearmor --yes -o /usr/share/keyrings/mysql.gpg "$MYSQL_KEY"; then
741 echo "==> MySQL 签名密钥格式异常,已停止安装"; rm -f "$MYSQL_KEY"; exit 1
742fi
743rm -f "$MYSQL_KEY"
744printf '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
745apt-get update -qq
746apt-get install -y mysql-community-server
747systemctl enable --now mysql
748mysql --version
749`, version, version, version)
750}
751
752func goInstallScript(d system.Distro, version string) string {
753 return pkgPreamble(d) + fmt.Sprintf(`
754ARCH=amd64
755case "$(uname -m)" in aarch64|arm64) ARCH=arm64 ;; esac
756DIR=/www/server/go/%s
757VER=%s
758echo "==> 下载 Go $VER ($ARCH)"
759TMPD=$(mktemp -d /tmp/mp-go.XXXXXX)
760trap 'rm -rf "$TMPD"' EXIT
761GOT=0
762# go.dev is unreachable from many mainland networks; try the official mirror
763# and Aliyun before giving up, and always with a deadline so the task cannot
764# hang for the whole 45 minute budget.
765for BASE in https://go.dev/dl https://golang.google.cn/dl https://mirrors.aliyun.com/golang; do
766 echo "==> 尝试 $BASE"
767 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
768 rm -f "$TMPD/go.tar.gz"
769done
770if [ "$GOT" != "1" ]; then
771 echo "==> 所有 Go 下载源均不可用(go.dev / golang.google.cn / mirrors.aliyun.com),请检查服务器网络"; exit 1
772fi
773rm -rf "$DIR"
774mkdir -p "$DIR"
775tar -xzf "$TMPD/go.tar.gz" -C "$DIR" --strip-components=1
776ln -sfn "$DIR" /www/server/go/current
777if [ ! -e /usr/local/bin/go ]; then ln -s /www/server/go/current/bin/go /usr/local/bin/go; fi
778/www/server/go/current/bin/go version
779`, version, version)
780}
781
782func nodeInstallScript(d system.Distro, version string) string {
783 return pkgPreamble(d) + fmt.Sprintf(`
784ARCH=x64
785case "$(uname -m)" in aarch64|arm64) ARCH=arm64 ;; esac
786DIR=/www/server/node/%s
787echo "==> 下载 Node.js %s ($ARCH)"
788TMPD=$(mktemp -d /tmp/mp-node.XXXXXX)
789trap 'rm -rf "$TMPD"' EXIT
790if ! 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
791 echo "==> 下载 Node.js 失败,请检查服务器能否访问 nodejs.org"; exit 1
792fi
793rm -rf "$DIR"
794mkdir -p "$DIR"
795tar -xJf "$TMPD/node.tar.xz" -C "$DIR" --strip-components=1
796ln -sfn "$DIR" /www/server/node/current
797for bin in node npm npx; do
798 if [ ! -e "/usr/local/bin/$bin" ]; then ln -s "/www/server/node/current/bin/$bin" "/usr/local/bin/$bin"; fi
799done
800/www/server/node/current/bin/node -v
801`, version, version, version, version)
802}
803
804func pythonInstallScript(d system.Distro, version, url string) string {
805 return pkgPreamble(d) + fmt.Sprintf(`
806DIR=/www/server/python/%s
807echo "==> 下载 Python %s"
808TMPD=$(mktemp -d /tmp/mp-python.XXXXXX)
809trap 'rm -rf "$TMPD"' EXIT
810# GitHub releases are slow or blocked on some networks: a deadline keeps the
811# task from hanging until the 45 minute job timeout.
812PY_URL=%s
813PY_OK=0
814# The releases only live on GitHub, which is slow or unreachable from many
815# mainland networks. Try the public GitHub proxies first and fall back to the
816# origin, keeping a deadline on every attempt.
817for PREFIX in https://gh-proxy.com/ https://ghproxy.net/ ""; do
818 if [ -z "$PREFIX" ]; then
819 echo "==> 尝试 GitHub 直连"
820 else
821 echo "==> 尝试镜像 $PREFIX"
822 fi
823 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
824 PY_OK=1; break
825 fi
826 rm -f "$TMPD/python.tar.gz"
827done
828if [ "$PY_OK" != "1" ]; then
829 echo "==> 所有 Python 下载源均不可用(gh-proxy.com / ghproxy.net / GitHub),请检查服务器网络"; exit 1
830fi
831rm -rf "$DIR"
832mkdir -p "$DIR"
833tar -xzf "$TMPD/python.tar.gz" -C "$DIR" --strip-components=1
834ln -sfn "$DIR" /www/server/python/current
835for bin in python3 pip3; do
836 if [ ! -e "/usr/local/bin/$bin" ] && [ -x "/www/server/python/current/bin/$bin" ]; then
837 ln -s "/www/server/python/current/bin/$bin" "/usr/local/bin/$bin"
838 fi
839done
840/www/server/python/current/bin/python3 -V
841`, version, version, shQuote(url))
842}
843
844func (s *Service) phpMyAdminInstallScript(d system.Distro, version string) string {
845 base := s.webRoot() + "/phpmyadmin"
846 dir := base + "/" + version
847 return pkgPreamble(d) + fmt.Sprintf(`
848BASE=%s
849DIR=%s
850echo "==> 下载 phpMyAdmin %s"
851TMPD=$(mktemp -d /tmp/mp-pma.XXXXXX)
852trap 'rm -rf "$TMPD"' EXIT
853if ! 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
854 echo "==> 下载 phpMyAdmin 失败,请检查服务器能否访问 files.phpmyadmin.net"; exit 1
855fi
856mkdir -p "$BASE"
857rm -rf "$DIR"
858mkdir -p "$DIR"
859tar -xzf "$TMPD/pma.tar.gz" -C "$DIR" --strip-components=1
860SECRET=$(head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
861mkdir -p "$DIR/tmp"
862# PHP-FPM runs as www-data on Debian and apache on RHEL, while panel sites
863# default to the www user. A sticky 1733 directory lets whichever PHP-FPM user
864# is active create session files without exposing them to other users.
865chmod 1733 "$DIR/tmp"
866cat > "$DIR/config.inc.php" <<EOF
867<?php
868declare(strict_types=1);
869\$cfg['blowfish_secret'] = '$SECRET';
870// Keep sessions and compiled templates inside the site root: the panel's
871// open_basedir restriction only allows the document root and its own tmp dir.
872\$cfg['TempDir'] = __DIR__ . '/tmp';
873\$cfg['SessionSavePath'] = __DIR__ . '/tmp';
874\$cfg['Servers'][\$i]['socket'] = '/run/mysqld/mysqld.sock';
875EOF
876WEBUSER=www
877for candidate in www-data apache nginx; do
878 if id "$candidate" >/dev/null 2>&1; then WEBUSER="$candidate"; break; fi
879done
880chown -R "$WEBUSER:$WEBUSER" "$DIR" 2>/dev/null || true
881chmod 1733 "$DIR/tmp"
882ln -sfn "$DIR" "$BASE/current"
883echo "phpMyAdmin 已安装到 $DIR"
884`+nginxFpmGroupSnippet, shQuote(base), shQuote(dir), version, version, version)
885}
886
887func gitInstallScript(d system.Distro) string {
888 return pkgPreamble(d) + `echo "==> 安装 Git"
889$PKG install -y git
890git --version
891`
892}
893
894func dockerInstallScript(d system.Distro) string {
895 base := ""
896 if d.Family == "rhel" {
897 base = pkgPreamble(d) + `
898echo "==> 配置阿里云 Docker CE 源"
899. /etc/os-release
900MAJOR="${VERSION_ID%%.*}"
901cat > /etc/yum.repos.d/docker-ce.repo <<EOF
902[docker-ce-stable]
903name=Docker CE Stable - Aliyun
904baseurl=https://mirrors.aliyun.com/docker-ce/linux/centos/${MAJOR}/\$basearch/stable
905enabled=1
906gpgcheck=1
907gpgkey=https://mirrors.aliyun.com/docker-ce/linux/centos/gpg
908EOF
909$PKG install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
910`
911 } else {
912 base = aptPreamble() + `
913echo "==> 配置阿里云 Docker CE 源"
914. /etc/os-release
915DOCKER_DISTRO=debian
916if [ "${ID:-}" = "ubuntu" ]; then DOCKER_DISTRO=ubuntu; fi
917apt-get update -qq
918apt-get install -y --no-install-recommends gnupg ca-certificates
919install -d -m 0755 /usr/share/keyrings
920DOCKER_KEY=$(mktemp /tmp/mp-docker-key.XXXXXX)
921if ! curl -fsSL --max-time 30 -o "$DOCKER_KEY" "https://mirrors.aliyun.com/docker-ce/linux/${DOCKER_DISTRO}/gpg"; then
922 echo "==> 下载 Docker CE 签名密钥失败,请检查服务器能否访问 mirrors.aliyun.com"; exit 1
923fi
924if ! gpg --dearmor --yes -o /usr/share/keyrings/docker-archive-keyring.gpg "$DOCKER_KEY"; then
925 echo "==> Docker CE 签名密钥格式异常,已停止安装"; rm -f "$DOCKER_KEY"; exit 1
926fi
927rm -f "$DOCKER_KEY"
928printf 'deb [arch=%s signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://mirrors.aliyun.com/docker-ce/linux/%s %s stable\n' \
929 "$(dpkg --print-architecture)" "${DOCKER_DISTRO}" "${VERSION_CODENAME:-bookworm}" \
930 > /etc/apt/sources.list.d/docker.list
931apt-get update -qq
932if ! apt-get install -y --no-install-recommends docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin; then
933 echo "==> apt 被中断,修复 dpkg 状态后重试一次"
934 dpkg --configure -a || true
935 apt-get install -y --no-install-recommends docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
936fi
937`
938 }
939 return base + `
940echo "==> 配置国内镜像加速与日志轮转"
941mkdir -p /etc/docker
942if [ ! -f /etc/docker/daemon.json ]; then
943cat > /etc/docker/daemon.json <<'EOF'
944{
945 "registry-mirrors": ["https://docker.m.daocloud.io", "https://docker.1ms.run"],
946 "log-driver": "json-file",
947 "log-opts": {"max-size": "100m", "max-file": "3"},
948 "live-restore": true
949}
950EOF
951fi
952systemctl enable --now docker
953sleep 2
954docker version
955docker compose version
956`
957}
958
959func (s *Service) uninstallScript(def AppDef, ver Version) (string, error) {
960 if !versionRe.MatchString(ver.Version) && ver.Version != "system" {
961 return "", errors.New("版本号不合法")
962 }
963 distro := system.Detect()
964 base := scriptHeader + "PKG=" + pkgCommand(distro) + "\n"
965 switch def.ID {
966 case "nginx":
967 return base + `echo "==> 卸载 nginx"
968$PKG remove -y nginx || true
969`, nil
970 case "php":
971 return base + fmt.Sprintf(`echo "==> 卸载 PHP %s"
972systemctl disable --now php-fpm 2>/dev/null || true
973systemctl disable --now php%s-fpm 2>/dev/null || true
974if command -v apt-get >/dev/null 2>&1; then
975 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
976else
977 $PKG remove -y php php-fpm php-cli php-mysqlnd php-gd php-mbstring php-xml php-curl php-zip php-bcmath php-opcache
978fi
979`, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version,
980 ver.Version, ver.Version, ver.Version, ver.Version, ver.Version, ver.Version), nil
981 case "mysql":
982 if isLegacyMySQL(ver.Version) {
983 return mysqlLegacyUninstallScript(ver.Version)
984 }
985 return base + `echo "==> 卸载 MySQL(数据目录 /var/lib/mysql 保留)"
986systemctl disable --now mysql mysqld 2>/dev/null || true
987# mysql-community-server-core owns /usr/sbin/mysqld. Removing only the
988# meta-package leaves it (and the running service) behind, which made the
989# store keep reporting MySQL as installed.
990$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
991if command -v dpkg >/dev/null 2>&1; then
992 if dpkg -l mysql-community-server-core 2>/dev/null | grep '^ii' >/dev/null; then
993 echo "MySQL 核心包仍然存在,卸载未完成"; exit 1
994 fi
995elif command -v rpm >/dev/null 2>&1; then
996 if rpm -q mysql-community-server-core >/dev/null 2>&1; then
997 echo "MySQL 核心包仍然存在,卸载未完成"; exit 1
998 fi
999fi
1000if [ -x /usr/sbin/mysqld ] && [ ! -e /www/server/mysql/current ]; then
1001 echo "检测到 /usr/sbin/mysqld 残留,卸载未完成"; exit 1
1002fi
1003`, nil
1004 case "mariadb":
1005 return base + `echo "==> 卸载 MariaDB(数据目录 /var/lib/mysql 保留)"
1006systemctl stop mariadb 2>/dev/null || true
1007$PKG remove -y mariadb-server mariadb-client mariadb-server-core mariadb-client-core mariadb-common galera-4 || true
1008rm -rf /etc/mysql/mariadb.conf.d
1009`, nil
1010 case "git":
1011 return base + "echo \"==> 卸载 Git\"\n$PKG remove -y git || true\n", nil
1012 case "docker":
1013 return base + `echo "==> 卸载 Docker(/var/lib/docker 与 daemon.json 保留)"
1014systemctl disable --now docker docker.socket containerd 2>/dev/null || true
1015$PKG remove -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin || true
1016`, nil
1017 case "go":
1018 return removeDirScript("/www/server/go", ver.Version, "go"), nil
1019 case "node":
1020 return removeDirScript("/www/server/node", ver.Version, "node"), nil
1021 case "python":
1022 return removeDirScript("/www/server/python", ver.Version, "python3"), nil
1023 case "phpmyadmin":
1024 return removeDirScript(s.webRoot()+"/phpmyadmin", ver.Version, ""), nil
1025 }
1026 return "", fmt.Errorf("不支持的应用 %q", def.ID)
1027}
1028
1029func removeDirScript(root, version, bin string) string {
1030 return scriptHeader + fmt.Sprintf(`
1031ROOT=%s
1032VER=%s
1033echo "==> 删除 $ROOT/$VER"
1034rm -rf "$ROOT/$VER"
1035if [ -L "$ROOT/current" ] && [ "$(readlink "$ROOT/current")" = "$ROOT/$VER" ]; then rm -f "$ROOT/current"; fi
1036`, shQuote(root), shQuote(version))
1037}
1038
1039// resolvePython maps a catalog minor (3.12) to the newest standalone build
1040// release and its download URL.
1041func resolvePython(ctx context.Context, minor string) (string, string, error) {
1042 if !regexp.MustCompile(`^3\.[0-9]+$`).MatchString(minor) {
1043 return "", "", errors.New("Python 版本不合法")
1044 }
1045 reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
1046 defer cancel()
1047 req, err := http.NewRequestWithContext(reqCtx, http.MethodGet,
1048 "https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest", nil)
1049 if err != nil {
1050 return "", "", err
1051 }
1052 req.Header.Set("User-Agent", "miaopanel-appstore")
1053 req.Header.Set("Accept", "application/vnd.github+json")
1054 resp, err := http.DefaultClient.Do(req)
1055 if err != nil {
1056 return "", "", fmt.Errorf("获取 Python 版本列表失败: %w", err)
1057 }
1058 defer resp.Body.Close()
1059 if resp.StatusCode != http.StatusOK {
1060 return "", "", fmt.Errorf("获取 Python 版本列表失败: HTTP %d", resp.StatusCode)
1061 }
1062 var release struct {
1063 Assets []struct {
1064 Name string `json:"name"`
1065 URL string `json:"browser_download_url"`
1066 } `json:"assets"`
1067 }
1068 if err := json.NewDecoder(io.LimitReader(resp.Body, 4<<20)).Decode(&release); err != nil {
1069 return "", "", err
1070 }
1071 arch := "x86_64"
1072 if runtime.GOARCH == "arm64" {
1073 arch = "aarch64"
1074 }
1075 pattern := regexp.MustCompile(`^cpython-(` + regexp.QuoteMeta(minor) + `\.[0-9]+)\+[0-9]+-` + arch + `-unknown-linux-gnu-install_only\.tar\.gz$`)
1076 type candidate struct {
1077 version string
1078 url string
1079 }
1080 var list []candidate
1081 for _, asset := range release.Assets {
1082 if m := pattern.FindStringSubmatch(asset.Name); m != nil {
1083 list = append(list, candidate{version: m[1], url: asset.URL})
1084 }
1085 }
1086 if len(list) == 0 {
1087 return "", "", fmt.Errorf("未找到 Python %s 的 Linux 构建", minor)
1088 }
1089 sort.Slice(list, func(i, j int) bool { return compareVersion(list[i].version, list[j].version) > 0 })
1090 return list[0].version, list[0].url, nil
1091}
1092
1093func shQuote(s string) string {
1094 return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
1095}
1096
1097func (s *Service) runScript(ctx context.Context, t *task, script string) error {
1098 cmd := exec.CommandContext(ctx, "/bin/bash", "-lc", script)
1099 cmd.Env = append(os.Environ(),
1100 "DEBIAN_FRONTEND=noninteractive",
1101 "LANG=C.UTF-8",
1102 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
1103 )
1104 stdout, err := cmd.StdoutPipe()
1105 if err != nil {
1106 return err
1107 }
1108 stderr, err := cmd.StderrPipe()
1109 if err != nil {
1110 return err
1111 }
1112 if err := cmd.Start(); err != nil {
1113 return err
1114 }
1115 var wg sync.WaitGroup
1116 scan := func(r io.Reader) {
1117 defer wg.Done()
1118 buf := bufio.NewScanner(r)
1119 buf.Buffer(make([]byte, 0, 64*1024), 1024*1024)
1120 for buf.Scan() {
1121 t.append(buf.Text())
1122 }
1123 }
1124 wg.Add(2)
1125 go scan(stdout)
1126 go scan(stderr)
1127 wg.Wait()
1128 err = cmd.Wait()
1129 if ctx.Err() == context.DeadlineExceeded {
1130 return errors.New("安装超时(45 分钟)")
1131 }
1132 return err
1133}