web.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. const express = require('express');
  2. const robot = require('./robot')
  3. const {getRustConfig} = require('./config')
  4. const http = require("./utils/http");
  5. const file = require('./utils/file')
  6. const {logger, fileLogger} = require("./utils/logger");
  7. const {spawn, exec, fork, execSync} = require("child_process");
  8. const path = require("path");
  9. const {ka, tr} = require("date-fns/locale");
  10. const {getAppMap} = require("./robot");
  11. const crypto = require('crypto');
  12. const fs = require("fs");
  13. /*******
  14. * web
  15. * **** */
  16. function init() {
  17. const app = express();
  18. const port = 3000;
  19. // 中间件示例,用于处理JSON请求体
  20. app.use(express.json());
  21. app.use((req, res, next) => {
  22. var k = "$8gBV!f&L@E"
  23. if ("timestamp" in req.headers) {
  24. var timestamp = req.headers.timestamp
  25. var md5 = req.headers.catilla
  26. //默认32位
  27. const md5Str = crypto.createHash('md5').update(k + timestamp).digest('hex');
  28. logger.info(JSON.stringify(md5Str))
  29. if (md5 === md5Str) {
  30. next();
  31. } else {
  32. res.status(403).send('拒绝访问!');
  33. }
  34. } else {
  35. res.status(403).send('没有访问权限!');
  36. }
  37. });
  38. // GET请求的路由示例
  39. app.get('/', (req, res) => {
  40. res.send('is OK!');
  41. });
  42. app.get('/robotList', (req, res) => {
  43. var map = robot.getAppMap()
  44. var list = new Array();
  45. robot.appMap.forEach((value, key) => {
  46. // str.set(key,JSON.stringify(value))
  47. list.push({
  48. id: value.id,
  49. nowBalance: value.nowBalance + "",
  50. posNum: value.posNum + "",
  51. messlist: value.messlist,
  52. threadStatus: value.threadStatus,
  53. errorMessage: value.errorMessage,
  54. threadStartTime: value.threadStartTime,
  55. status: value.status,
  56. restartStatus: value.restartStatus
  57. })
  58. })
  59. res.send({'code': 200, 'data': JSON.stringify(list), "message": "SUCCESS"});
  60. });
  61. //简单三个接口,为了方便使用get请求
  62. app.get('/isOK', (req, res) => {
  63. res.send({'code': 200, 'data': true, "message": "SUCCESS"});
  64. });
  65. app.get('/logs', (req, res) => {
  66. // 获取发送过来的信息(请求体的数据)
  67. const param = req.query;
  68. const n = param.n
  69. const id = param.id
  70. var port = 1111;
  71. robot.appMap.forEach((value, key) => {
  72. // logger.info(JSON.stringify(value))
  73. if (value.id + "" === id + "") {
  74. port = value.port
  75. }
  76. })
  77. let result = [];
  78. if (port !== -1) {
  79. var logPath = "./logs" + port
  80. logger.info(`访问-日志相对目录:${logPath}`)
  81. // 将相对路径转换为绝对路径
  82. const directoryPath = path.resolve(logPath);
  83. try {
  84. file.checkPathSync(directoryPath)
  85. file.getLastFile(logPath, 5, async (fileNameList, _) => {
  86. // logger.info('cccccccccccccc文件:', fileNameList);
  87. // result = await file.readLastNLines(logPath, fileNameList, n);
  88. result = await file.getRecentLogs(logPath,fileNameList.reverse(),n);
  89. // logger.info('?????:', result);
  90. res.send({'code': 200, 'data': result, "message": "SUCCESS"});
  91. });
  92. } catch (e) {
  93. logger.info('获取日志异常了~~', e);
  94. res.send({'code': 200, 'data': [], "message": "SUCCESS"});
  95. }
  96. } else {
  97. res.send({'code': 200, 'data': result, "message": "SUCCESS"});
  98. }
  99. });
  100. app.post('/execute', (req, res) => {
  101. // 获取发送过来的信息(请求体的数据)
  102. const param = req.body;
  103. // logger.info('--web 启动',param);
  104. (async (param) => {
  105. // logger.info('请求体:', );
  106. var executeType = param.executeType
  107. if (executeType === "RUN") {
  108. await robot.run(param)
  109. } else if (executeType === "STOP") {
  110. await robot.closeApp(param)
  111. } else if (executeType === "RESTART") {
  112. await robot.restartApp(param)
  113. }
  114. })(param);
  115. // 回应信号(响应请求)
  116. res.send({'code': 200, 'data': "null", "message": "SUCCESS"});
  117. })
  118. //启动-仓位检查
  119. app.get('/searchPositions', (req, res) => {
  120. const param = req.query;
  121. logger.info(JSON.stringify(param));
  122. robot.searchPositions(param)
  123. res.send({'code': 200, 'data': true, "message": "SUCCESS"});
  124. })
  125. // 新策略-返回机器人状态
  126. app.get('/predictorState', (req, res) => {
  127. // const param = req.query;
  128. // logger.info(JSON.stringify(param));
  129. // let data = robot.predictorState(param)
  130. // res.send(data);
  131. const param = req.query;
  132. const id = param.id
  133. var port = -1;
  134. robot.appMap.forEach((value, key) => {
  135. // logger.info(JSON.stringify(value))
  136. if (value.id + "" === id + "") {
  137. port = value.port
  138. }
  139. })
  140. var accUrl = "http://127.0.0.1:" + port
  141. var config = getRustConfig()
  142. logger.info(`#####################开始:`)
  143. http.request_get(`${accUrl}/predictor_state`, {...config.headers})
  144. .then((data) => {
  145. // logger.info(`#####################返回数据:`,data)
  146. res.send({'code': 200, 'data': JSON.parse(data), "message": "SUCCESS"});
  147. }).catch((error) => {
  148. // 处理可能发生的错误
  149. logger.info(`#####################汇报:获取状态请求失败: ${error.message}`)
  150. res.send({'code': -1, 'data': null, "message": `获取状态请求失败${error.message}`});
  151. });
  152. logger.info(`#####################最后:`)
  153. })
  154. // 使服务器监听特定端口
  155. app.listen(port, () => {
  156. // console.log(`服务器正在监听 http://localhost:${port}`);
  157. });
  158. logger.info('--web 启动');
  159. }
  160. // node-已上线-上报
  161. function robotNodeStatus() {
  162. var config = getRustConfig()
  163. http.request_post(`${config.reportedUrl}/report/beOnline`, {}, {...config.headers}).then((data) => {
  164. // logger.info('??', data);
  165. logger.info('#####################汇报:node 在线-上报成功!', data);
  166. }).catch((error) => {
  167. logger.error(`node 在线!-上报失败: ${error.message}`); // 处理可能发生的错误
  168. });
  169. }
  170. function isOK(req, res) {
  171. res.send({'code': 200, 'data': "null", "message": "SUCCESS"});
  172. }
  173. // 日志读取操作
  174. module.exports = {
  175. init,
  176. robotNodeStatus
  177. };