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 = -1;
  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, 500, async (fileNameList, _) => {
  86. // logger.info('文件:', fileNameList);
  87. result = await file.readLastNLines(logPath, fileNameList, n);
  88. // logger.info('?????:', result);
  89. res.send({'code': 200, 'data': result, "message": "SUCCESS"});
  90. });
  91. } catch (e) {
  92. logger.info('获取日志异常了~~', e);
  93. res.send({'code': 200, 'data': [], "message": "SUCCESS"});
  94. }
  95. } else {
  96. res.send({'code': 200, 'data': result, "message": "SUCCESS"});
  97. }
  98. });
  99. app.post('/execute', (req, res) => {
  100. // 获取发送过来的信息(请求体的数据)
  101. const param = req.body;
  102. // logger.info('--web 启动',param);
  103. (async (param) => {
  104. // logger.info('请求体:', );
  105. var executeType = param.executeType
  106. if (executeType === "RUN") {
  107. await robot.run(param)
  108. } else if (executeType === "STOP") {
  109. await robot.closeApp(param)
  110. } else if (executeType === "RESTART") {
  111. await robot.restartApp(param)
  112. }
  113. })(param);
  114. // 回应信号(响应请求)
  115. res.send({'code': 200, 'data': "null", "message": "SUCCESS"});
  116. })
  117. //启动-仓位检查
  118. app.get('/searchPositions', (req, res) => {
  119. const param = req.query;
  120. logger.info(JSON.stringify(param));
  121. robot.searchPositions(param)
  122. res.send({'code': 200, 'data': true, "message": "SUCCESS"});
  123. })
  124. // 新策略-返回机器人状态
  125. app.get('/predictorState', (req, res) => {
  126. const param = req.query;
  127. logger.info(JSON.stringify(param));
  128. var id = param.id;
  129. var port = -1;
  130. robot.appMap.forEach((value, key) => {
  131. // logger.info(JSON.stringify(value))
  132. if (value.id + "" === id + "") {
  133. port = value.port
  134. }
  135. })
  136. if (port !== -1) {
  137. logger.info('#####################predictorState:');
  138. var config = getRustConfig()
  139. var com = `curl -X GET -H "auth: 4L" -H "token: r7T$8gBV!f&L@E2+" "http://127.0.0.1:${port}/predictor_state"`;
  140. logger.info('#####################com:', com);
  141. execSync(com, (error, stdout, stderr) => {
  142. if (error) {
  143. logger.info(`#####################汇报:获取状态请求失败: ${error.message}`)
  144. res.send({'code': -1, 'data': null, "message": `获取状态请求失败`});
  145. }
  146. logger.info('#####################-d', stdout);
  147. logger.info('#####################-ok');
  148. res.send({'code': 200, 'data': stdout, "message": "SUCCESS"});
  149. });
  150. } else {
  151. res.send({'code': -1, 'data': null, "message": "机器人不存在"});
  152. }
  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. };