This repository has been archived by the owner on Apr 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 110
/
remote-terminal-widget.ts
380 lines (324 loc) · 12.3 KB
/
remote-terminal-widget.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
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
227
228
229
230
231
232
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/* eslint-disable header/header */
/*
* Copyright (C) 2017 TypeFox and others.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*/
// Copied from 'terminal-widget.ts' with some modifications, CQ: https://dev.eclipse.org/ipzilla/show_bug.cgi?id=16269
import {
ATTACH_TERMINAL_SEGMENT,
RemoteTerminalServerProxy,
RemoteTerminalWatcher,
} from '../server-definition/remote-terminal-protocol';
import { IBaseTerminalServer, TerminalProcessInfo } from '@theia/terminal/lib/common/base-terminal-protocol';
import { OutputChannel, OutputChannelManager } from '@theia/output/lib/common/output-channel';
import { inject, injectable, postConstruct } from 'inversify';
import { Deferred } from '@theia/core/lib/common/promise-util';
import { Disposable } from 'vscode-jsonrpc';
import { IDisposable } from 'xterm';
import { Message } from '@theia/core/lib/browser';
import { MessageService } from '@theia/core/lib/common';
import ReconnectingWebSocket from 'reconnecting-websocket';
import { RemoteWebSocketConnectionProvider } from '../server-definition/remote-connection';
import { TerminalProxyCreatorProvider } from '../server-definition/terminal-proxy-creator';
import { TerminalWidgetImpl } from '@theia/terminal/lib/browser/terminal-widget-impl';
import { TerminalWidgetOptions } from '@theia/terminal/lib/browser/base/terminal-widget';
import URI from '@theia/core/lib/common/uri';
export const REMOTE_TERMINAL_TARGET_SCOPE = 'remote-terminal';
export const REMOTE_TERMINAL_WIDGET_FACTORY_ID = 'remote-terminal';
export const RemoteTerminalWidgetOptions = Symbol('RemoteTerminalWidgetOptions');
export interface RemoteTerminalWidgetOptions extends Partial<TerminalWidgetOptions> {
machineName: string;
workspaceId: string;
closeWidgetOnExitOrError: boolean;
endpoint: string;
}
export interface RemoteTerminalWidgetFactoryOptions extends Partial<TerminalWidgetOptions> {
/* a unique string per terminal */
created: string;
}
@injectable()
export class RemoteTerminalWidget extends TerminalWidgetImpl {
public static OUTPUT_CHANNEL_NAME = 'remote-terminal';
protected termServer: RemoteTerminalServerProxy | undefined;
protected waitForRemoteConnection:
| Deferred<ReconnectingWebSocket>
| undefined = new Deferred<ReconnectingWebSocket>();
@inject('TerminalProxyCreatorProvider')
protected readonly termProxyCreatorProvider: TerminalProxyCreatorProvider;
@inject(RemoteWebSocketConnectionProvider)
protected readonly remoteWebSocketConnectionProvider: RemoteWebSocketConnectionProvider;
@inject(RemoteTerminalWatcher)
protected readonly remoteTerminalWatcher: RemoteTerminalWatcher;
@inject(RemoteTerminalWidgetOptions)
options: RemoteTerminalWidgetOptions;
@inject(MessageService)
protected readonly messageService: MessageService;
@inject(OutputChannelManager)
protected readonly outputChannelManager: OutputChannelManager;
private socket: ReconnectingWebSocket;
protected channel: OutputChannel;
protected closeOutputConnectionDisposable: Disposable;
protected processGone: boolean;
@postConstruct()
protected init(): void {
super.init();
this.channel = this.outputChannelManager.getChannel(RemoteTerminalWidget.OUTPUT_CHANNEL_NAME);
this.toDispose.push(
this.remoteTerminalWatcher.onTerminalExecExit(exitEvent => {
if (this.terminalId === exitEvent.id) {
this.processGone = true;
if (this.options.closeWidgetOnExitOrError) {
this.dispose();
} else {
this.closeOutputConnectionDisposable.dispose();
}
this.onTermDidClose.fire(this);
this.onTermDidClose.dispose();
}
})
);
this.toDispose.push(
this.term.onTitleChange((title: string) => {
if (this.options.useServerTitle) {
this.title.label = this.options.machineName + ': ' + title;
}
})
);
const badDefaultLoginErr = 'command terminated with exit code 126';
const missedPrivilegesErr = 'cannot create resource "pods/exec"';
this.toDispose.push(
this.remoteTerminalWatcher.onTerminalExecError(errEvent => {
if (this.terminalId === errEvent.id) {
this.processGone = true;
if (this.options.closeWidgetOnExitOrError) {
this.dispose();
} else {
this.closeOutputConnectionDisposable.dispose();
}
this.onTermDidClose.fire(this);
this.onTermDidClose.dispose();
this.logger.error(`Terminal error: ${errEvent.stack}`);
this.channel.appendLine(errEvent.stack);
let reason = '';
if (errEvent.stack.indexOf(badDefaultLoginErr) !== -1) {
reason = 'Possible reason is terminal cannot open default login shell. ';
} else if (errEvent.stack.indexOf(missedPrivilegesErr) !== -1) {
reason = 'Possible reason is workspace service account lacks some privileges. ';
}
reason += 'See more in "Output".';
this.messageService.error(`Terminal failed to connect. ${reason}`);
}
})
);
}
async start(id?: number): Promise<number> {
try {
if (!this.termServer) {
const termProxyCreator = await this.termProxyCreatorProvider();
this.termServer = termProxyCreator.create();
this.toDispose.push(
this.termServer.onDidCloseConnection(() => {
const disposable = this.termServer!.onDidOpenConnection(async () => {
disposable.dispose();
this.waitForRemoteConnection = new Deferred<ReconnectingWebSocket>();
await this.reconnectTerminalProcess();
});
this.toDispose.push(disposable);
})
);
}
} catch (err) {
throw new Error('Failed to create terminal server proxy. Cause: ' + err);
}
this._terminalId = typeof id !== 'number' ? await this.createTerminal() : await this.attachTerminal(id);
this.connectTerminalProcess();
await this.waitForRemoteConnection!.promise;
// Some delay need to attach exec. If we send resize earlier this size will be skipped.
setTimeout(async () => {
this.resizeTerminalProcess();
}, 100);
if (IBaseTerminalServer.validateId(this.terminalId)) {
this.onDidOpenEmitter.fire(undefined);
return this.terminalId;
}
throw new Error('Failed to start terminal' + (id ? ` for id: ${id}.` : '.'));
}
protected async reconnectTerminalProcess(): Promise<void> {
if (typeof this.terminalId === 'number') {
let termId;
try {
termId = await this.termServer!.check({ id: this.terminalId });
} catch (error) {
termId = -1;
}
if (!IBaseTerminalServer.validateId(termId)) {
return;
}
await this.start(this.terminalId);
}
}
protected async connectTerminalProcess(): Promise<void> {
if (typeof this.terminalId !== 'number') {
return;
}
this.toDisposeOnConnect.dispose();
await this.connectSocket(this.terminalId);
}
get cwd(): Promise<URI> {
// It is not possible to retrieve current working directory of a terminal process which is run via exec mechanism.
// But we have to override this method to avoid requesting wrong terminal backend.
// Returning empty cwd will result in some features not working in some cases (for example opening files in editor by
// relative link from terminal with exec backend), however it will prevent some errors.
return Promise.resolve(new URI());
}
get processId(): Promise<number> {
return (async () => {
if (!IBaseTerminalServer.validateId(this.terminalId)) {
throw new Error('terminal is not started');
}
// Exec server side unable to return real process pid. This information is encapsulated.
return this.terminalId;
})();
}
get processInfo(): Promise<TerminalProcessInfo> {
return (async () => {
if (!IBaseTerminalServer.validateId(this.terminalId)) {
throw new Error('terminal is not started');
}
return { executable: '/bin/bash', arguments: [] };
})();
}
protected async connectSocket(id: number): Promise<void> {
if (this.socket) {
this.resolveRemoteConnection();
return Promise.resolve();
}
this.socket = this.createWebSocket(id.toString());
const sendListener = (data: string) => this.socket.send(data);
let onDataDisposeHandler: IDisposable;
this.socket.onopen = () => {
this.term.reset();
this.resolveRemoteConnection();
onDataDisposeHandler = this.term.onData(sendListener);
this.socket.onmessage = ev => this.write(ev.data);
this.closeOutputConnectionDisposable = Disposable.create(() => {
onDataDisposeHandler.dispose();
this.socket.close();
});
this.toDispose.push(this.closeOutputConnectionDisposable);
return Promise.resolve();
};
this.socket.onerror = err => {
if (onDataDisposeHandler) {
onDataDisposeHandler.dispose();
}
return Promise.resolve();
};
this.socket.onclose = code => {
if (onDataDisposeHandler) {
onDataDisposeHandler.dispose();
}
return Promise.resolve();
};
}
protected createWebSocket(pid: string): ReconnectingWebSocket {
const url = new URI(this.options.endpoint).resolve(ATTACH_TERMINAL_SEGMENT).resolve(this.terminalId + '');
return new ReconnectingWebSocket(url.toString(true), undefined, {
maxReconnectionDelay: 10000,
minReconnectionDelay: 1000,
reconnectionDelayGrowFactor: 1.3,
connectionTimeout: 10000,
maxRetries: Infinity,
debug: false,
});
}
protected async attachTerminal(id: number): Promise<number> {
let termId;
try {
termId = await this.termServer!.check({ id: id });
} catch (error) {
termId = -1;
}
if (IBaseTerminalServer.validateId(termId) || this.kind !== 'user') {
return termId;
}
this.logger.error(
`Error attaching to terminal id ${id}, the terminal is most likely gone. Starting up a new terminal instead.`
);
return this.createTerminal();
}
protected async createTerminal(): Promise<number> {
const cols = this.term.cols;
const rows = this.term.rows;
let cmd: string[] = [];
if (this.options.shellPath) {
cmd = [this.options.shellPath, ...(this.options.shellArgs || [])];
}
const machineExec = {
identifier: {
machineName: this.options.machineName,
workspaceId: this.options.workspaceId,
},
cmd: cmd,
cwd: this.options.cwd,
cols,
rows,
tty: true,
};
const termId = await this.termServer!.create(machineExec);
if (IBaseTerminalServer.validateId(termId)) {
return termId;
}
throw new Error('Error creating terminal widget');
}
protected resizeTerminalProcess(): void {
if (this.processGone) {
return;
}
if (!IBaseTerminalServer.validateId(this.terminalId) && !this.terminalService.getById(this.id)) {
return;
}
const cols = this.term.cols;
const rows = this.term.rows;
if (this.termServer && this.termServer.resize) {
this.termServer.resize({ id: this.terminalId, cols, rows });
}
}
sendText(text: string): void {
if (this.waitForRemoteConnection) {
this.waitForRemoteConnection.promise.then(socket => socket.send(text));
}
}
protected onCloseRequest(msg: Message): void {
this.closeOnDispose = true;
super.onCloseRequest(msg);
}
dispose(): void {
if (!this.closeOnDispose || !this.options.attributes || !this.options.attributes.interruptProcessOnClose) {
super.dispose();
return;
}
this.interruptProcess().then(() => {
super.dispose();
});
}
private resolveRemoteConnection(): void {
if (this.waitForRemoteConnection) {
this.waitForRemoteConnection.resolve(this.socket);
}
}
private async interruptProcess(): Promise<void> {
try {
const termId = await this.termServer!.check({ id: this.terminalId });
if (!IBaseTerminalServer.validateId(termId)) {
return;
}
if (this.waitForRemoteConnection) {
const socket = await this.waitForRemoteConnection.promise;
socket.send('\x03');
}
} catch (error) {}
}
}