Browse Source

增加历史策略包清理和node、策略日志清理

JiahengHe 3 months ago
parent
commit
f7184c69d9
4 changed files with 89 additions and 37 deletions
  1. 20 13
      src/Interval.js
  2. 45 14
      src/robot.js
  3. 15 1
      src/utils/file.js
  4. 9 9
      src/web.js

+ 20 - 13
src/Interval.js

@@ -1,7 +1,7 @@
 const robot = require('./robot')
 const web = require('./web')
 const {logger} = require("./utils/logger");
-const {tr} = require("date-fns/locale");
+// const {tr} = require("date-fns/locale");
 const path = require("path");
 const file = require("./utils/file");
 const {getRustConfig} = require("./config");
@@ -13,7 +13,7 @@ const http = require("./utils/http");
  * **** */
 function init() {
     // reportNodeStatus()
-    reportDel()
+    reportDeleteLog()
     reportSearchPositions()
     reportAmount()
     cacheLogs()
@@ -30,17 +30,22 @@ function reportNodeStatus() {
 }
 
 
-//定时清理机器人
-function reportDel() {
-    const intervalInMilliseconds = 1000 * 5;
+//定时清理日志(每12小时执行一次)
+function reportDeleteLog() {
+    const intervalInMilliseconds = 1000 * 60 * 60 * 12;
     setInterval(() => {
-        // logger.info('当前1',robot.appMap);
+        logger.info('清理日志开始执行!');
+        // 清理node日志
+        robot.delNodeLog()
+        logger.info('清理node日志结束!');
+        // 清理机器人日志
         robot.appMap.forEach((value, key) => {
             if (value.id !== -1) {
-                // logger.info(`清理没用机器人开始111!`,value);
-                robot.delRobot(value)
+                // logger.info(`清理机器人日志开始!`,value);
+                robot.delRobotLog(value)
             }
         });
+        logger.info('清理机器人日志结束!');
     }, intervalInMilliseconds);
 }
 
@@ -100,7 +105,7 @@ function cacheLogs() {
     setInterval(() => {
         // logger.info('当前2',robot.appMap);
         robot.appMap.forEach((value, key) => {
-            var thisTime = new Date().getTime()
+            // var thisTime = new Date().getTime()
             let port = value.port
             let n = 200
             let messlist = value.messlist
@@ -145,7 +150,7 @@ function cachePredictorState() {
         // logger.info('当前2',robot.appMap);
         var config = getRustConfig()
         robot.appMap.forEach((value, key) => {
-            var thisTime = new Date().getTime()
+            // var thisTime = new Date().getTime()
             let port = value.port
             let predictorState = value.predictorState
             if (value.id !== -1 && port !== -1 && value.threadStatus === robot.RobotStatus.RUNNING) {
@@ -156,10 +161,12 @@ function cachePredictorState() {
                 var accUrl = "http://127.0.0.1:" + port
                 http.request_get_timeout(`${accUrl}/predictor_state`, {...config.headers})
                     .then((data) => {
-                        if (data.length < 50) {
-                            logger.info(`可能出错的data~~: ${data}`)
+                        if (data.length > 0){
+                            if (data.length < 50) {
+                                logger.info(`可能出错的data~~: ${data}`)
+                            }
+                            value.predictorState = JSON.parse(data)
                         }
-                        value.predictorState = JSON.parse(data)
                     }).catch((error) => {
                     logger.info(`异步缓存predictorState异常~~ ${error.message}`)
                 });

+ 45 - 14
src/robot.js

@@ -1,10 +1,10 @@
 const file = require("./utils/file");
 const {getRustConfig} = require("./config");
-const {spawn, exec, fork, execSync} = require("child_process");
+const {spawn, exec, execSync} = require("child_process");
 const {logger} = require("./utils/logger");
 const http = require("./utils/http");
-const e = require("express");
-const {is, tr} = require("date-fns/locale");
+// const e = require("express");
+// const {is, tr} = require("date-fns/locale");
 /*******
  * web
  * **** */
@@ -106,7 +106,22 @@ async function run(param) {
         //相对路径存放
         appPath = config.filePath + "/" + app.id + "/" + strategyName + "/" + programName
         //1. 检查目录
-        file.checkPathSync(appPath);
+        let is_exist = file.checkFilePath(appPath)
+        // 目录不存在即是新策略,创建前清理机器人下不用的策略包
+        if (!is_exist){
+            // 清理该机器人下历史的策略包 sudo find ~/4l_capital_central_control_client/rust/203 -mindepth 1 -delete
+            let clear_command = `sudo find ` + config.filePath + "/" + app.id + ` -mindepth 1 -delete`
+            exec(clear_command, (error, stdout, stderr) => {
+                if (error) {
+                    logger.error(`清理不用的策略文件:清理失败: ${error}`);
+                }
+            });
+            // 时间给到文件清理
+            await delay(1000);
+            // 同步创建目录
+            file.mkdir(appPath);
+        }
+
 
         /****
          *** 第三步:rust 启动程序检查(下载更新)
@@ -117,11 +132,14 @@ async function run(param) {
         var scheduleConfig = 0
         //2、 检查执行程序
         var destination = appPath + "/" + exeName
-        if (!file.checkFilePath(destination)) {
+        // 确认路径是否存在
+        let is_program_exist = file.checkFilePath(destination);
+        if (!is_program_exist) {
             app.threadStatus = RobotStatus.DOWNLOADING
             robotStatus(app)
             isDow = true
             var dowHeaders = {...config.headers};
+
             if (platform === 'win32') {
                 downloadFileWithPowerShell(
                     config.baseUrl + config.dowAppURL + '/?path=' + appName,
@@ -248,7 +266,7 @@ async function run(param) {
         //3. spawn启动
         const exePath = appPath + "/" + exeName
         const configPath = appPath + "/" + configName
-        logger.info(`文件地址:${exePath}-----${configPath}`);
+        // logger.info(`文件地址:${exePath}-----${configPath}`);
         const command = exePath
         const args = ['--config=' + configPath, '--port=' + app.port]
         app.childProcess = spawn(command, args)
@@ -543,13 +561,25 @@ function robotAmount(app) {
     }
 }
 
-// 定时清理停止状态的 机器人
-function delRobot(app) {
-    // const platform = process.platform;
-    // if (platform !== 'win32' && app.threadStatus === RobotStatus.STOPPED) {
-    //     var pid = app.childProcess.pid
-    //     delApp(app.id)
-    // }
+// 定时清理机器人日志
+function delRobotLog(app) {
+    // 组装日志删除命令(最后修改时间在3天前的)
+    let deleteLogCommand = `sudo find logs` + app.port + ` -type f -mtime +3 -exec rm {} \\;`;
+    exec(deleteLogCommand, (error, stdout, stderr) => {
+        if (error) {
+            logger.error(`清理机器人日志命令执行失败~: ${deleteLogCommand} 错误:${error}`);
+        }
+    });
+}
+
+function delNodeLog() {
+    // 组装日志删除命令(最后修改时间在3天前的)
+    let deleteLogCommand = `sudo find logs/node -type f -mtime +3 -exec rm {} \\;`;
+    exec(deleteLogCommand, (error, stdout, stderr) => {
+        if (error) {
+            logger.error(`清理node日志命令执行失败~:错误:${error}`);
+        }
+    });
 }
 
 //----------------------------------------------
@@ -559,7 +589,8 @@ module.exports = {
     run,
     closeApp,
     restartApp,
-    delRobot,
+    delRobotLog,
+    delNodeLog,
     robotStatus,
     robotAmount,
     closeAppAll,

+ 15 - 1
src/utils/file.js

@@ -1,7 +1,7 @@
 const fs = require('fs');
 const path = require('path');
 const {logger} = require("./logger");
-const {rustConfig} = require("../config");
+// const {rustConfig} = require("../config");
 const http = require("./http");
 const readline = require('readline');
 
@@ -30,6 +30,19 @@ function checkPathSync(filePath) {
     return true
 }
 
+// 创建文件夹
+function mkdir(filePath){
+    const directoryPath = path.resolve(filePath);
+    try {
+        // 同步创建目录
+        fs.mkdirSync(directoryPath, {recursive: true});
+        logger.info('目录已成功创建 38');
+    } catch (error) {
+        // 创建目录失败
+        logger.error('38 创建目录失败:', error);
+    }
+}
+
 // 检查文件是否存在
 function checkFilePath(filePath) {
     // 同步检查文件是否存在
@@ -459,6 +472,7 @@ async function readLines(filePath, maxLines) {
 
 module.exports = {
     dowFile,
+    mkdir,
     checkFilePath,
     checkPathSync,
     writeFile,

+ 9 - 9
src/web.js

@@ -2,15 +2,15 @@ const express = require('express');
 const robot = require('./robot')
 const {getRustConfig} = require('./config')
 const http = require("./utils/http");
-const file = require('./utils/file')
-const {logger, fileLogger} = require("./utils/logger");
-const {spawn, exec, fork, execSync} = require("child_process");
-const path = require("path");
+// const file = require('./utils/file')
+const {logger} = require("./utils/logger");
+// const {spawn, exec, fork, execSync} = require("child_process");
+// const path = require("path");
 
-const {ka, tr} = require("date-fns/locale");
-const {getAppMap} = require("./robot");
+// const {ka, tr} = require("date-fns/locale");
+// const {getAppMap} = require("./robot");
 const crypto = require('crypto');
-const fs = require("fs");
+// const fs = require("fs");
 
 /*******
  * web
@@ -28,7 +28,7 @@ function init() {
             var md5 = req.headers.catilla
             //默认32位
             const md5Str = crypto.createHash('md5').update(k + timestamp).digest('hex');
-            logger.info(JSON.stringify(md5Str)+'\t'+req.url)
+            // logger.info(JSON.stringify(md5Str)+'\t'+req.url)
             if (md5 === md5Str) {
                 next();
             } else {
@@ -139,7 +139,7 @@ function init() {
     //启动-仓位检查
     app.get('/searchPositions', (req, res) => {
         const param = req.query;
-        logger.info(JSON.stringify(param));
+        // logger.info(JSON.stringify(param));
         robot.searchPositions(param)
         res.send({'code': 200, 'data': true, "message": "SUCCESS"});
     })