Skip to content

Commit ebe83e7

Browse files
committed
add remoteRunner
1 parent fb46bfb commit ebe83e7

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

packages/server/utils.ts

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
/* eslint-disable @typescript-eslint/no-loop-func */
2+
/* eslint-disable no-await-in-loop */
3+
import { spawn } from 'child_process';
14
import Logger from 'reggol';
25

36
Logger.levels.base = process.env.DEV ? 3 : 2;
@@ -88,3 +91,41 @@ export function StaticHTML(context, randomHash) {
8891
// eslint-disable-next-line max-len
8992
return `<html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>@Hydro/XCPC-TOOLS</title></head><body><div id="root"></div><script>window.Context=JSON.parse('${JSON.stringify(context)}')</script><script src="/main.js?${randomHash}"></script></body></html>`;
9093
}
94+
95+
// wait for undefined to write
96+
export async function remoteRunner(user: string, target: string, targetPort: string, timeout = 10, RETRY = 3, command) {
97+
let log = '';
98+
const defaultCommand = `-o ConnectTimeout=${timeout} -o StrictHostKeyChecking=no -P ${targetPort}`;
99+
const cmds = {
100+
exec: [defaultCommand, `${user}@${target}`, command],
101+
upload: [defaultCommand, command.from, `${user}@${target}:${command.to}`],
102+
download: [defaultCommand, `${user}@${target}:${command.from.replace('{target}', target)}`, command.to.replace('{target}', target)],
103+
};
104+
let retry = 0;
105+
while (retry < RETRY) {
106+
const child = spawn(command.type === 'exec' ? 'ssh' : 'scp', cmds[command.type]);
107+
// 输出命令行执行的结果
108+
let success = false;
109+
child.stdout.on('data', (data) => {
110+
success = true;
111+
log += data;
112+
});
113+
child.stderr.on('data', (data) => {
114+
success = false;
115+
log += data;
116+
});
117+
// 执行命令行错误
118+
child.on('error', (err) => {
119+
log += err;
120+
return { success: false, log };
121+
});
122+
// 命令行执行结束
123+
child.on('close', (e) => {
124+
if (e === 0) return { success: true, log };
125+
if (success) return { success: true, log };
126+
log += `retry ${retry} times`;
127+
retry++;
128+
});
129+
}
130+
return { success: false, log };
131+
}

0 commit comments

Comments
 (0)