Cleanup shell sessions (#2469)

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton authored and GitHub committed 2021-04-12 09:51:25 +03:00
1 parent 4504a76e6a
commit 743597e2f5
7 files changed
+335 -392

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
export * from "./node-shell-session";
export * from "./local-shell-session";
@@ -0,0 +1,40 @@
import path from "path";
import { helmCli } from "../helm/helm-cli";
import { userStore } from "../../common/user-store";
import { ShellSession } from "./shell-session";
export class LocalShellSession extends ShellSession {
ShellType = "shell";
protected getPathEntries(): string[] {
return [helmCli.getBinaryDir()];
}
public async open() {
const env = await this.getCachedShellEnv();
const shell = env.PTYSHELL;
const args = await this.getShellArgs(shell);
super.open(env.PTYSHELL, args, env);
}
protected async getShellArgs(shell: string): Promise<string[]> {
const helmpath = helmCli.getBinaryDir();
const pathFromPreferences = userStore.preferences.kubectlBinariesPath || this.kubectl.getBundledPath();
const kubectlPathDir = userStore.preferences.downloadKubectlBinaries ? await this.kubectlBinDirP : path.dirname(pathFromPreferences);
switch(path.basename(shell)) {
case "powershell.exe":
return ["-NoExit", "-command", `& {Set-Location $Env:USERPROFILE; $Env:PATH="${helmpath};${kubectlPathDir};$Env:PATH"}`];
case "bash":
return ["--init-file", path.join(await this.kubectlBinDirP, ".bash_set_path")];
case "fish":
return ["--login", "--init-command", `export PATH="${helmpath}:${kubectlPathDir}:$PATH"; export KUBECONFIG="${this.kubeconfigPathP}"`];
case "zsh":
return ["--login"];
default:
return [];
}
}
}
@@ -0,0 +1,108 @@
import * as WebSocket from "ws";
import { v4 as uuid } from "uuid";
import * as k8s from "@kubernetes/client-node";
import { KubeConfig } from "@kubernetes/client-node";
import { Cluster } from "../cluster";
import { ShellOpenError, ShellSession } from "./shell-session";
export class NodeShellSession extends ShellSession {
ShellType = "node-shell";
protected podId = `node-shell-${uuid()}`;
protected kc: KubeConfig;
constructor(socket: WebSocket, cluster: Cluster, protected nodeName: string) {
super(socket, cluster);
}
public async open() {
this.kc = await this.cluster.getProxyKubeconfig();
const shell = await this.kubectl.getPath();
try {
await this.createNodeShellPod();
await this.waitForRunningPod();
} catch (error) {
this.deleteNodeShellPod();
this.sendResponse("Error occurred. ");
throw new ShellOpenError("failed to create node pod", error);
}
const args = ["exec", "-i", "-t", "-n", "kube-system", this.podId, "--", "sh", "-c", "((clear && bash) || (clear && ash) || (clear && sh))"];
const env = await this.getCachedShellEnv();
super.open(shell, args, env);
}
protected createNodeShellPod() {
return this
.kc
.makeApiClient(k8s.CoreV1Api)
.createNamespacedPod("kube-system", {
metadata: {
name: this.podId,
namespace: "kube-system"
},
spec: {
nodeName: this.nodeName,
restartPolicy: "Never",
terminationGracePeriodSeconds: 0,
hostPID: true,
hostIPC: true,
hostNetwork: true,
tolerations: [{
operator: "Exists"
}],
containers: [{
name: "shell",
image: "docker.io/alpine:3.12",
securityContext: {
privileged: true,
},
command: ["nsenter"],
args: ["-t", "1", "-m", "-u", "-i", "-n", "sleep", "14000"]
}],
}
});
}
protected waitForRunningPod(): Promise<void> {
return new Promise((resolve, reject) => {
const watch = new k8s.Watch(this.kc);
watch
.watch(`/api/v1/namespaces/kube-system/pods`,
{},
// callback is called for each received object.
(type, obj) => {
if (obj.metadata.name == this.podId && obj.status.phase === "Running") {
resolve();
}
},
// done callback is called if the watch terminates normally
(err) => {
console.log(err);
reject(err);
}
)
.then(req => {
setTimeout(() => {
console.log("aborting");
req.abort();
}, 2 * 60 * 1000);
})
.catch(err => {
console.log("watch failed");
reject(err);
});
});
}
protected deleteNodeShellPod() {
this
.kc
.makeApiClient(k8s.CoreV1Api)
.deleteNamespacedPod(this.podId, "kube-system");
}
}
+179
View File
@@ -0,0 +1,179 @@
import { Cluster } from "../cluster";
import { Kubectl } from "../kubectl";
import * as WebSocket from "ws";
import shellEnv from "shell-env";
import { app } from "electron";
import { clearKubeconfigEnvVars } from "../utils/clear-kube-env-vars";
import path from "path";
import { isWindows } from "../../common/vars";
import { userStore } from "../../common/user-store";
import * as pty from "node-pty";
import { appEventBus } from "../../common/event-bus";
export class ShellOpenError extends Error {
constructor(message: string, public cause: Error) {
super(`${message}: ${cause}`);
this.name = this.constructor.name;
Error.captureStackTrace(this);
}
}
export abstract class ShellSession {
abstract ShellType: string;
static shellEnvs: Map<string, Record<string, any>> = new Map();
protected kubectl: Kubectl;
protected running = false;
protected shellProcess: pty.IPty;
protected kubectlBinDirP: Promise<string>;
protected kubeconfigPathP: Promise<string>;
protected get cwd(): string | undefined {
return this.cluster.preferences?.terminalCWD;
}
constructor(protected websocket: WebSocket, protected cluster: Cluster) {
this.kubectl = new Kubectl(cluster.version);
this.kubeconfigPathP = this.cluster.getProxyKubeconfigPath();
this.kubectlBinDirP = this.kubectl.binDir();
}
open(shell: string, args: string[], env: Record<string, any>): void {
this.shellProcess = pty.spawn(shell, args, {
cols: 80,
cwd: this.cwd || env.HOME,
env,
name: "xterm-256color",
rows: 30,
});
this.running = true;
this.shellProcess.onData(data => this.sendResponse(data));
this.shellProcess.onExit(({ exitCode }) => {
this.running = false;
if (exitCode > 0) {
this.sendResponse("Terminal will auto-close in 15 seconds ...");
setTimeout(() => this.exit(), 15 * 1000);
} else {
this.exit();
}
});
this.websocket
.on("message", (data: string) => {
if (!this.running) {
return;
}
const message = Buffer.from(data.slice(1, data.length), "base64").toString();
switch (data[0]) {
case "0":
this.shellProcess.write(message);
break;
case "4":
const { Width, Height } = JSON.parse(message);
this.shellProcess.resize(Width, Height);
break;
}
})
.on("close", () => {
if (this.running) {
try {
process.kill(this.shellProcess.pid);
} catch (e) {
}
}
this.running = false;
});
appEventBus.emit({ name: this.ShellType, action: "open" });
}
protected getPathEntries(): string[] {
return [];
}
protected async getCachedShellEnv() {
const { id: clusterId } = this.cluster;
let env = ShellSession.shellEnvs.get(clusterId);
if (!env) {
env = await this.getShellEnv();
ShellSession.shellEnvs.set(clusterId, env);
} else {
// refresh env in the background
this.getShellEnv().then((shellEnv: any) => {
ShellSession.shellEnvs.set(clusterId, shellEnv);
});
}
return env;
}
protected async getShellEnv() {
const env = clearKubeconfigEnvVars(JSON.parse(JSON.stringify(await shellEnv())));
const pathStr = [...this.getPathEntries(), await this.kubectlBinDirP, process.env.PATH].join(path.delimiter);
const shell = userStore.preferences.shell || process.env.SHELL || process.env.PTYSHELL;
delete env.DEBUG; // don't pass DEBUG into shells
if (isWindows) {
env.SystemRoot = process.env.SystemRoot;
env.PTYSHELL = shell || "powershell.exe";
env.PATH = pathStr;
env.LENS_SESSION = "true";
env.WSLENV = [
process.env.WSLENV,
"KUBECONFIG/up:LENS_SESSION/u"
]
.filter(Boolean)
.join(":");
} else if (shell !== undefined) {
env.PTYSHELL = shell;
env.PATH = pathStr;
} else {
env.PTYSHELL = ""; // blank runs the system default shell
}
if (path.basename(env.PTYSHELL) === "zsh") {
env.OLD_ZDOTDIR = env.ZDOTDIR || env.HOME;
env.ZDOTDIR = this.kubectlBinDirP;
env.DISABLE_AUTO_UPDATE = "true";
}
env.PTYPID = process.pid.toString();
env.KUBECONFIG = await this.kubeconfigPathP;
env.TERM_PROGRAM = app.getName();
env.TERM_PROGRAM_VERSION = app.getVersion();
if (this.cluster.preferences.httpsProxy) {
env.HTTPS_PROXY = this.cluster.preferences.httpsProxy;
}
env.NO_PROXY = [
"localhost",
"127.0.0.1",
env.NO_PROXY
]
.filter(Boolean)
.join();
return env;
}
protected exit(code = 1000) {
if (this.websocket.readyState == this.websocket.OPEN) {
this.websocket.close(code);
}
}
protected sendResponse(msg: string) {
this.websocket.send(`1${Buffer.from(msg).toString("base64")}`);
}
}