2020-09-09 07:39:17 +08:00
|
|
|
import { logger } from "@coder/logger"
|
2020-09-09 12:06:28 +08:00
|
|
|
import { spawn } from "child_process"
|
|
|
|
import path from "path"
|
|
|
|
import split2 from "split2"
|
2020-09-09 12:03:01 +08:00
|
|
|
|
|
|
|
const coderCloudAgent = path.resolve(__dirname, "../../lib/coder-cloud-agent")
|
2020-09-09 07:39:17 +08:00
|
|
|
|
2020-10-07 09:05:32 +08:00
|
|
|
export async function coderCloudBind(serverName: string): Promise<void> {
|
2020-09-09 07:39:17 +08:00
|
|
|
const agent = spawn(coderCloudAgent, ["link", serverName], {
|
|
|
|
stdio: ["inherit", "inherit", "pipe"],
|
|
|
|
})
|
|
|
|
|
2020-09-09 12:06:28 +08:00
|
|
|
agent.stderr.pipe(split2()).on("data", (line) => {
|
2020-09-09 07:39:17 +08:00
|
|
|
line = line.replace(/^[0-9-]+ [0-9:]+ [^ ]+\t/, "")
|
|
|
|
logger.info(line)
|
|
|
|
})
|
|
|
|
|
|
|
|
return new Promise((res, rej) => {
|
|
|
|
agent.on("error", rej)
|
|
|
|
|
2020-09-09 12:06:28 +08:00
|
|
|
agent.on("close", (code) => {
|
2020-09-09 07:39:17 +08:00
|
|
|
if (code !== 0) {
|
|
|
|
rej({
|
|
|
|
message: `coder cloud agent exited with ${code}`,
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
res()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
2020-09-09 12:03:01 +08:00
|
|
|
|
|
|
|
export function coderCloudProxy(addr: string) {
|
|
|
|
// addr needs to be in host:port format.
|
|
|
|
// So we trim the protocol.
|
|
|
|
addr = addr.replace(/^https?:\/\//, "")
|
|
|
|
|
|
|
|
const _proxy = async () => {
|
|
|
|
const agent = spawn(coderCloudAgent, ["proxy", "--code-server-addr", addr], {
|
|
|
|
stdio: ["inherit", "inherit", "pipe"],
|
|
|
|
})
|
|
|
|
|
2020-09-09 12:06:28 +08:00
|
|
|
agent.stderr.pipe(split2()).on("data", (line) => {
|
2020-09-09 12:03:01 +08:00
|
|
|
line = line.replace(/^[0-9-]+ [0-9:]+ [^ ]+\t/, "")
|
|
|
|
logger.info(line)
|
|
|
|
})
|
|
|
|
|
|
|
|
return new Promise((res, rej) => {
|
|
|
|
agent.on("error", rej)
|
|
|
|
|
2020-09-09 12:06:28 +08:00
|
|
|
agent.on("close", (code) => {
|
2020-09-09 12:03:01 +08:00
|
|
|
if (code !== 0) {
|
|
|
|
rej({
|
|
|
|
message: `coder cloud agent exited with ${code}`,
|
|
|
|
})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
res()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const proxy = async () => {
|
|
|
|
try {
|
|
|
|
await _proxy()
|
2020-09-09 12:06:28 +08:00
|
|
|
} catch (err) {
|
2020-09-09 12:03:01 +08:00
|
|
|
logger.error(err.message)
|
|
|
|
}
|
|
|
|
setTimeout(proxy, 3000)
|
|
|
|
}
|
|
|
|
proxy()
|
|
|
|
}
|