forked from louislam/dockge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathterminal.ts
305 lines (256 loc) · 9.11 KB
/
terminal.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
import { DockgeServer } from "./dockge-server";
import * as os from "node:os";
import * as pty from "@homebridge/node-pty-prebuilt-multiarch";
import { LimitQueue } from "./utils/limit-queue";
import { DockgeSocket } from "./util-server";
import {
allowedCommandList, allowedRawKeys,
PROGRESS_TERMINAL_ROWS,
TERMINAL_COLS,
TERMINAL_ROWS
} from "../common/util-common";
import { sync as commandExistsSync } from "command-exists";
import { log } from "./log";
/**
* Terminal for running commands, no user interaction
*/
export class Terminal {
protected static terminalMap : Map<string, Terminal> = new Map();
protected _ptyProcess? : pty.IPty;
protected server : DockgeServer;
protected buffer : LimitQueue<string> = new LimitQueue(100);
protected _name : string;
protected file : string;
protected args : string | string[];
protected cwd : string;
protected callback? : (exitCode : number) => void;
protected _rows : number = TERMINAL_ROWS;
protected _cols : number = TERMINAL_COLS;
public enableKeepAlive : boolean = false;
protected keepAliveInterval? : NodeJS.Timeout;
protected kickDisconnectedClientsInterval? : NodeJS.Timeout;
protected socketList : Record<string, DockgeSocket> = {};
constructor(server : DockgeServer, name : string, file : string, args : string | string[], cwd : string) {
this.server = server;
this._name = name;
//this._name = "terminal-" + Date.now() + "-" + getCryptoRandomInt(0, 1000000);
this.file = file;
this.args = args;
this.cwd = cwd;
Terminal.terminalMap.set(this.name, this);
}
get rows() {
return this._rows;
}
set rows(rows : number) {
this._rows = rows;
try {
this.ptyProcess?.resize(this.cols, this.rows);
} catch (e) {
if (e instanceof Error) {
log.debug("Terminal", "Failed to resize terminal: " + e.message);
}
}
}
get cols() {
return this._cols;
}
set cols(cols : number) {
this._cols = cols;
log.debug("Terminal", `Terminal cols: ${this._cols}`); // Added to check if cols is being set when changing terminal size.
try {
this.ptyProcess?.resize(this.cols, this.rows);
} catch (e) {
if (e instanceof Error) {
log.debug("Terminal", "Failed to resize terminal: " + e.message);
}
}
}
public start() {
if (this._ptyProcess) {
return;
}
this.kickDisconnectedClientsInterval = setInterval(() => {
for (const socketID in this.socketList) {
const socket = this.socketList[socketID];
if (!socket.connected) {
log.debug("Terminal", "Kicking disconnected client " + socket.id + " from terminal " + this.name);
this.leave(socket);
}
}
}, 60 * 1000);
if (this.enableKeepAlive) {
log.debug("Terminal", "Keep alive enabled for terminal " + this.name);
// Close if there is no clients
this.keepAliveInterval = setInterval(() => {
const numClients = Object.keys(this.socketList).length;
if (numClients === 0) {
log.debug("Terminal", "Terminal " + this.name + " has no client, closing...");
this.close();
} else {
log.debug("Terminal", "Terminal " + this.name + " has " + numClients + " client(s)");
}
}, 60 * 1000);
} else {
log.debug("Terminal", "Keep alive disabled for terminal " + this.name);
}
try {
this._ptyProcess = pty.spawn(this.file, this.args, {
name: this.name,
cwd: this.cwd,
cols: TERMINAL_COLS,
rows: this.rows,
});
// On Data
this._ptyProcess.onData((data) => {
this.buffer.pushItem(data);
for (const socketID in this.socketList) {
const socket = this.socketList[socketID];
socket.emitAgent("terminalWrite", this.name, data);
}
});
// On Exit
this._ptyProcess.onExit(this.exit);
} catch (error) {
if (error instanceof Error) {
clearInterval(this.keepAliveInterval);
log.error("Terminal", "Failed to start terminal: " + error.message);
const exitCode = Number(error.message.split(" ").pop());
this.exit({
exitCode,
});
}
}
}
/**
* Exit event handler
* @param res
*/
protected exit = (res : {exitCode: number, signal?: number | undefined}) => {
for (const socketID in this.socketList) {
const socket = this.socketList[socketID];
socket.emitAgent("terminalExit", this.name, res.exitCode);
}
// Remove all clients
this.socketList = {};
Terminal.terminalMap.delete(this.name);
log.debug("Terminal", "Terminal " + this.name + " exited with code " + res.exitCode);
clearInterval(this.keepAliveInterval);
clearInterval(this.kickDisconnectedClientsInterval);
if (this.callback) {
this.callback(res.exitCode);
}
};
public onExit(callback : (exitCode : number) => void) {
this.callback = callback;
}
public join(socket : DockgeSocket) {
this.socketList[socket.id] = socket;
}
public leave(socket : DockgeSocket) {
delete this.socketList[socket.id];
}
public get ptyProcess() {
return this._ptyProcess;
}
public get name() {
return this._name;
}
/**
* Get the terminal output string
*/
getBuffer() : string {
if (this.buffer.length === 0) {
return "";
}
return this.buffer.join("");
}
close() {
clearInterval(this.keepAliveInterval);
// Send Ctrl+C to the terminal
this.ptyProcess?.write("\x03");
}
/**
* Get a running and non-exited terminal
* @param name
*/
public static getTerminal(name : string) : Terminal | undefined {
return Terminal.terminalMap.get(name);
}
public static getOrCreateTerminal(server : DockgeServer, name : string, file : string, args : string | string[], cwd : string) : Terminal {
// Since exited terminal will be removed from the map, it is safe to get the terminal from the map
let terminal = Terminal.getTerminal(name);
if (!terminal) {
terminal = new Terminal(server, name, file, args, cwd);
}
return terminal;
}
public static exec(server : DockgeServer, socket : DockgeSocket | undefined, terminalName : string, file : string, args : string | string[], cwd : string) : Promise<number> {
return new Promise((resolve, reject) => {
// check if terminal exists
if (Terminal.terminalMap.has(terminalName)) {
reject("Another operation is already running, please try again later.");
return;
}
let terminal = new Terminal(server, terminalName, file, args, cwd);
terminal.rows = PROGRESS_TERMINAL_ROWS;
if (socket) {
terminal.join(socket);
}
terminal.onExit((exitCode : number) => {
resolve(exitCode);
});
terminal.start();
});
}
public static getTerminalCount() {
return Terminal.terminalMap.size;
}
}
/**
* Interactive terminal
* Mainly used for container exec
*/
export class InteractiveTerminal extends Terminal {
public write(input : string) {
this.ptyProcess?.write(input);
}
resetCWD() {
const cwd = process.cwd();
this.ptyProcess?.write(`cd "${cwd}"\r`);
}
}
/**
* User interactive terminal that use bash or powershell with limited commands such as docker, ls, cd, dir
*/
export class MainTerminal extends InteractiveTerminal {
constructor(server : DockgeServer, name : string) {
let shell;
if (os.platform() === "win32") {
if (commandExistsSync("pwsh.exe")) {
shell = "pwsh.exe";
} else {
shell = "powershell.exe";
}
} else {
shell = "bash";
}
super(server, name, shell, [], server.stacksDir);
}
public write(input : string) {
// For like Ctrl + C
if (allowedRawKeys.includes(input)) {
super.write(input);
return;
}
// Check if the command is allowed
const cmdParts = input.split(" ");
const executable = cmdParts[0].trim();
log.debug("console", "Executable: " + executable);
log.debug("console", "Executable length: " + executable.length);
if (!allowedCommandList.includes(executable)) {
throw new Error("Command not allowed.");
}
super.write(input);
}
}