Close terminal if there is no clients connecting

This commit is contained in:
Louis Lam 2023-11-17 16:03:52 +08:00
parent 8c4004f32d
commit fe6735824c
2 changed files with 30 additions and 1 deletions

View file

@ -30,6 +30,7 @@ import { Cron } from "croner";
import gracefulShutdown from "http-graceful-shutdown"; import gracefulShutdown from "http-graceful-shutdown";
import User from "./models/user"; import User from "./models/user";
import childProcess from "child_process"; import childProcess from "child_process";
import { Terminal } from "./terminal";
export class DockgeServer { export class DockgeServer {
app : Express; app : Express;
@ -230,6 +231,11 @@ export class DockgeServer {
}); });
if (isDev) {
setInterval(() => {
log.debug("terminal", "Terminal count: " + Terminal.getTerminalCount());
}, 10000);
}
} }
async afterLogin(socket : DockgeSocket, user : User) { async afterLogin(socket : DockgeSocket, user : User) {

View file

@ -34,6 +34,8 @@ export class Terminal {
protected _rows : number = TERMINAL_ROWS; protected _rows : number = TERMINAL_ROWS;
protected _cols : number = TERMINAL_COLS; protected _cols : number = TERMINAL_COLS;
protected keepAliveInterval? : NodeJS.Timeout;
constructor(server : DockgeServer, name : string, file : string, args : string | string[], cwd : string) { constructor(server : DockgeServer, name : string, file : string, args : string | string[], cwd : string) {
this.server = server; this.server = server;
this._name = name; this._name = name;
@ -101,10 +103,26 @@ export class Terminal {
Terminal.terminalMap.delete(this.name); Terminal.terminalMap.delete(this.name);
log.debug("Terminal", "Terminal " + this.name + " exited with code " + res.exitCode); log.debug("Terminal", "Terminal " + this.name + " exited with code " + res.exitCode);
clearInterval(this.keepAliveInterval);
if (this.callback) { if (this.callback) {
this.callback(res.exitCode); this.callback(res.exitCode);
} }
}); });
// Close if there is no clients
this.keepAliveInterval = setInterval(() => {
const clients = this.server.io.sockets.adapter.rooms.get(this.name);
const numClients = clients ? clients.size : 0;
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);
} }
public onExit(callback : (exitCode : number) => void) { public onExit(callback : (exitCode : number) => void) {
@ -138,7 +156,8 @@ export class Terminal {
} }
close() { close() {
this._ptyProcess?.kill(); // Send Ctrl+C to the terminal
this.ptyProcess?.write("\x03");
} }
/** /**
@ -173,6 +192,10 @@ export class Terminal {
terminal.start(); terminal.start();
}); });
} }
public static getTerminalCount() {
return Terminal.terminalMap.size;
}
} }
/** /**