123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195 |
- 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 {ka, tr} = require("date-fns/locale");
- const {getAppMap} = require("./robot");
- const crypto = require('crypto');
- const fs = require("fs");
- /*******
- * web
- * **** */
- function init() {
- const app = express();
- const port = 3000;
- // 中间件示例,用于处理JSON请求体
- app.use(express.json());
- app.use((req, res, next) => {
- var k = "$8gBV!f&L@E"
- if ("timestamp" in req.headers) {
- var timestamp = req.headers.timestamp
- var md5 = req.headers.catilla
- //默认32位
- const md5Str = crypto.createHash('md5').update(k + timestamp).digest('hex');
- logger.info(JSON.stringify(md5Str))
- if (md5 === md5Str) {
- next();
- } else {
- res.status(403).send('拒绝访问!');
- }
- } else {
- res.status(403).send('没有访问权限!');
- }
- });
- // GET请求的路由示例
- app.get('/', (req, res) => {
- res.send('is OK!');
- });
- app.get('/robotList', (req, res) => {
- var map = robot.getAppMap()
- var list = new Array();
- robot.appMap.forEach((value, key) => {
- // str.set(key,JSON.stringify(value))
- list.push({
- id: value.id,
- nowBalance: value.nowBalance + "",
- posNum: value.posNum + "",
- messlist: value.messlist,
- threadStatus: value.threadStatus,
- errorMessage: value.errorMessage,
- threadStartTime: value.threadStartTime,
- status: value.status,
- restartStatus: value.restartStatus
- })
- })
- res.send({'code': 200, 'data': JSON.stringify(list), "message": "SUCCESS"});
- });
- //简单三个接口,为了方便使用get请求
- app.get('/isOK', (req, res) => {
- res.send({'code': 200, 'data': true, "message": "SUCCESS"});
- });
- app.get('/logs', (req, res) => {
- // 获取发送过来的信息(请求体的数据)
- const param = req.query;
- const n = param.n
- const id = param.id
- var port = -1;
- robot.appMap.forEach((value, key) => {
- // logger.info(JSON.stringify(value))
- if (value.id + "" === id + "") {
- port = value.port
- }
- })
- let result = [];
- if (port !== -1) {
- var logPath = "./logs" + port
- logger.info(`访问-日志相对目录:${logPath}`)
- // 将相对路径转换为绝对路径
- const directoryPath = path.resolve(logPath);
- try {
- file.checkPathSync(directoryPath)
- file.getLastFile(logPath, 500, async (fileNameList, _) => {
- // logger.info('文件:', fileNameList);
- result = await file.readLastNLines(logPath, fileNameList, n);
- // logger.info('?????:', result);
- res.send({'code': 200, 'data': result, "message": "SUCCESS"});
- });
- } catch (e) {
- logger.info('获取日志异常了~~', e);
- res.send({'code': 200, 'data': [], "message": "SUCCESS"});
- }
- } else {
- res.send({'code': 200, 'data': result, "message": "SUCCESS"});
- }
- });
- app.post('/execute', (req, res) => {
- // 获取发送过来的信息(请求体的数据)
- const param = req.body;
- // logger.info('--web 启动',param);
- (async (param) => {
- // logger.info('请求体:', );
- var executeType = param.executeType
- if (executeType === "RUN") {
- await robot.run(param)
- } else if (executeType === "STOP") {
- await robot.closeApp(param)
- } else if (executeType === "RESTART") {
- await robot.restartApp(param)
- }
- })(param);
- // 回应信号(响应请求)
- res.send({'code': 200, 'data': "null", "message": "SUCCESS"});
- })
- //启动-仓位检查
- app.get('/searchPositions', (req, res) => {
- const param = req.query;
- logger.info(JSON.stringify(param));
- robot.searchPositions(param)
- res.send({'code': 200, 'data': true, "message": "SUCCESS"});
- })
- // 新策略-返回机器人状态
- app.get('/predictorState', (req, res) => {
- const param = req.query;
- logger.info(JSON.stringify(param));
- var id = param.id;
- var port = -1;
- robot.appMap.forEach((value, key) => {
- // logger.info(JSON.stringify(value))
- if (value.id + "" === id + "") {
- port = value.port
- }
- })
- if (port !== -1) {
- logger.info('#####################predictorState:');
- var config = getRustConfig()
- var com = `curl -X GET -H "auth: 4L" -H "token: r7T$8gBV!f&L@E2+" "http://127.0.0.1:${port}/predictor_state"`;
- logger.info('#####################com:', com);
- execSync(com, (error, stdout, stderr) => {
- if (error) {
- logger.info(`#####################汇报:获取状态请求失败: ${error.message}`)
- res.send({'code': -1, 'data': null, "message": `获取状态请求失败`});
- }
- logger.info('#####################-d', stdout);
- logger.info('#####################-ok');
- res.send({'code': 200, 'data': stdout, "message": "SUCCESS"});
- });
- } else {
- res.send({'code': -1, 'data': null, "message": "机器人不存在"});
- }
- })
- // 使服务器监听特定端口
- app.listen(port, () => {
- // console.log(`服务器正在监听 http://localhost:${port}`);
- });
- logger.info('--web 启动');
- }
- // node-已上线-上报
- function robotNodeStatus() {
- var config = getRustConfig()
- http.request_post(`${config.reportedUrl}/report/beOnline`, {}, {...config.headers}).then((data) => {
- // logger.info('??', data);
- logger.info('#####################汇报:node 在线-上报成功!', data);
- }).catch((error) => {
- logger.error(`node 在线!-上报失败: ${error.message}`); // 处理可能发生的错误
- });
- }
- function isOK(req, res) {
- res.send({'code': 200, 'data': "null", "message": "SUCCESS"});
- }
- // 日志读取操作
- module.exports = {
- init,
- robotNodeStatus
- };
|