ClientRuntimeAgent.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. package com.mes.util;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import java.io.*;
  4. import java.net.*;
  5. import java.nio.charset.StandardCharsets;
  6. import java.nio.file.*;
  7. import java.util.Properties;
  8. import java.util.concurrent.*;
  9. /**
  10. * 客户端运行状态代理。
  11. * - 类型由 ClientType.CODE 硬编码自报
  12. * - clientId 由服务端根据 (类型, IP) 决定
  13. * - 心跳上报本地 config.properties 当前内容(currentConfigJson)
  14. * - 服务端下发 desiredConfigJson 直接合并写回 config.properties(备份 .bak)→ 重启生效
  15. * - 服务端下发 desiredJarVersion 与本地不一致 → 下载对应 jar → 备份 .bak → 替换 → 重启
  16. */
  17. public final class ClientRuntimeAgent {
  18. private static final ScheduledExecutorService EXEC = Executors.newSingleThreadScheduledExecutor(r -> {
  19. Thread t = new Thread(r, "client-runtime-agent");
  20. t.setDaemon(true);
  21. return t;
  22. });
  23. private static volatile boolean updating;
  24. private ClientRuntimeAgent() {}
  25. public static void start(String serverIp, String station, String line) {
  26. start(serverIp, station, line, "com.mes.ui.MesClient");
  27. }
  28. public static void start(final String serverIp, final String station, final String line, final String mainClass) {
  29. if (serverIp == null || serverIp.trim().isEmpty()) return;
  30. send(serverIp, station, line, mainClass);
  31. EXEC.scheduleAtFixedRate(() -> send(serverIp, station, line, mainClass), 30, 30, TimeUnit.SECONDS);
  32. }
  33. private static void send(String serverIp, String station, String line, String mainClass) {
  34. String type = ClientType.CODE;
  35. try {
  36. String body = "clientType=" + enc(type)
  37. + "&stationCode=" + enc(station)
  38. + "&lineSn=" + enc(line)
  39. + "&jarVersion=" + version()
  40. + "&configVersion=" + configVersion()
  41. + "&status=RUNNING"
  42. + "&statusMessage=" + enc("客户端运行中")
  43. + "&currentConfigJson=" + enc(readLocalConfigAsJson());
  44. HttpURLConnection c = (HttpURLConnection) new URL("http://" + serverIp + ":8980/js/a/mes/clientRuntime/heartbeat").openConnection();
  45. c.setRequestMethod("POST");
  46. c.setConnectTimeout(5000);
  47. c.setReadTimeout(10000);
  48. c.setDoOutput(true);
  49. c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
  50. byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
  51. c.setFixedLengthStreamingMode(bytes.length);
  52. try (OutputStream out = c.getOutputStream()) { out.write(bytes); }
  53. int code = c.getResponseCode();
  54. System.out.println("[ClientRuntime] heartbeat type=" + type + " code=" + code);
  55. if (code == 200) {
  56. String resp = read(c.getInputStream());
  57. System.out.println("[ClientRuntime] response=" + resp);
  58. JSONObject data = JSONObject.parseObject(resp).getJSONObject("data");
  59. if (data != null) {
  60. Long cv = data.getLong("desiredConfigVersion");
  61. String cfg = data.getString("desiredConfigJson");
  62. if (cv != null && cfg != null && !cfg.trim().isEmpty() && cv > configVersion()) {
  63. applyConfig(cv, cfg, mainClass);
  64. return; // applyConfig 会重启,不用继续处理 jar
  65. }
  66. Long jv = data.getLong("desiredJarVersion");
  67. if (jv != null && jv > version() && !updating) update(serverIp, type, jv, mainClass);
  68. }
  69. } else {
  70. System.err.println("[ClientRuntime] heartbeat rejected code=" + code);
  71. }
  72. c.disconnect();
  73. } catch (Exception e) {
  74. System.err.println("[ClientRuntime] heartbeat/update failed: " + e.getMessage());
  75. }
  76. }
  77. // 读本地 config/config.properties 转为 JSON 字符串
  78. private static String readLocalConfigAsJson() {
  79. Path p = Paths.get("config", "config.properties");
  80. if (!Files.exists(p)) return "";
  81. try {
  82. Properties props = new Properties();
  83. try (InputStream in = Files.newInputStream(p)) { props.load(in); }
  84. StringBuilder sb = new StringBuilder("{");
  85. boolean first = true;
  86. for (String key : props.stringPropertyNames()) {
  87. if (!first) sb.append(",");
  88. first = false;
  89. sb.append('"').append(esc(key)).append("\":\"").append(esc(props.getProperty(key))).append('"');
  90. }
  91. sb.append('}');
  92. return sb.toString();
  93. } catch (Exception e) {
  94. return "";
  95. }
  96. }
  97. /**
  98. * 应用服务端下发的配置:合并到 config.properties(保留未下发的 key),备份 .bak,然后重启生效。
  99. */
  100. private static void applyConfig(long ver, String cfg, String mainClass) throws Exception {
  101. JSONObject json;
  102. try { json = JSONObject.parseObject(cfg); } catch (Exception e) { System.err.println("[ClientRuntime] invalid config json"); return; }
  103. if (json == null || json.isEmpty()) return;
  104. Path dir = Paths.get("config");
  105. Files.createDirectories(dir);
  106. Path pfile = dir.resolve("config.properties");
  107. Properties props = new Properties();
  108. if (Files.exists(pfile)) {
  109. try (InputStream in = Files.newInputStream(pfile)) { props.load(in); }
  110. Files.copy(pfile, dir.resolve("config.properties.bak"), StandardCopyOption.REPLACE_EXISTING);
  111. }
  112. // 合并:JSON 里的 key 覆盖到 properties
  113. for (String key : json.keySet()) {
  114. String val = json.getString(key);
  115. if (val == null) continue;
  116. props.setProperty(key, val);
  117. }
  118. try (OutputStream out = Files.newOutputStream(pfile)) {
  119. props.store(out, "Updated by ClientRuntimeAgent " + new java.util.Date());
  120. }
  121. // 注意:config-version.txt 不在这里写,交给 restartSelf 的 vbs 在启动新 Java 前写
  122. // 这样即使 restart 失败,version 也不会被更新,下次心跳仍会触发同一个 applyConfig
  123. System.out.println("[ClientRuntime] config applied v=" + ver + ", restarting");
  124. restartSelf(mainClass, ver);
  125. }
  126. /** 触发升级:下载新 jar → 备份 → 替换 → 重启 */
  127. private static void update(String serverIp, String type, long target, String mainClass) throws Exception {
  128. updating = true;
  129. JSONObject root = JSONObject.parseObject(read(new URL("http://" + serverIp + ":8980/js/a/mes/clientVersion/ver?clientType=" + enc(type) + "&version=" + target).openStream()));
  130. JSONObject data = root.getJSONObject("data");
  131. if (data == null) throw new IOException("target version unavailable");
  132. File jar = currentJar();
  133. File download = new File(jar.getParentFile(), jar.getName() + ".download");
  134. download(data.getString("path"), download);
  135. if (download.length() == 0) throw new IOException("empty download");
  136. // 版本号不在这里写,改由 VBScript 在移动文件成功后写入,避免 VBS 失败时版本号已变
  137. File vbs = new File(jar.getParentFile(), "client-update-" + System.currentTimeMillis() + ".vbs");
  138. String jarPath = jar.getAbsolutePath();
  139. String bakPath = jarPath + ".bak";
  140. String downloadPath = download.getAbsolutePath();
  141. String libGlob = new File(jar.getParentFile(), "lib").getAbsolutePath() + File.separator + "*";
  142. String workDir = jar.getParentFile().getAbsolutePath();
  143. String verFile = new File(new File(workDir, "config"), "client-version.txt").getAbsolutePath();
  144. try (Writer w = new OutputStreamWriter(new FileOutputStream(vbs), StandardCharsets.UTF_8)) {
  145. w.write(
  146. "Set sh = CreateObject(\"WScript.Shell\")\r\n" +
  147. "Set fso = CreateObject(\"Scripting.FileSystemObject\")\r\n" +
  148. "WScript.Sleep 2000\r\n" +
  149. "If fso.FileExists(\"" + jarPath + "\") Then\r\n" +
  150. " If fso.FileExists(\"" + bakPath + "\") Then fso.DeleteFile \"" + bakPath + "\"\r\n" +
  151. " fso.MoveFile \"" + jarPath + "\", \"" + bakPath + "\"\r\n" +
  152. "End If\r\n" +
  153. "fso.MoveFile \"" + downloadPath + "\", \"" + jarPath + "\"\r\n" +
  154. "Set f = fso.CreateTextFile(\"" + verFile + "\", True)\r\n" +
  155. "f.Write \"" + target + "\"\r\n" +
  156. "f.Close\r\n" +
  157. "sh.CurrentDirectory = \"" + workDir + "\"\r\n" +
  158. "sh.Run \"javaw -cp \"\"" + jarPath + ";" + libGlob + "\"\" " + mainClass + "\", 0, False\r\n" +
  159. "fso.DeleteFile WScript.ScriptFullName\r\n"
  160. );
  161. }
  162. new ProcessBuilder("wscript.exe", vbs.getAbsolutePath()).start();
  163. System.exit(0);
  164. }
  165. /** 仅重启当前 jar,不替换文件(用于配置生效);vbs 在启动新 Java 前把 verToWrite 写入 config-version.txt */
  166. private static void restartSelf(String mainClass, long verToWrite) throws Exception {
  167. File jar = currentJar();
  168. File vbs = new File(jar.getParentFile(), "client-restart-" + System.currentTimeMillis() + ".vbs");
  169. String jarPath = jar.getAbsolutePath();
  170. String libGlob = new File(jar.getParentFile(), "lib").getAbsolutePath() + File.separator + "*";
  171. String workDir = jar.getParentFile().getAbsolutePath();
  172. String verFile = new File(new File(workDir, "config"), "config-version.txt").getAbsolutePath();
  173. try (Writer w = new OutputStreamWriter(new FileOutputStream(vbs), StandardCharsets.UTF_8)) {
  174. w.write(
  175. "Set sh = CreateObject(\"WScript.Shell\")\r\n" +
  176. "Set fso = CreateObject(\"Scripting.FileSystemObject\")\r\n" +
  177. "WScript.Sleep 2000\r\n" +
  178. "Set f = fso.CreateTextFile(\"" + verFile + "\", True)\r\n" +
  179. "f.Write \"" + verToWrite + "\"\r\n" +
  180. "f.Close\r\n" +
  181. "sh.CurrentDirectory = \"" + workDir + "\"\r\n" +
  182. "sh.Run \"javaw -cp \"\"" + jarPath + ";" + libGlob + "\"\" " + mainClass + "\", 0, False\r\n" +
  183. "fso.DeleteFile WScript.ScriptFullName\r\n"
  184. );
  185. }
  186. new ProcessBuilder("wscript.exe", vbs.getAbsolutePath()).start();
  187. System.exit(0);
  188. }
  189. private static void download(String u, File f) throws IOException {
  190. HttpURLConnection c = (HttpURLConnection) new URL(u).openConnection();
  191. c.setConnectTimeout(10000);
  192. c.setReadTimeout(120000);
  193. if (c.getResponseCode() != 200) throw new IOException("download failed");
  194. try (InputStream in = c.getInputStream(); OutputStream out = new FileOutputStream(f)) {
  195. byte[] b = new byte[8192];
  196. int n;
  197. while ((n = in.read(b)) != -1) out.write(b, 0, n);
  198. } finally { c.disconnect(); }
  199. }
  200. private static File currentJar() throws Exception {
  201. File f = new File(ClientRuntimeAgent.class.getProtectionDomain().getCodeSource().getLocation().toURI());
  202. if (!f.isFile()) throw new IOException("not running from jar");
  203. return f;
  204. }
  205. private static long version() { return readLong("client-version.txt", 1); }
  206. private static long configVersion() { return readLong("config-version.txt", 0); }
  207. private static long readLong(String n, long d) {
  208. try { return Long.parseLong(new String(Files.readAllBytes(Paths.get("config", n)), StandardCharsets.UTF_8).trim()); }
  209. catch (Exception e) { return d; }
  210. }
  211. private static String enc(String s) {
  212. try { return URLEncoder.encode(s == null ? "" : s, "UTF-8"); } catch (Exception e) { return ""; }
  213. }
  214. private static String esc(String s) {
  215. if (s == null) return "";
  216. return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t");
  217. }
  218. private static String read(InputStream in) throws IOException {
  219. try (BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
  220. StringBuilder b = new StringBuilder();
  221. String l;
  222. while ((l = r.readLine()) != null) b.append(l);
  223. return b.toString();
  224. }
  225. }
  226. }