Archived
1
0

Merge pull request #2099 from cdr/open-in

Make opening in an existing instance work outside code-server
This commit is contained in:
Anmol Sethi
2020-10-12 01:14:15 -04:00
committed by GitHub
8 changed files with 439 additions and 234 deletions

View File

@ -5,7 +5,7 @@ import * as os from "os"
import * as path from "path"
import { Args as VsArgs } from "../../lib/vscode/src/vs/server/ipc"
import { AuthType } from "./http"
import { generatePassword, humanPath, paths } from "./util"
import { canConnect, generatePassword, humanPath, paths } from "./util"
export class Optional<T> {
public constructor(public readonly value?: T) {}
@ -152,12 +152,12 @@ const options: Options<Required<Args>> = {
"new-window": {
type: "boolean",
short: "n",
description: "Force to open a new window. (use with open-in)",
description: "Force to open a new window.",
},
"reuse-window": {
type: "boolean",
short: "r",
description: "Force to open a file or folder in an already opened window. (use with open-in)",
description: "Force to open a file or folder in an already opened window.",
},
locale: { type: "string" },
@ -327,6 +327,21 @@ export const parse = (
logger.debug("parsed command line", field("args", args))
return args
}
export async function setDefaults(args: Args): Promise<Args> {
args = { ...args }
if (!args["user-data-dir"]) {
await copyOldMacOSDataDir()
args["user-data-dir"] = paths.data
}
if (!args["extensions-dir"]) {
args["extensions-dir"] = path.join(args["user-data-dir"], "extensions")
}
// --verbose takes priority over --log and --log takes priority over the
// environment variable.
if (args.verbose) {
@ -369,21 +384,6 @@ export const parse = (
return args
}
export async function setDefaults(args: Args): Promise<Args> {
args = { ...args }
if (!args["user-data-dir"]) {
await copyOldMacOSDataDir()
args["user-data-dir"] = paths.data
}
if (!args["extensions-dir"]) {
args["extensions-dir"] = path.join(args["user-data-dir"], "extensions")
}
return args
}
async function defaultConfigFile(): Promise<string> {
return `bind-addr: 127.0.0.1:8080
auth: password
@ -410,10 +410,6 @@ export async function readConfigFile(configPath?: string): Promise<Args> {
logger.info(`Wrote default config file to ${humanPath(configPath)}`)
}
if (!process.env.CODE_SERVER_PARENT_PID && !process.env.VSCODE_IPC_HOOK_CLI) {
logger.info(`Using config file ${humanPath(configPath)}`)
}
const configFile = await fs.readFile(configPath)
const config = yaml.safeLoad(configFile.toString(), {
filename: configPath,
@ -496,3 +492,52 @@ async function copyOldMacOSDataDir(): Promise<void> {
await fs.copy(oldDataDir, paths.data)
}
}
export const shouldRunVsCodeCli = (args: Args): boolean => {
return !!args["list-extensions"] || !!args["install-extension"] || !!args["uninstall-extension"]
}
/**
* Determine if it looks like the user is trying to open a file or folder in an
* existing instance. The arguments here should be the arguments the user
* explicitly passed on the command line, not defaults or the configuration.
*/
export const shouldOpenInExistingInstance = async (args: Args): Promise<string | undefined> => {
// Always use the existing instance if we're running from VS Code's terminal.
if (process.env.VSCODE_IPC_HOOK_CLI) {
return process.env.VSCODE_IPC_HOOK_CLI
}
const readSocketPath = async (): Promise<string | undefined> => {
try {
return await fs.readFile(path.join(os.tmpdir(), "vscode-ipc"), "utf8")
} catch (error) {
if (error.code !== "ENOENT") {
throw error
}
}
return undefined
}
// If these flags are set then assume the user is trying to open in an
// existing instance since these flags have no effect otherwise.
const openInFlagCount = ["reuse-window", "new-window"].reduce((prev, cur) => {
return args[cur as keyof Args] ? prev + 1 : prev
}, 0)
if (openInFlagCount > 0) {
return readSocketPath()
}
// It's possible the user is trying to spawn another instance of code-server.
// Check if any unrelated flags are set (check against one because `_` always
// exists), that a file or directory was passed, and that the socket is
// active.
if (Object.keys(args).length === 1 && args._.length > 0) {
const socketPath = await readSocketPath()
if (socketPath && (await canConnect(socketPath))) {
return socketPath
}
}
return undefined
}

View File

@ -11,19 +11,21 @@ import { ProxyHttpProvider } from "./app/proxy"
import { StaticHttpProvider } from "./app/static"
import { UpdateHttpProvider } from "./app/update"
import { VscodeHttpProvider } from "./app/vscode"
import { Args, bindAddrFromAllSources, optionDescriptions, parse, readConfigFile, setDefaults } from "./cli"
import {
Args,
bindAddrFromAllSources,
optionDescriptions,
parse,
readConfigFile,
setDefaults,
shouldOpenInExistingInstance,
shouldRunVsCodeCli,
} from "./cli"
import { coderCloudBind } from "./coder-cloud"
import { AuthType, HttpServer, HttpServerOptions } from "./http"
import { loadPlugins } from "./plugin"
import { generateCertificate, hash, humanPath, open } from "./util"
import { ipcMain, wrap } from "./wrapper"
process.on("uncaughtException", (error) => {
logger.error(`Uncaught exception: ${error.message}`)
if (typeof error.stack !== "undefined") {
logger.error(error.stack)
}
})
import { ipcMain, WrapperProcess } from "./wrapper"
let pkg: { version?: string; commit?: string } = {}
try {
@ -35,6 +37,86 @@ try {
const version = pkg.version || "development"
const commit = pkg.commit || "development"
export const runVsCodeCli = (args: Args): void => {
logger.debug("forking vs code cli...")
const vscode = cp.fork(path.resolve(__dirname, "../../lib/vscode/out/vs/server/fork"), [], {
env: {
...process.env,
CODE_SERVER_PARENT_PID: process.pid.toString(),
},
})
vscode.once("message", (message: any) => {
logger.debug("got message from VS Code", field("message", message))
if (message.type !== "ready") {
logger.error("Unexpected response waiting for ready response", field("type", message.type))
process.exit(1)
}
const send: CliMessage = { type: "cli", args }
vscode.send(send)
})
vscode.once("error", (error) => {
logger.error("Got error from VS Code", field("error", error))
process.exit(1)
})
vscode.on("exit", (code) => process.exit(code || 0))
}
export const openInExistingInstance = async (args: Args, socketPath: string): Promise<void> => {
const pipeArgs: OpenCommandPipeArgs & { fileURIs: string[] } = {
type: "open",
folderURIs: [],
fileURIs: [],
forceReuseWindow: args["reuse-window"],
forceNewWindow: args["new-window"],
}
const isDir = async (path: string): Promise<boolean> => {
try {
const st = await fs.stat(path)
return st.isDirectory()
} catch (error) {
return false
}
}
for (let i = 0; i < args._.length; i++) {
const fp = path.resolve(args._[i])
if (await isDir(fp)) {
pipeArgs.folderURIs.push(fp)
} else {
pipeArgs.fileURIs.push(fp)
}
}
if (pipeArgs.forceNewWindow && pipeArgs.fileURIs.length > 0) {
logger.error("--new-window can only be used with folder paths")
process.exit(1)
}
if (pipeArgs.folderURIs.length === 0 && pipeArgs.fileURIs.length === 0) {
logger.error("Please specify at least one file or folder")
process.exit(1)
}
const vscode = http.request(
{
path: "/",
method: "POST",
socketPath,
},
(response) => {
response.on("data", (message) => {
logger.debug("got message from VS Code", field("message", message.toString()))
})
},
)
vscode.on("error", (error: unknown) => {
logger.error("got error from VS Code", field("error", error))
})
vscode.write(JSON.stringify(pipeArgs))
vscode.end()
}
const main = async (args: Args, configArgs: Args): Promise<void> => {
if (args.link) {
// If we're being exposed to the cloud, we listen on a random address and disable auth.
@ -99,13 +181,15 @@ const main = async (args: Args, configArgs: Args): Promise<void> => {
await loadPlugins(httpServer, args)
ipcMain().onDispose(() => {
ipcMain.onDispose(() => {
httpServer.dispose().then((errors) => {
errors.forEach((error) => logger.error(error.message))
})
})
logger.info(`code-server ${version} ${commit}`)
logger.info(`Using config file ${humanPath(args.config)}`)
const serverAddress = await httpServer.listen()
logger.info(`HTTP server listening on ${serverAddress}`)
@ -139,7 +223,9 @@ const main = async (args: Args, configArgs: Args): Promise<void> => {
if (serverAddress && !options.socket && args.open) {
// The web socket doesn't seem to work if browsing with 0.0.0.0.
const openAddress = serverAddress.replace(/:\/\/0.0.0.0/, "://localhost")
await open(openAddress).catch(console.error)
await open(openAddress).catch((error: Error) => {
logger.error("Failed to open", field("address", openAddress), field("error", error))
})
logger.info(`Opened ${openAddress}`)
}
@ -148,27 +234,27 @@ const main = async (args: Args, configArgs: Args): Promise<void> => {
await coderCloudBind(serverAddress!, args.link.value)
} catch (err) {
logger.error(err.message)
ipcMain().exit(1)
ipcMain.exit(1)
}
}
}
async function entry(): Promise<void> {
const tryParse = async (): Promise<[Args, Args]> => {
try {
const cliArgs = parse(process.argv.slice(2))
const configArgs = await readConfigFile(cliArgs.config)
// This prioritizes the flags set in args over the ones in the config file.
let args = Object.assign(configArgs, cliArgs)
args = await setDefaults(args)
return [args, configArgs]
} catch (error) {
console.error(error.message)
process.exit(1)
}
const cliArgs = parse(process.argv.slice(2))
const configArgs = await readConfigFile(cliArgs.config)
// This prioritizes the flags set in args over the ones in the config file.
let args = Object.assign(configArgs, cliArgs)
args = await setDefaults(args)
// There's no need to check flags like --help or to spawn in an existing
// instance for the child process because these would have already happened in
// the parent and the child wouldn't have been spawned.
if (ipcMain.isChild) {
await ipcMain.handshake()
ipcMain.preventExit()
return main(args, configArgs)
}
const [args, configArgs] = await tryParse()
if (args.help) {
console.log("code-server", version, commit)
console.log("")
@ -178,7 +264,10 @@ async function entry(): Promise<void> {
optionDescriptions().forEach((description) => {
console.log("", description)
})
} else if (args.version) {
return
}
if (args.version) {
if (args.json) {
console.log({
codeServer: version,
@ -188,83 +277,23 @@ async function entry(): Promise<void> {
} else {
console.log(version, commit)
}
process.exit(0)
} else if (args["list-extensions"] || args["install-extension"] || args["uninstall-extension"]) {
logger.debug("forking vs code cli...")
const vscode = cp.fork(path.resolve(__dirname, "../../lib/vscode/out/vs/server/fork"), [], {
env: {
...process.env,
CODE_SERVER_PARENT_PID: process.pid.toString(),
},
})
vscode.once("message", (message: any) => {
logger.debug("Got message from VS Code", field("message", message))
if (message.type !== "ready") {
logger.error("Unexpected response waiting for ready response")
process.exit(1)
}
const send: CliMessage = { type: "cli", args }
vscode.send(send)
})
vscode.once("error", (error) => {
logger.error(error.message)
process.exit(1)
})
vscode.on("exit", (code) => process.exit(code || 0))
} else if (process.env.VSCODE_IPC_HOOK_CLI) {
const pipeArgs: OpenCommandPipeArgs = {
type: "open",
folderURIs: [],
forceReuseWindow: args["reuse-window"],
forceNewWindow: args["new-window"],
}
const isDir = async (path: string): Promise<boolean> => {
try {
const st = await fs.stat(path)
return st.isDirectory()
} catch (error) {
return false
}
}
for (let i = 0; i < args._.length; i++) {
const fp = path.resolve(args._[i])
if (await isDir(fp)) {
pipeArgs.folderURIs.push(fp)
} else {
if (!pipeArgs.fileURIs) {
pipeArgs.fileURIs = []
}
pipeArgs.fileURIs.push(fp)
}
}
if (pipeArgs.forceNewWindow && pipeArgs.fileURIs && pipeArgs.fileURIs.length > 0) {
logger.error("new-window can only be used with folder paths")
process.exit(1)
}
if (pipeArgs.folderURIs.length === 0 && (!pipeArgs.fileURIs || pipeArgs.fileURIs.length === 0)) {
logger.error("Please specify at least one file or folder argument")
process.exit(1)
}
const vscode = http.request(
{
path: "/",
method: "POST",
socketPath: process.env["VSCODE_IPC_HOOK_CLI"],
},
(res) => {
res.on("data", (message) => {
logger.debug("Got message from VS Code", field("message", message.toString()))
})
},
)
vscode.on("error", (err) => {
logger.debug("Got error from VS Code", field("error", err))
})
vscode.write(JSON.stringify(pipeArgs))
vscode.end()
} else {
wrap(() => main(args, configArgs))
return
}
if (shouldRunVsCodeCli(args)) {
return runVsCodeCli(args)
}
const socketPath = await shouldOpenInExistingInstance(cliArgs)
if (socketPath) {
return openInExistingInstance(args, socketPath)
}
const wrapper = new WrapperProcess(require("../../package.json").version)
return wrapper.start()
}
entry()
entry().catch((error) => {
logger.error(error.message)
ipcMain.exit(error)
})

View File

@ -4,7 +4,7 @@ import * as path from "path"
import * as tls from "tls"
import { Emitter } from "../common/emitter"
import { generateUuid } from "../common/util"
import { tmpdir } from "./util"
import { canConnect, tmpdir } from "./util"
/**
* Provides a way to proxy a TLS socket. Can be used when you need to pass a
@ -89,17 +89,6 @@ export class SocketProxyProvider {
}
public async findFreeSocketPath(basePath: string, maxTries = 100): Promise<string> {
const canConnect = (path: string): Promise<boolean> => {
return new Promise((resolve) => {
const socket = net.connect(path)
socket.once("error", () => resolve(false))
socket.once("connect", () => {
socket.destroy()
resolve(true)
})
})
}
let i = 0
let path = basePath
while ((await canConnect(path)) && i < maxTries) {

View File

@ -2,6 +2,7 @@ import * as cp from "child_process"
import * as crypto from "crypto"
import envPaths from "env-paths"
import * as fs from "fs-extra"
import * as net from "net"
import * as os from "os"
import * as path from "path"
import * as util from "util"
@ -246,3 +247,17 @@ export function pathToFsPath(path: string, keepDriveLetterCasing = false): strin
}
return value
}
/**
* Return a promise that resolves with whether the socket path is active.
*/
export function canConnect(path: string): Promise<boolean> {
return new Promise((resolve) => {
const socket = net.connect(path)
socket.once("error", () => resolve(false))
socket.once("connect", () => {
socket.destroy()
resolve(true)
})
})
}

View File

@ -32,19 +32,13 @@ export class IpcMain {
public readonly onMessage = this._onMessage.event
private readonly _onDispose = new Emitter<NodeJS.Signals | undefined>()
public readonly onDispose = this._onDispose.event
public readonly processExit: (code?: number) => never
public readonly processExit: (code?: number) => never = process.exit
public constructor(public readonly parentPid?: number) {
public constructor(private readonly parentPid?: number) {
process.on("SIGINT", () => this._onDispose.emit("SIGINT"))
process.on("SIGTERM", () => this._onDispose.emit("SIGTERM"))
process.on("exit", () => this._onDispose.emit(undefined))
// Ensure we control when the process exits.
this.processExit = process.exit
process.exit = function (code?: number) {
logger.warn(`process.exit() was prevented: ${code || "unknown code"}.`)
} as (code?: number) => never
this.onDispose((signal) => {
// Remove listeners to avoid possibly triggering disposal again.
process.removeAllListeners()
@ -71,6 +65,19 @@ export class IpcMain {
}
}
/**
* Ensure we control when the process exits.
*/
public preventExit(): void {
process.exit = function (code?: number) {
logger.warn(`process.exit() was prevented: ${code || "unknown code"}.`)
} as (code?: number) => never
}
public get isChild(): boolean {
return typeof this.parentPid !== "undefined"
}
public exit(error?: number | ProcessError): never {
if (error && typeof error !== "number") {
this.processExit(typeof error.code === "number" ? error.code : 1)
@ -127,17 +134,12 @@ export class IpcMain {
}
}
let _ipcMain: IpcMain
export const ipcMain = (): IpcMain => {
if (!_ipcMain) {
_ipcMain = new IpcMain(
typeof process.env.CODE_SERVER_PARENT_PID !== "undefined"
? parseInt(process.env.CODE_SERVER_PARENT_PID)
: undefined,
)
}
return _ipcMain
}
/**
* Channel for communication between the child and parent processes.
*/
export const ipcMain = new IpcMain(
typeof process.env.CODE_SERVER_PARENT_PID !== "undefined" ? parseInt(process.env.CODE_SERVER_PARENT_PID) : undefined,
)
export interface WrapperOptions {
maxMemory?: number
@ -162,14 +164,11 @@ export class WrapperProcess {
this.logStdoutStream = rfs.createStream(path.join(paths.data, "coder-logs", "code-server-stdout.log"), opts)
this.logStderrStream = rfs.createStream(path.join(paths.data, "coder-logs", "code-server-stderr.log"), opts)
ipcMain().onDispose(() => {
if (this.process) {
this.process.removeAllListeners()
this.process.kill()
}
ipcMain.onDispose(() => {
this.disposeChild()
})
ipcMain().onMessage((message) => {
ipcMain.onMessage((message) => {
switch (message.type) {
case "relaunch":
logger.info(`Relaunching: ${this.currentVersion} -> ${message.version}`)
@ -181,55 +180,65 @@ export class WrapperProcess {
break
}
})
process.on("SIGUSR1", async () => {
logger.info("Received SIGUSR1; hotswapping")
this.relaunch()
})
}
private async relaunch(): Promise<void> {
private disposeChild(): void {
this.started = undefined
if (this.process) {
this.process.removeAllListeners()
this.process.kill()
}
}
private async relaunch(): Promise<void> {
this.disposeChild()
try {
await this.start()
} catch (error) {
logger.error(error.message)
ipcMain().exit(typeof error.code === "number" ? error.code : 1)
ipcMain.exit(typeof error.code === "number" ? error.code : 1)
}
}
public start(): Promise<void> {
if (!this.started) {
this.started = this.spawn().then((child) => {
// Log both to stdout and to the log directory.
if (child.stdout) {
child.stdout.pipe(this.logStdoutStream)
child.stdout.pipe(process.stdout)
}
if (child.stderr) {
child.stderr.pipe(this.logStderrStream)
child.stderr.pipe(process.stderr)
}
logger.debug(`spawned inner process ${child.pid}`)
ipcMain()
.handshake(child)
.then(() => {
child.once("exit", (code) => {
logger.debug(`inner process ${child.pid} exited unexpectedly`)
ipcMain().exit(code || 0)
})
})
this.process = child
// If we have a process then we've already bound this.
if (!this.process) {
process.on("SIGUSR1", async () => {
logger.info("Received SIGUSR1; hotswapping")
this.relaunch()
})
}
if (!this.started) {
this.started = this._start()
}
return this.started
}
private async spawn(): Promise<cp.ChildProcess> {
private async _start(): Promise<void> {
const child = this.spawn()
this.process = child
// Log both to stdout and to the log directory.
if (child.stdout) {
child.stdout.pipe(this.logStdoutStream)
child.stdout.pipe(process.stdout)
}
if (child.stderr) {
child.stderr.pipe(this.logStderrStream)
child.stderr.pipe(process.stderr)
}
logger.debug(`spawned inner process ${child.pid}`)
await ipcMain.handshake(child)
child.once("exit", (code) => {
logger.debug(`inner process ${child.pid} exited unexpectedly`)
ipcMain.exit(code || 0)
})
}
private spawn(): cp.ChildProcess {
// Flags to pass along to the Node binary.
let nodeOptions = `${process.env.NODE_OPTIONS || ""} ${(this.options && this.options.nodeOptions) || ""}`
if (!/max_old_space_size=(\d+)/g.exec(nodeOptions)) {
@ -251,23 +260,13 @@ export class WrapperProcess {
// It's possible that the pipe has closed (for example if you run code-server
// --version | head -1). Assume that means we're done.
if (!process.stdout.isTTY) {
process.stdout.on("error", () => ipcMain().exit())
process.stdout.on("error", () => ipcMain.exit())
}
export const wrap = (fn: () => Promise<void>): void => {
if (ipcMain().parentPid) {
ipcMain()
.handshake()
.then(() => fn())
.catch((error: ProcessError): void => {
logger.error(error.message)
ipcMain().exit(error)
})
} else {
const wrapper = new WrapperProcess(require("../../package.json").version)
wrapper.start().catch((error) => {
logger.error(error.message)
ipcMain().exit(error)
})
// Don't let uncaught exceptions crash the process.
process.on("uncaughtException", (error) => {
logger.error(`Uncaught exception: ${error.message}`)
if (typeof error.stack !== "undefined") {
logger.error(error.stack)
}
}
})