123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409 |
- const file = require("./utils/file");
- const {getRustConfig} = require("./config");
- const {spawn, exec, fork, execSync} = require("child_process");
- const {logger} = require("./utils/logger");
- const http = require("./utils/http");
- const e = require("express");
- const RobotStatus = Object.freeze({
-
- STOPPED: "STOPPED",
-
- STOP_PENDING: "STOP_PENDING",
-
- RUNNING: "RUNNING",
-
- START_PENDING: "START_PENDING",
-
- DOWNLOADING: "DOWNLOADING",
-
- ERROR: "ERROR"
- });
- let appMap = new Map();
- function getApp(key) {
- let app = {
- id: -1,
- childProcess: undefined,
- nowBalance: 0,
- messlist: [],
- threadStatus: RobotStatus.STOPPED,
- errorMessage: "成功",
- threadStartTime: -1,
- }
-
- if (appMap.has(key)) {
- app = appMap.get(key)
- } else {
- appMap.set(key, app)
- }
-
- return app
- }
- function delApp(key) {
- appMap.delete(key)
- }
- async function run(param) {
- var key = param.id
- var appName = param.path
- var app = getApp(key)
- var config = getRustConfig()
-
- var waitForCondition = function (intervalDuration, conditionFunction) {
- return new Promise((resolve, reject) => {
- const intervalId = setInterval(() => {
- if (conditionFunction()) {
- clearInterval(intervalId);
- resolve();
- }
- }, intervalDuration);
- });
- }
- logger.info('当前app', app);
- if (app.childProcess !== undefined && app.threadStatus !== RobotStatus.STOPPED
- && app.threadStatus !== RobotStatus.ERROR && app.threadStatus !== RobotStatus.STOP_PENDING) {
- logger.info('防止重复启动,需要先杀死');
- app.threadStatus = RobotStatus.STOP_PENDING
- robotStatus(app)
- app.childProcess.kill()
-
- await waitForCondition(1000, () => {
- if (app.threadStatus === RobotStatus.STOPPED) {
- logger.info('成功杀死可以重新开启');
- return true
- } else {
- logger.info('等待杀死');
- return false
- }
- });
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- app.threadStatus = RobotStatus.START_PENDING
- app.id = key
- robotStatus(app)
-
-
- const platform = process.platform;
- let exeName = appName;
-
- let configName = "config.json";
- let appPath = "";
- if (platform === 'win32') {
- appPath = config.winPath + "/" + app.id
- } else {
- appPath = config.linuxPath + "/" + app.id
- }
-
- var isDow = false
- var scheduleDow = 0
- var scheduleConfig = 0
-
- file.checkPathSync(appPath);
-
- var destination = appPath + "/" + exeName
- if (!file.checkFilePath(destination)) {
- app.threadStatus = RobotStatus.DOWNLOADING
- robotStatus(app)
- isDow = true
- var dowHeaders = {...config.headers};
- if (platform === 'win32') {
- downloadFileWithPowerShell(
- config.baseUrl + config.dowAppURL + '/?path=' + appName,
- appPath + "/" + appName,
- dowHeaders, (err, b) => {
- if (err === null) {
- scheduleDow = 1
- } else {
- app.threadStatus = RobotStatus.ERROR
- app.errorMessage = '下载失败!'
- scheduleDow = -1
- robotStatus(app)
- }
- });
- } else {
- downloadFileWithLinux(
- config.baseUrl + config.dowAppURL + '/?path=' + appName,
- appPath + "/" + appName,
- dowHeaders, (err, b) => {
- if (err === null) {
- scheduleDow = 1
- } else {
- app.threadStatus = RobotStatus.ERROR
- app.errorMessage = '下载失败!'
- scheduleDow = -1
- robotStatus(app)
- }
- });
- }
- } else {
- scheduleDow = 1
- }
-
-
- var destination2 = appPath + "/" + configName
- var urrrl = config.baseUrl + config.dowConfigURL + '/?robotId=' + app.id
- var configHeaders = {...config.headers};
- http.request_get(urrrl, {...config.headers})
- .then((data) => {
- logger.info('配置参数:', data);
- const json = JSON.parse(data)
-
- const map = json.data
- var json_obj = JSON.parse("{}")
- for (k in map) {
-
- if (k === "account") {
- var account = map["account"];
- delete map.account
- json_obj["account_name"] = account["name"]
- json_obj["access_key"] = account["accessKey"]
- json_obj["secret_key"] = account["secretKey"]
- json_obj["pass_key"] = account["pass"]
- } else if (k === "ref_pair") {
- json_obj["ref_pair"] = [map["ref_pair"]]
- } else {
- json_obj[k] = map[k]
- }
- logger.info(map[k] + "\t")
- }
- logger.info("参数组装完成!")
- te = JSON.stringify(json_obj)
- file.writeFile(destination2, te, (errer, b) => {
- if (errer === null && b === true) {
- scheduleConfig = 1
- } else {
- logger.info("配置参数写入配置失败!", errer)
- app.threadStatus = RobotStatus.ERROR
- app.errorMessage = '配置参数写入配置失败!'
- scheduleConfig = -1
- robotStatus(app)
- }
- })
- })
- .catch((e) => {
- logger.info("配置参数获取失败", e)
- app.threadStatus = RobotStatus.ERROR
- app.errorMessage = '配置参数获取失败!'
- scheduleConfig = -1
- robotStatus(app)
- })
-
- while (true) {
- await delay(5000);
- let info_t = ""
- let info_t2 = ""
-
- if (isDow) {
- if (scheduleDow === 1) {
- info_t = "启动文件:下载完成!"
-
- execSync(`chmod +x ${appPath + "/" + appName}`, (error, stdout, stderr) => {
- if (error) {
- logger.error(`启动文件:授权失败: ${error}`);
- }
- logger.info(`启动文件:授权完成!`);
- });
- } else if (scheduleDow === -1) {
- info_t = "启动文件:下载失败!"
- } else {
- info_t = "启动文件:还在下载..."
- }
- } else {
- info_t = "启动文件:完整无需下载"
- }
- if (scheduleConfig === 1) {
- info_t2 = "配置文件:读取成功!"
- } else if (scheduleConfig === -1) {
- info_t = "配置文件:读取失败!"
- } else {
- info_t2 = "配置文件:还在读取..."
- }
- logger.info(info_t, info_t2);
- if (scheduleDow === 1 && scheduleConfig === 1) {
- break
- } else if (scheduleConfig === -1 || scheduleDow === -1) {
- return;
- }
- }
- app.threadStatus = RobotStatus.START_PENDING
- robotStatus(app)
- logger.info("开始启动程序!");
-
- const exePath = appPath + "/" + exeName
- const configPath = appPath + "/" + configName
- logger.info(`文件地址:${exePath}-----${configPath}`);
- const command = exePath
- const args = ['--config=' + configPath]
- app.childProcess = spawn(command, args)
- app.threadStartTime = new Date().getTime()
-
- app.childProcess.stdout.on('data', (msg) => {
-
- })
- app.childProcess.on('message', (msg) => {
-
- });
- app.childProcess.on('exit', (code, signal) => {
- logger.info(`子进程退出-exit,退出码: ${code}, 信号: ${signal}`);
- });
- app.childProcess.on('close', (code) => {
- logger.info(`子进程退出-close,退出码 ${code}`);
- app.threadStatus = RobotStatus.STOPPED
- robotStatus(app)
- });
- app.threadStatus = RobotStatus.RUNNING
- }
- function delay(ms) {
- return new Promise(resolve => setTimeout(resolve, ms));
- }
- async function closeApp(param) {
- var key = param.id
- var app = getApp(key)
- logger.info(` 信号: `, app.threadStatus);
- if (app.threadStatus === RobotStatus.RUNNING) {
- app.childProcess.kill('SIGTERM');
- app.threadStatus = RobotStatus.STOP_PENDING
- robotStatus(app)
- }
- }
- function downloadFileWithPowerShell(url, destination, headers, funBreak) {
- const headersString = Object.entries(headers)
- .map(([key, value]) => `'${key}'='${value}'`)
- .join('; ');
- const command = `powershell -command "Invoke-WebRequest -Uri '${url}' -OutFile '${destination}' -Headers @{${headersString}}"`;
- exec(command, (error, stdout, stderr) => {
- if (error) {
- logger.error(`下载出错: ${error}`);
- return funBreak(error);
- }
- logger.info(`下载完成!`);
- funBreak(null, true);
- });
- }
- function downloadFileWithLinux(url, destination, headers, funBreak) {
- const headersString = Object.entries(headers)
- .map(([key, value]) => `-H '${key}: ${value}'`)
- .join(' ');
- const command = `curl ${headersString} '${url}' -o '${destination}'`;
- exec(command, (error, stdout, stderr) => {
- if (error) {
- logger.error(`下载出错: ${error}`);
- return funBreak(error);
- }
- logger.info(`下载完成!`);
- funBreak(null, true);
- });
- }
- function robotStatus(app) {
- var config = getRustConfig()
- var msg = (app.threadStatus !== RobotStatus.ERROR ? "完成" : app.errorMessage)
- http.request_post(`${config.baseUrl}/report/statusReport`, {
- "robotId": app.id,
- "status": app.threadStatus,
- "msg": msg
- }, {...config.headers}).then((data) => {
-
- logger.info('汇报--状态:', '机器人id:', app.id, '状态:', app.threadStatus);
- }).catch((error) => {
- logger.error(`请求遇到问题1: ${error.message}`);
- });
- }
- function robotAmount(app) {
-
- try {
- var config = getRustConfig()
- http.request_get(`${config.rustUrl}/account`, {...config.headers})
- .then((data) => {
- var d = JSON.parse(data)
-
- if ((app.nowBalance + "") !== (d.now_balance + "")) {
- http.request_post(`${config.baseUrl}/report/amountReport`, {
- "robotId": app.id,
- "amount": d.now_balance
- }, {...config.headers})
- .then((data2) => {
-
- logger.info('汇报--余额:pid:', app.childProcess.pid, '机器人id:', app.id, '机器人本地余额:', app.nowBalance, '实际余额:', d.now_balance);
- }).catch((error) => {
- logger.error(`请求遇到问题:2 ${error.message}`);
- });
- app.nowBalance = d.now_balance
- }
- }).catch((error) => {
- logger.error(`请求遇到问题2: ${error.message}`);
- });
- } catch (e) {
- logger.error('请求失败!:', e)
- }
- }
- function delRobot(app) {
- const platform = process.platform;
- if (platform !== 'win32' && app.threadStatus === RobotStatus.STOPPED) {
- var pid = app.childProcess.pid
- delApp(app.id)
- }
- }
- module.exports = {
- run, closeApp, delRobot, robotStatus, robotAmount, appMap, RobotStatus
- };
|