gaoshuaixing 1 year ago
parent
commit
7a1b6af8b5

+ 0 - 93
electron/addon/javaServer/index.js

@@ -1,93 +0,0 @@
-const server = require("./server");
-const { app: electronApp } = require('electron');
-const Log = require('ee-core/log');
-const Conf = require('ee-core/config');
-const GetPort = require('ee-core/utils/get-port');
-
-/**
- * java server插件
- * @class
- */
-class JavaServerAddon {
-
-  constructor() {
-    this.cfg;
-    this.javaServer;
-  }
-
-  /**
-   * 创建java服务
-   *
-   * @function 
-   * @since 1.0.0
-   */
-  async createServer () {
-
-    this.cfg = Conf.getValue('addons.javaServer');
-    await this.createJavaPorts();
-
-    this.javaServer = new server();
-    await this.javaServer.create(this.cfg);
-
-    // kill
-    electronApp.on("before-quit", async () => {
-      Log.info("[addon:javaServer] before-quit: kill-----------");
-      await this.javaServer.kill();
-    });
-
-    return;
-  }
-
-  /**
-   * todo 检查服务是否启动
-   *
-   * @function 
-   * @since 1.0.0
-   */
-  async check () {
-    Log.info("进入-----检查服务是否启动------"+this.javaServer);
-    if(this.javaServer == undefined){
-      Log.info("[addon:javaServer:check] status-----------"+false);
-      return false;
-    }
-    
-    const flag = await this.javaServer.isRun(Conf.getValue('addons.javaServer'));
-    Log.info("[addon:javaServer:check] status-----------"+flag);
-
-    return flag;    
-  }
-
-  /**
-   * 创建服务端口
-   *
-   * @function 
-   * @since 1.0.0
-   */
-  async createJavaPorts() {
-    if (!this.cfg.enable) {
-      return;
-    }
-    const javaPort = await GetPort({ port: this.cfg.port });
-    process.env.EE_JAVA_PORT = javaPort;
-    this.cfg.port = javaPort;
-
-    // 更新config配置
-    Conf.setValue('addons.javaServer', this.cfg);
-  }
-
-  /**
-   * 杀掉进程
-   *
-   * @function 
-   * @since 1.0.0
-   */
-  async kill() {
-    if (!this.cfg.enable) {
-      return;
-    }
-    await this.javaServer.kill();
-  }
-}
-
-JavaServerAddon.toString = () => '[class JavaServerAddon]';
-module.exports = JavaServerAddon;

+ 0 - 257
electron/addon/javaServer/ps.js

@@ -1,257 +0,0 @@
-var ChildProcess = require("child_process");
-var IS_WIN = process.platform === "win32";
-var TableParser = require("table-parser");
-/**
- * End of line.
- * Basically, the EOL should be:
- * - windows: \r\n
- * - *nix: \n
- * But i'm trying to get every possibilities covered.
- */
-var EOL = /(\r\n)|(\n\r)|\n|\r/;
-var SystemEOL = require("os").EOL;
-
-/**
- * Execute child process
- * @type {Function}
- * @param {String[]} args
- * @param {String} where
- * @param {Function} callback
- * @param {Object=null} callback.err
- * @param {Object[]} callback.stdout
- */
-var Exec = function (args, where) {
-  var spawnSync = ChildProcess.spawnSync;
-  var execSync = ChildProcess.execSync;
-
-  // on windows, if use ChildProcess.exec(`wmic process get`), the stdout will gives you nothing
-  // that's why I use `cmd` instead
-  if (IS_WIN) {
-    const cmd = `wmic process where ${where} get ProcessId,ParentProcessId,CommandLine \n`;
-    const result = execSync(cmd);
-    if (!result) {
-      throw new Error(result);
-    }
-
-    var stdout = result.toString();
-
-    var beginRow;
-    stdout = stdout.split(EOL);
-
-    // Find the line index for the titles
-    stdout.forEach(function (out, index) {
-      if (
-        out &&
-        typeof beginRow == "undefined" &&
-        out.indexOf("CommandLine") === 0
-      ) {
-        beginRow = index;
-      }
-    });
-
-    // get rid of the start (copyright) and the end (current pwd)
-    stdout.splice(stdout.length - 1, 1);
-    stdout.splice(0, beginRow);
-
-    return stdout.join(SystemEOL) || false;
-  } else {
-    if (typeof args === "string") {
-      args = args.split(/\s+/);
-    }
-    const result = spawnSync("ps", args);
-    if (result.stderr && !!result.stderr.toString()) {
-      throw new Error(result.stderr);
-    } else {
-      return result.stdout.toString();
-    }
-  }
-};
-
-/**
- * Query Process: Focus on pid & cmd
- * @param query
- * @param {String|String[]} query.pid
- * @param {String} query.command RegExp String
- * @param {String} query.arguments RegExp String
- * @param {String|array} query.psargs
- * @param {String|array} query.where where 条件
- * @param {Function} callback
- * @param {Object=null} callback.err
- * @param {Object[]} callback.processList
- * @return {Object}
- */
-
-exports.lookup = function (query) {
-  /**
-   * add 'lx' as default ps arguments, since the default ps output in linux like "ubuntu", wont include command arguments
-   */
-  var exeArgs = query.psargs || ["lx"];
-  var where = query.where || 'name="javaw.exe"';
-  var filter = {};
-  var idList;
-
-  // Lookup by PID
-  if (query.pid) {
-    if (Array.isArray(query.pid)) {
-      idList = query.pid;
-    } else {
-      idList = [query.pid];
-    }
-
-    // Cast all PIDs as Strings
-    idList = idList.map(function (v) {
-      return String(v);
-    });
-  }
-
-  if (query.command) {
-    filter["command"] = new RegExp(query.command, "i");
-  }
-
-  if (query.arguments) {
-    filter["arguments"] = new RegExp(query.arguments, "i");
-  }
-
-  if (query.ppid) {
-    filter["ppid"] = new RegExp(query.ppid);
-  }
-
-  const result = Exec(exeArgs, where);
-
-  var processList = parseGrid(result);
-  var resultList = [];
-
-  processList.forEach(function (p) {
-    var flt;
-    var type;
-    var result = true;
-
-    if (idList && idList.indexOf(String(p.pid)) < 0) {
-      return;
-    }
-
-    for (type in filter) {
-      flt = filter[type];
-      result = flt.test(p[type]) ? result : false;
-    }
-
-    if (result) {
-      resultList.push(p);
-    }
-  });
-
-  return resultList;
-};
-
-/**
- * Kill process
- * @param pid
- * @param {Object|String} signal
- * @param {String} signal.signal
- * @param {number} signal.timeout
- * @param next
- */
-
-exports.kill = function (pid, signal, next) {
-  //opts are optional
-  if (arguments.length == 2 && typeof signal == "function") {
-    next = signal;
-    signal = undefined;
-  }
-
-  var checkTimeoutSeconds = (signal && signal.timeout) || 30;
-
-  if (typeof signal === "object") {
-    signal = signal.signal;
-  }
-
-  try {
-    process.kill(pid, signal);
-  } catch (e) {
-    return next && next(e);
-  }
-
-  var checkConfident = 0;
-  var checkTimeoutTimer = null;
-  var checkIsTimeout = false;
-
-  function checkKilled(finishCallback) {
-    exports.lookup({ pid: pid }, function (err, list) {
-      if (checkIsTimeout) return;
-
-      if (err) {
-        clearTimeout(checkTimeoutTimer);
-        finishCallback && finishCallback(err);
-      } else if (list.length > 0) {
-        checkConfident = checkConfident - 1 || 0;
-        checkKilled(finishCallback);
-      } else {
-        checkConfident++;
-        if (checkConfident === 5) {
-          clearTimeout(checkTimeoutTimer);
-          finishCallback && finishCallback();
-        } else {
-          checkKilled(finishCallback);
-        }
-      }
-    });
-  }
-
-  next && checkKilled(next);
-
-  checkTimeoutTimer =
-    next &&
-    setTimeout(function () {
-      checkIsTimeout = true;
-      next(new Error("Kill process timeout"));
-    }, checkTimeoutSeconds * 1000);
-};
-
-/**
- * Parse the stdout into readable object.
- * @param {String} output
- */
-
-function parseGrid(output) {
-  if (!output) {
-    return [];
-  }
-  return formatOutput(TableParser.parse(output));
-}
-
-/**
- * format the structure, extract pid, command, arguments, ppid
- * @param data
- * @return {Array}
- */
-
-function formatOutput(data) {
-  var formatedData = [];
-  data.forEach(function (d) {
-    var pid =
-      (d.PID && d.PID[0]) || (d.ProcessId && d.ProcessId[0]) || undefined;
-    var cmd = d.CMD || d.CommandLine || d.COMMAND || undefined;
-    var ppid =
-      (d.PPID && d.PPID[0]) ||
-      (d.ParentProcessId && d.ParentProcessId[0]) ||
-      undefined;
-
-    if (pid && cmd) {
-      var command = cmd[0];
-      var args = "";
-
-      if (cmd.length > 1) {
-        args = cmd.slice(1);
-      }
-
-      formatedData.push({
-        pid: pid,
-        command: command,
-        arguments: args,
-        ppid: ppid,
-      });
-    }
-  });
-
-  return formatedData;
-}

+ 0 - 126
electron/addon/javaServer/server.js

@@ -1,126 +0,0 @@
-const _ = require("lodash");
-const assert = require("assert");
-const fs = require("fs");
-const path = require("path");
-const { exec, execSync } = require("child_process");
-const ps = require("./ps");
-const Log = require('ee-core/log');
-const is = require('ee-core/utils/is');
-const UtilsPs = require('ee-core/ps');
-
-/**
- * java server
- */
-class JavaServer {
-  constructor () {
-    this.options;
-  }
-
-  /**
-   * 创建服务
-   */
-  async create (cfg) {
-    this.options = cfg;
-    if (this.options.enable == false) {
-      return;
-    }
-  
-    let port = process.env.EE_JAVA_PORT ? parseInt(process.env.EE_JAVA_PORT) : parseInt(this.options.port);
-    assert(typeof port === "number", "java port required, and must be a number");
-  
-    try {
-      const jarName = this.options.name;
-      let softwarePath = path.join(UtilsPs.getExtraResourcesDir(), jarName);
-      let javaOptStr = this.options.opt;
-      let jrePath = path.join(UtilsPs.getExtraResourcesDir(), this.options.jreVersion);
-      let cmdStr = '';
-      
-      Log.info("[addon:javaServer] jar file path:", softwarePath); 
-      if (!fs.existsSync(softwarePath)) throw new Error('java program does not exist');
-
-      // 替换opt参数
-      javaOptStr = _.replace(javaOptStr, "${port}", port);
-      javaOptStr = _.replace(javaOptStr, "${path}", UtilsPs.getLogDir());
-
-      if (is.windows()) {
-        jrePath = path.join(jrePath, "bin", "javaw.exe");
-        cmdStr = `start ${jrePath} -jar ${javaOptStr} ${softwarePath}`;
-      } else if (is.macOS()) {
-        // 如果提示:不受信任,请执行:  sudo spctl --master-disable
-        jrePath = path.join(jrePath, "Contents", "Home", "bin", "java");
-        //cmdStr = `nohup ${jrePath} -jar ${javaOptStr} ${softwarePath} >/dev/null 2>&1 &`;
-        cmdStr = `${jrePath} -jar ${javaOptStr} ${softwarePath}`;
-      } else {
-        // todo linux
-      }
-
-      Log.info("[addon:javaServer] cmdStr:", cmdStr);
-      exec(cmdStr);
-
-    } catch (err) {
-      Log.error('[addon:javaServer] throw error:', err);
-    }
-  }
-
-  /**
-   * 关闭服务
-   */
-  async kill () {
-    const jarName = this.options.name;
-    if (is.windows()) {
-      const resultList = ps.lookup({
-        command: "java",
-        where: 'caption="javaw.exe"',
-        arguments: jarName,
-      });
-  
-      //Log.info("[addon:javaServer] resultList:", resultList);
-      resultList.forEach((item) => {
-        ps.kill(item.pid, "SIGKILL", (err) => {
-          if (err) {
-            throw new Error(err);
-          }
-          Log.info("[addon:javaServer] java程序退出 pid: ", item.pid);
-        });
-      });
-  
-      //   const cmd = `for /f "tokens=1-5" %i in ('netstat -ano ^| findstr ":${port}"') do taskkill /F /T /PID %m`;
-      //   const a = await execSync(cmd, {encoding: 'utf-8'});
-      //   Log.info("[javaServer] kill:", a);
-    } else if (is.macOS()) {
-      const cmd = `ps -ef | grep java | grep ${jarName} | grep -v grep | awk '{print $2}' | xargs kill -9`;
-      const result = await execSync(cmd);
-      Log.info("[addon:javaServer] kill:", result != null ? result.toString(): '');
-    } else {
-      // todo linux
-    }
-  }
-
-  /**
-   * 服务是否运行中
-   */
-  async isRun(cfg){
-    const jarName = cfg.name;
-    if (is.windows()) {
-      const resultList = ps.lookup({
-        command: "java",
-        where: 'caption="javaw.exe"',
-        arguments: jarName,
-      });
-  
-      Log.info("[addon:javaServer] resultList:", resultList);
-      return resultList.length>0;
-    } else if (is.macOS()) {
-      const cmd = `ps -ef | grep java | grep ${jarName} | grep -v grep | awk '{print $2}' `;
-      Log.info("[addon:javaServer:isRun] cmdStr:", cmd);
-      const result = execSync(cmd);
-      Log.info('[addon:javaServer:isRun] result:', result.toString());
-      //不等于空说明正在运行
-      return result.toString()!==""
-    } else {
-      // todo linux
-    }
-  }  
-}
-
-module.exports = JavaServer;

+ 2 - 2
package.json

@@ -1,6 +1,6 @@
 {
   "name": "ee",
-  "version": "3.9.0",
+  "version": "3.10.0",
   "description": "A fast, desktop software development framework",
   "main": "main.js",
   "scripts": {
@@ -55,7 +55,7 @@
   },
   "dependencies": {
     "dayjs": "^1.10.7",
-    "ee-core": "^2.7.0",
+    "ee-core": "^2.8.0",
     "electron-updater": "^5.3.0",
     "lodash": "^4.17.21"
   }