package com.xuqm.tenant.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.function.Consumer; @Service public class SystemUpdateService { private static final Logger log = LoggerFactory.getLogger(SystemUpdateService.class); // nginx is restarted last so it picks up any patched config files. private static final List OTHER_SERVICES = List.of( "file-service", "tenant-web", "im-service", "push-service", "update-service", "license-service", "nginx" ); @Value("${PRIVATE_DEPLOY_ROOT:/opt/xuqm-private}") private String deployRoot; /** 拉取最新镜像并重建所有容器。 */ public void runUpdate(Consumer emit) { String composeFile = deployRoot + "/docker-compose.yml"; dockerLogin(emit); patchConfigs(emit); emit.accept(">>> 拉取最新镜像..."); for (String svc : OTHER_SERVICES) { emit.accept(" pulling " + svc + " ..."); exec(emit, "docker", "compose", "-f", composeFile, "pull", "--quiet", svc); } emit.accept(" pulling tenant-service ..."); exec(emit, "docker", "compose", "-f", composeFile, "pull", "--quiet", "tenant-service"); emit.accept(">>> 镜像拉取完成"); restartAndSelfUpdate(emit, composeFile); } /** 不拉取新镜像,直接用当前本地镜像重建所有容器。 */ public void runReset(Consumer emit) { String composeFile = deployRoot + "/docker-compose.yml"; patchConfigs(emit); restartAndSelfUpdate(emit, composeFile); } // ── Shared core ─────────────────────────────────────────────────────────── private void restartAndSelfUpdate(Consumer emit, String composeFile) { emit.accept(">>> 重建各服务容器..."); for (String svc : OTHER_SERVICES) { emit.accept(" restarting " + svc + " ..."); exec(emit, "docker", "compose", "-f", composeFile, "up", "-d", "--no-deps", "--force-recreate", svc); emit.accept(" " + svc + " ✓"); } emit.accept(">>> 启动自更新助手容器..."); String selfImage = getCurrentImage(); if (selfImage == null) { emit.accept(">>> [错误] 无法获取当前 tenant-service 镜像名,请手动执行:"); emit.accept(">>> docker compose -f " + composeFile + " up -d --no-deps --force-recreate tenant-service"); emit.accept("DONE"); return; } boolean helperStarted = spawnSelfUpdater(composeFile, selfImage); if (helperStarted) { emit.accept(">>> 助手容器已就绪,tenant-service 即将重建(连接将短暂中断)..."); emit.accept("RESTART_SELF"); } else { emit.accept(">>> [警告] 助手容器启动失败,请手动执行:"); emit.accept(">>> docker compose -f " + composeFile + " up -d --no-deps --force-recreate tenant-service"); emit.accept("DONE"); } } // ── Config patchers ─────────────────────────────────────────────────────── private void patchConfigs(Consumer emit) { emit.accept(">>> 检查并修复配置文件..."); patchNginxFileRoute(emit); patchNginxUpdateTimeout(emit); patchDockerComposeFileService(emit); } private void patchNginxUpdateTimeout(Consumer emit) { Path conf = Paths.get(deployRoot, "config", "nginx", "conf.d", "xuqm.conf"); if (!Files.exists(conf)) return; try { String content = Files.readString(conf); // Already patched with regex location (new format) or exact-match (old format) if (content.contains("location ~ ^/api/system/") || content.contains("location = /api/system/update")) return; String anchor = " # 核心 API(兜底,在所有具体 /api/xxx/ 之后)\n location /api/ {"; if (!content.contains(anchor)) { emit.accept(" [跳过] nginx 更新超时补丁锚点未找到,请手动检查"); return; } String injection = " # 一键更新/重置:操作耗时较长,需要更长超时(精确匹配,优先于 /api/ 前缀)\n" + " location ~ ^/api/system/(update|reset)$ {\n" + " set $svc tenant-service;\n" + " proxy_pass http://$svc:9001;\n" + " proxy_set_header Host $host;\n" + " proxy_set_header X-Real-IP $remote_addr;\n" + " proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n" + " proxy_read_timeout 600s;\n" + " proxy_send_timeout 600s;\n" + " }\n\n" + anchor; String patched = content.replace(anchor, injection); Files.writeString(conf, patched, StandardOpenOption.TRUNCATE_EXISTING); emit.accept(" [已修复] nginx: 补齐 /api/system/(update|reset) 600s 超时"); } catch (IOException e) { emit.accept(" [警告] nginx 更新超时修复失败: " + e.getMessage()); } } private void patchNginxFileRoute(Consumer emit) { Path conf = Paths.get(deployRoot, "config", "nginx", "conf.d", "xuqm.conf"); if (!Files.exists(conf)) return; try { String content = Files.readString(conf); if (!content.contains("location /file/")) return; String patched = content.replace("location /file/", "location /api/file/"); Files.writeString(conf, patched, StandardOpenOption.TRUNCATE_EXISTING); emit.accept(" [已修复] nginx: location /file/ → /api/file/"); } catch (IOException e) { emit.accept(" [警告] nginx 配置修复失败: " + e.getMessage()); } } private void patchDockerComposeFileService(Consumer emit) { Path composeFile = Paths.get(deployRoot, "docker-compose.yml"); if (!Files.exists(composeFile)) return; try { String content = Files.readString(composeFile); if (content.contains("FILE_UPLOAD_DIR") && content.contains("FILE_BASE_URL")) return; String consoleDomain = readEnvValue(Paths.get(deployRoot, "config", "xuqm.env"), "CONSOLE_DOMAIN"); if (consoleDomain == null) consoleDomain = ""; String anchor = " SPRING_DATA_REDIS_DATABASE: \"${REDIS_DATABASE:-0}\"\n"; if (!content.contains(anchor)) { emit.accept(" [跳过] docker-compose 文件-服务补丁锚点未找到,请手动检查"); return; } String injection = anchor + " FILE_UPLOAD_DIR: \"/data/uploads\"\n" + " FILE_BASE_URL: \"" + consoleDomain + "\"\n"; String patched = content.replace(anchor, injection); Files.writeString(composeFile, patched, StandardOpenOption.TRUNCATE_EXISTING); emit.accept(" [已修复] docker-compose: 补齐 FILE_UPLOAD_DIR 和 FILE_BASE_URL"); } catch (IOException e) { emit.accept(" [警告] docker-compose 修复失败: " + e.getMessage()); } } // ── Docker helpers ──────────────────────────────────────────────────────── private void dockerLogin(Consumer emit) { try { String registry = null, user = null, password = null; for (String line : Files.readAllLines(Paths.get(deployRoot + "/.env"))) { if (line.startsWith("REGISTRY=")) registry = line.substring("REGISTRY=".length()).trim(); else if (line.startsWith("REGISTRY_USER=")) user = line.substring("REGISTRY_USER=".length()).trim(); else if (line.startsWith("REGISTRY_PASSWORD=")) password = line.substring("REGISTRY_PASSWORD=".length()).trim(); } if (registry == null || user == null || password == null || password.isEmpty()) return; String host = registry.contains("/") ? registry.substring(0, registry.indexOf('/')) : registry; ProcessBuilder pb = new ProcessBuilder("docker", "login", host, "-u", user, "--password-stdin") .redirectErrorStream(true); Process p = pb.start(); p.getOutputStream().write((password + "\n").getBytes()); p.getOutputStream().flush(); p.getOutputStream().close(); String out = new String(p.getInputStream().readAllBytes()).trim(); int code = p.waitFor(); if (code == 0) { emit.accept(" 已完成镜像仓库登录"); } else { emit.accept(" [警告] 镜像仓库登录失败,将使用本地缓存(" + out + ")"); } } catch (Exception e) { emit.accept(" [警告] 读取仓库凭据失败: " + e.getMessage()); } } private boolean spawnSelfUpdater(String composeFile, String image) { try { new ProcessBuilder("docker", "rm", "-f", "xuqm-self-updater") .redirectErrorStream(true).start().waitFor(); String shellCmd = "sleep 8 && docker compose -f " + composeFile + " up -d --no-deps --force-recreate tenant-service"; Process p = new ProcessBuilder( "docker", "run", "-d", "--rm", "--name", "xuqm-self-updater", "-v", "/var/run/docker.sock:/var/run/docker.sock", "-v", deployRoot + ":" + deployRoot, "--entrypoint", "sh", image, "-c", shellCmd ).redirectErrorStream(true).start(); String out = new String(p.getInputStream().readAllBytes()).trim(); int code = p.waitFor(); log.info("self-updater spawn: code={} containerId={}", code, out); return code == 0; } catch (Exception e) { log.error("failed to spawn self-updater", e); return false; } } private String getCurrentImage() { try { Process p = new ProcessBuilder( "docker", "ps", "--filter", "label=com.docker.compose.service=tenant-service", "--format", "{{.Image}}" ).redirectErrorStream(true).start(); String out = new String(p.getInputStream().readAllBytes()).trim(); p.waitFor(); return out.isEmpty() ? null : out; } catch (Exception e) { return null; } } private String readEnvValue(Path envFile, String key) { if (!Files.exists(envFile)) return null; try { for (String line : Files.readAllLines(envFile)) { if (line.startsWith(key + "=")) { return line.substring(key.length() + 1).trim(); } } } catch (IOException ignored) {} return null; } private void exec(Consumer emit, String... cmd) { try { Process p = new ProcessBuilder(cmd) .redirectErrorStream(true) .start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { if (!line.isBlank()) emit.accept(" " + line); } } int code = p.waitFor(); if (code != 0) emit.accept(" [warn] exit code " + code); } catch (Exception e) { emit.accept(" [error] " + e.getMessage()); log.error("exec failed: {}", String.join(" ", cmd), e); } } }