remoteTerminalService.ts 11.1 KB
Newer Older
A
Alex Dima 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import * as nls from 'vs/nls';
A
Alex Dima 已提交
7 8 9 10 11 12 13 14 15
import { Barrier } from 'vs/base/common/async';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { revive } from 'vs/base/common/marshalling';
import { URI } from 'vs/base/common/uri';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
A
Alex Dima 已提交
16
import { IRemoteTerminalService, ITerminalInstanceService } from 'vs/workbench/contrib/terminal/browser/terminal';
A
Alex Dima 已提交
17
import { IRemoteTerminalProcessExecCommandEvent, IShellLaunchConfigDto, RemoteTerminalChannelClient, REMOTE_TERMINAL_CHANNEL_NAME } from 'vs/workbench/contrib/terminal/common/remoteTerminalChannel';
A
Alex Dima 已提交
18
import { IProcessDataEvent, IRemoteTerminalAttachTarget, IShellLaunchConfig, ITerminalChildProcess, ITerminalConfigHelper, ITerminalDimensionsOverride, ITerminalLaunchError } from 'vs/workbench/contrib/terminal/common/terminal';
A
Alex Dima 已提交
19 20 21 22 23 24
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';

export class RemoteTerminalService extends Disposable implements IRemoteTerminalService {
	public _serviceBrand: undefined;

	private readonly _remoteTerminalChannel: RemoteTerminalChannelClient | null;
25
	private _hasConnectedToRemote = false;
A
Alex Dima 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

	constructor(
		@ITerminalInstanceService readonly terminalInstanceService: ITerminalInstanceService,
		@IRemoteAgentService private readonly _remoteAgentService: IRemoteAgentService,
		@ILogService private readonly _logService: ILogService,
		@IInstantiationService private readonly _instantiationService: IInstantiationService,
		@ICommandService private readonly _commandService: ICommandService,
	) {
		super();
		const connection = this._remoteAgentService.getConnection();
		if (connection) {
			this._remoteTerminalChannel = this._instantiationService.createInstance(RemoteTerminalChannelClient, connection.remoteAuthority, connection.getChannel(REMOTE_TERMINAL_CHANNEL_NAME));
		} else {
			this._remoteTerminalChannel = null;
		}
	}

	public async createRemoteTerminalProcess(terminalId: number, shellLaunchConfig: IShellLaunchConfig, activeWorkspaceRootUri: URI | undefined, cols: number, rows: number, configHelper: ITerminalConfigHelper,): Promise<ITerminalChildProcess> {
		if (!this._remoteTerminalChannel) {
			throw new Error(`Cannot create remote terminal when there is no remote!`);
		}

48 49 50 51 52 53 54 55 56
		let isPreconnectionTerminal = false;
		if (!this._hasConnectedToRemote) {
			isPreconnectionTerminal = true;
			this._remoteAgentService.getEnvironment().then(() => {
				this._hasConnectedToRemote = true;
			});
		}

		return new RemoteTerminalProcess(terminalId, shellLaunchConfig, activeWorkspaceRootUri, cols, rows, configHelper, isPreconnectionTerminal, this._remoteTerminalChannel, this._remoteAgentService, this._logService, this._commandService);
A
Alex Dima 已提交
57
	}
58

A
Alex Dima 已提交
59 60 61 62 63 64 65 66 67 68
	public async listTerminals(): Promise<IRemoteTerminalAttachTarget[]> {
		const terms = this._remoteTerminalChannel ? await this._remoteTerminalChannel.listTerminals() : [];
		return terms.map(termDto => {
			return <IRemoteTerminalAttachTarget>{
				id: termDto.id,
				pid: termDto.pid,
				title: termDto.title,
				cwd: termDto.cwd
			};
		});
A
Alex Dima 已提交
69 70 71 72 73
	}
}

export class RemoteTerminalProcess extends Disposable implements ITerminalChildProcess {

A
Alex Dima 已提交
74 75
	public readonly _onProcessData = this._register(new Emitter<IProcessDataEvent>());
	public readonly onProcessData: Event<IProcessDataEvent> = this._onProcessData.event;
A
Alex Dima 已提交
76 77 78 79 80 81
	private readonly _onProcessExit = this._register(new Emitter<number | undefined>());
	public readonly onProcessExit: Event<number | undefined> = this._onProcessExit.event;
	public readonly _onProcessReady = this._register(new Emitter<{ pid: number, cwd: string }>());
	public get onProcessReady(): Event<{ pid: number, cwd: string }> { return this._onProcessReady.event; }
	private readonly _onProcessTitleChanged = this._register(new Emitter<string>());
	public readonly onProcessTitleChanged: Event<string> = this._onProcessTitleChanged.event;
A
Alex Dima 已提交
82 83
	private readonly _onProcessOverrideDimensions = this._register(new Emitter<ITerminalDimensionsOverride | undefined>());
	public readonly onProcessOverrideDimensions: Event<ITerminalDimensionsOverride | undefined> = this._onProcessOverrideDimensions.event;
A
Alex Dima 已提交
84 85 86 87 88 89
	private readonly _onProcessResolvedShellLaunchConfig = this._register(new Emitter<IShellLaunchConfig>());
	public get onProcessResolvedShellLaunchConfig(): Event<IShellLaunchConfig> { return this._onProcessResolvedShellLaunchConfig.event; }

	private _startBarrier: Barrier;
	private _remoteTerminalId: number;

A
Alex Dima 已提交
90 91
	private _inReplay = false;

A
Alex Dima 已提交
92 93 94 95 96 97 98
	constructor(
		private readonly _terminalId: number,
		private readonly _shellLaunchConfig: IShellLaunchConfig,
		private readonly _activeWorkspaceRootUri: URI | undefined,
		private readonly _cols: number,
		private readonly _rows: number,
		private readonly _configHelper: ITerminalConfigHelper,
99
		private readonly _isPreconnectionTerminal: boolean,
A
Alex Dima 已提交
100 101 102 103 104 105 106 107
		private readonly _remoteTerminalChannel: RemoteTerminalChannelClient,
		private readonly _remoteAgentService: IRemoteAgentService,
		private readonly _logService: ILogService,
		private readonly _commandService: ICommandService,
	) {
		super();
		this._startBarrier = new Barrier();
		this._remoteTerminalId = 0;
108 109 110 111 112 113

		if (this._isPreconnectionTerminal) {
			// Add a loading title only if this terminal is
			// instantiated before a connection is up and running
			setTimeout(() => this._onProcessTitleChanged.fire(nls.localize('terminal.integrated.starting', "Starting2...")), 0);
		}
A
Alex Dima 已提交
114 115 116 117 118 119 120 121 122 123
	}

	public async start(): Promise<ITerminalLaunchError | undefined> {
		// Fetch the environment to check shell permissions
		const env = await this._remoteAgentService.getEnvironment();
		if (!env) {
			// Extension host processes are only allowed in remote extension hosts currently
			throw new Error('Could not fetch remote environment');
		}

A
Alex Dima 已提交
124 125
		if (!this._shellLaunchConfig.remoteAttach) {
			const isWorkspaceShellAllowed = this._configHelper.checkWorkspaceShellPermissions(env.os);
A
Alex Dima 已提交
126

A
Alex Dima 已提交
127 128 129 130 131 132 133
			const shellLaunchConfigDto: IShellLaunchConfigDto = {
				name: this._shellLaunchConfig.name,
				executable: this._shellLaunchConfig.executable,
				args: this._shellLaunchConfig.args,
				cwd: this._shellLaunchConfig.cwd,
				env: this._shellLaunchConfig.env
			};
A
Alex Dima 已提交
134

A
Alex Dima 已提交
135
			this._logService.trace('Spawning remote agent process', { terminalId: this._terminalId, shellLaunchConfigDto });
A
Alex Dima 已提交
136

A
Alex Dima 已提交
137 138 139
			const result = await this._remoteTerminalChannel.createTerminalProcess(
				shellLaunchConfigDto,
				this._activeWorkspaceRootUri,
R
Rob Lourens 已提交
140
				!this._shellLaunchConfig.isFeatureTerminal,
A
Alex Dima 已提交
141 142 143 144
				this._cols,
				this._rows,
				isWorkspaceShellAllowed,
			);
A
Alex Dima 已提交
145

A
Alex Dima 已提交
146 147 148
			this._remoteTerminalId = result.terminalId;
			this.setupTerminalEventListener();
			this._onProcessResolvedShellLaunchConfig.fire(reviveIShellLaunchConfig(result.resolvedShellLaunchConfig));
A
Alex Dima 已提交
149

A
Alex Dima 已提交
150
			const startResult = await this._remoteTerminalChannel.startTerminalProcess(this._remoteTerminalId);
A
Alex Dima 已提交
151

A
Alex Dima 已提交
152 153 154 155 156 157 158 159
			if (typeof startResult !== 'undefined') {
				// An error occurred
				return startResult;
			}
		} else {
			this._remoteTerminalId = this._shellLaunchConfig.remoteAttach.id;
			this._onProcessReady.fire({ pid: this._shellLaunchConfig.remoteAttach.pid, cwd: this._shellLaunchConfig.remoteAttach.cwd });
			this.setupTerminalEventListener();
A
Alex Dima 已提交
160

A
Alex Dima 已提交
161 162 163
			setTimeout(() => {
				this._onProcessTitleChanged.fire(this._shellLaunchConfig.remoteAttach!.title);
			}, 0);
A
Alex Dima 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176
		}

		this._startBarrier.open();
		return undefined;
	}

	public shutdown(immediate: boolean): void {
		this._startBarrier.wait().then(_ => {
			this._remoteTerminalChannel.shutdownTerminalProcess(this._remoteTerminalId, immediate);
		});
	}

	public input(data: string): void {
A
Alex Dima 已提交
177 178 179 180
		if (this._inReplay) {
			return;
		}

A
Alex Dima 已提交
181 182 183 184 185
		this._startBarrier.wait().then(_ => {
			this._remoteTerminalChannel.sendInputToTerminalProcess(this._remoteTerminalId, data);
		});
	}

A
Alex Dima 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
	private setupTerminalEventListener(): void {
		this._register(this._remoteTerminalChannel.onTerminalProcessEvent(this._remoteTerminalId)(event => {
			switch (event.type) {
				case 'ready':
					return this._onProcessReady.fire({ pid: event.pid, cwd: event.cwd });
				case 'titleChanged':
					return this._onProcessTitleChanged.fire(event.title);
				case 'data':
					return this._onProcessData.fire({ data: event.data, sync: false });
				case 'replay': {
					try {
						this._inReplay = true;

						for (const e of event.events) {
							if (e.cols !== 0 || e.rows !== 0) {
								// never override with 0x0 as that is a marker for an unknown initial size
								this._onProcessOverrideDimensions.fire({ cols: e.cols, rows: e.rows, forceExactSize: true });
							}
							this._onProcessData.fire({ data: e.data, sync: true });
						}
					} finally {
						this._inReplay = false;
					}

					// remove size override
					this._onProcessOverrideDimensions.fire(undefined);

					return;
				}
				case 'exit':
					return this._onProcessExit.fire(event.exitCode);
				case 'execCommand':
					return this._execCommand(event);
				case 'orphan?': {
					this._remoteTerminalChannel.orphanQuestionReply(this._remoteTerminalId);
					return;
				}
			}
		}));
	}

A
Alex Dima 已提交
227
	public resize(cols: number, rows: number): void {
A
Alex Dima 已提交
228 229 230
		if (this._inReplay) {
			return;
		}
A
Alex Dima 已提交
231
		this._startBarrier.wait().then(_ => {
A
Alex Dima 已提交
232

A
Alex Dima 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
			this._remoteTerminalChannel.resizeTerminalProcess(this._remoteTerminalId, cols, rows);
		});
	}

	public async getInitialCwd(): Promise<string> {
		await this._startBarrier.wait();
		return this._remoteTerminalChannel.getTerminalInitialCwd(this._remoteTerminalId);
	}

	public async getCwd(): Promise<string> {
		await this._startBarrier.wait();
		return this._remoteTerminalChannel.getTerminalCwd(this._remoteTerminalId);
	}

	/**
	 * TODO@roblourens I don't think this does anything useful in the EH and the value isn't used
	 */
	public async getLatency(): Promise<number> {
		return 0;
	}

	private async _execCommand(event: IRemoteTerminalProcessExecCommandEvent): Promise<void> {
		const reqId = event.reqId;
		const commandArgs = event.commandArgs.map(arg => revive(arg));
		try {
			const result = await this._commandService.executeCommand(event.commandId, ...commandArgs);
			this._remoteTerminalChannel.sendCommandResultToTerminalProcess(this._remoteTerminalId, reqId, false, result);
		} catch (err) {
			this._remoteTerminalChannel.sendCommandResultToTerminalProcess(this._remoteTerminalId, reqId, true, err);
		}
	}
}

function reviveIShellLaunchConfig(dto: IShellLaunchConfigDto): IShellLaunchConfig {
	return {
		name: dto.name,
		executable: dto.executable,
		args: dto.args,
		cwd: (
			(typeof dto.cwd === 'string' || typeof dto.cwd === 'undefined')
				? dto.cwd
				: URI.revive(dto.cwd)
		),
		env: dto.env,
		hideFromUser: dto.hideFromUser
	};
}

registerSingleton(IRemoteTerminalService, RemoteTerminalService);