mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
make more injectable for testing
Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
1 parent
62af94bb2d
commit
28227c923d
30 files changed
+1349
-273
No files matched your search
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import type { Stats } from "fs";
|
||||
import fsInjectable from "./fs.injectable";
|
||||
|
||||
export type Stat = (path: string) => Promise<Stats>;
|
||||
|
||||
const statInjectable = getInjectable({
|
||||
id: "stat",
|
||||
instantiate: (di): Stat => di.inject(fsInjectable).stat,
|
||||
});
|
||||
|
||||
export default statInjectable;
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import { computed } from "mobx";
|
||||
import userStoreInjectable from "./user-store.injectable";
|
||||
|
||||
const resolvedShellInjectable = getInjectable({
|
||||
id: "resolved-shell",
|
||||
instantiate: (di) => {
|
||||
const store = di.inject(userStoreInjectable);
|
||||
|
||||
return computed(() => store.shell || process.env.SHELL || process.env.PTYSHELL);
|
||||
},
|
||||
});
|
||||
|
||||
export default resolvedShellInjectable;
|
||||
@@ -102,10 +102,6 @@ export class UserStore extends BaseStore<UserStoreModel> /* implements UserStore
|
||||
return semver.gt(getAppVersion(), this.lastSeenAppVersion);
|
||||
}
|
||||
|
||||
@computed get resolvedShell(): string | undefined {
|
||||
return this.shell || process.env.SHELL || process.env.PTYSHELL;
|
||||
}
|
||||
|
||||
startMainReactions() {
|
||||
// open at system start-up
|
||||
reaction(() => this.openAtLogin, openAtLogin => {
|
||||
|
||||
@@ -4,22 +4,26 @@
|
||||
*/
|
||||
|
||||
export type Disposer = () => void;
|
||||
|
||||
interface Extendable<T> {
|
||||
push(...vals: T[]): void;
|
||||
export interface LibraryDisposers {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export type ExtendableDisposer = Disposer & Extendable<Disposer>;
|
||||
export interface ExtendableDisposer {
|
||||
(): void;
|
||||
push(...disposers: (Disposer | LibraryDisposers)[]): void;
|
||||
}
|
||||
|
||||
export function disposer(...args: (Disposer | undefined | null)[]): ExtendableDisposer {
|
||||
const res = () => {
|
||||
args.forEach(dispose => dispose?.());
|
||||
export function disposer(...args: (Disposer | LibraryDisposers | undefined | null)[]): ExtendableDisposer {
|
||||
return Object.assign(() => {
|
||||
args.forEach(d => {
|
||||
if (typeof d === "function") {
|
||||
d();
|
||||
} else if (d) {
|
||||
d.dispose();
|
||||
}
|
||||
});
|
||||
args.length = 0;
|
||||
};
|
||||
|
||||
res.push = (...vals: Disposer[]) => {
|
||||
args.push(...vals);
|
||||
};
|
||||
|
||||
return res;
|
||||
}, {
|
||||
push: (...vals) => args.push(...vals),
|
||||
} as Pick<ExtendableDisposer, "push">);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import configurePackages from "./common/configure-packages";
|
||||
import { configure } from "mobx";
|
||||
import { setImmediate } from "timers";
|
||||
import { TextEncoder, TextDecoder as TextDecoderNode } from "util";
|
||||
import ResizeObserver from "resize-observer-polyfill";
|
||||
|
||||
// setup default configuration for external npm-packages
|
||||
configurePackages();
|
||||
@@ -36,3 +37,18 @@ process.on("unhandledRejection", (err: any) => {
|
||||
|
||||
global.TextEncoder = TextEncoder;
|
||||
global.TextDecoder = TextDecoderNode as unknown as typeof TextDecoder;
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
value: jest.fn().mockImplementation(query => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: jest.fn(), // Deprecated
|
||||
removeListener: jest.fn(), // Deprecated
|
||||
addEventListener: jest.fn(),
|
||||
removeEventListener: jest.fn(),
|
||||
dispatchEvent: jest.fn(),
|
||||
})),
|
||||
});
|
||||
|
||||
global.ResizeObserver = ResizeObserver;
|
||||
@@ -101,6 +101,9 @@ import { registerMobX } from "@ogre-tools/injectable-extension-for-mobx";
|
||||
import electronInjectable from "./utils/resolve-system-proxy/electron.injectable";
|
||||
import type { HotbarStore } from "../common/hotbars/store";
|
||||
import focusApplicationInjectable from "./electron-app/features/focus-application.injectable";
|
||||
import getValidCwdInjectable from "./shell-session/get-valid-cwd.injectable";
|
||||
import getCachedShellEnvInjectable from "./shell-session/get-cached-shell-env.injectable";
|
||||
import spawnPtyInjectable from "./shell-session/spawn-pty.injectable";
|
||||
|
||||
export function getDiForUnitTesting(opts: { doGeneralOverrides?: boolean } = {}) {
|
||||
const {
|
||||
@@ -158,6 +161,16 @@ export function getDiForUnitTesting(opts: { doGeneralOverrides?: boolean } = {})
|
||||
di.override(applicationMenuInjectable, () => ({ start: () => {}, stop: () => {} }));
|
||||
|
||||
di.override(periodicalCheckForUpdatesInjectable, () => ({ start: () => {}, stop: () => {}, started: false }));
|
||||
di.override(getValidCwdInjectable, () => () => Promise.resolve("/some/valid/cwd"));
|
||||
di.override(getCachedShellEnvInjectable, (di) => ({ cluster }) => Promise.resolve({
|
||||
NO_PROXY: "localhost,127.0.0.1",
|
||||
TERM_PROGRAM: di.inject(appNameInjectable),
|
||||
TERM_PROGRAM_VERSION: di.inject(appVersionInjectable),
|
||||
KUBECONFIG: `/some/proxy/kubeconfig/${cluster.id}`,
|
||||
PTYPID: "12345",
|
||||
PTYSHELL: "zsh",
|
||||
PATH: process.env.PATH,
|
||||
}));
|
||||
|
||||
overrideFunctionalInjectables(di, [
|
||||
getHelmChartInjectable,
|
||||
@@ -175,6 +188,7 @@ export function getDiForUnitTesting(opts: { doGeneralOverrides?: boolean } = {})
|
||||
readJsonFileInjectable,
|
||||
readFileInjectable,
|
||||
execFileInjectable,
|
||||
spawnPtyInjectable,
|
||||
]);
|
||||
|
||||
// TODO: Remove usages of globally exported appEventBus to get rid of this
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
|
||||
const cachedShellEnvInjectable = getInjectable({
|
||||
id: "cached-shell-env",
|
||||
instantiate: () => new Map<string, Record<string, string | undefined>>(),
|
||||
});
|
||||
|
||||
export default cachedShellEnvInjectable;
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import type { IPty } from "node-pty";
|
||||
import loggerInjectable from "../../common/logger.injectable";
|
||||
import { getOrInsertWith } from "../../renderer/utils";
|
||||
import shellProcessesInjectable from "./shell-processes.injectable";
|
||||
import spawnPtyInjectable from "./spawn-pty.injectable";
|
||||
|
||||
export interface EnsuredShellProcess {
|
||||
shellProcess: IPty;
|
||||
resume: boolean;
|
||||
cleanup: () => void;
|
||||
}
|
||||
export interface EnsureShellProcessArgs {
|
||||
shell: string;
|
||||
args: string[];
|
||||
env: Record<string, string | undefined>;
|
||||
cwd: string;
|
||||
terminalId: string;
|
||||
}
|
||||
export type EnsureShellProcess = (args: EnsureShellProcessArgs) => EnsuredShellProcess;
|
||||
|
||||
const ensureShellProcessInjectable = getInjectable({
|
||||
id: "ensure-shell-process",
|
||||
instantiate: (di): EnsureShellProcess => {
|
||||
const shellProcesses = di.inject(shellProcessesInjectable);
|
||||
const logger = di.inject(loggerInjectable);
|
||||
const spawnPty = di.inject(spawnPtyInjectable);
|
||||
|
||||
return ({ shell, args, env, cwd, terminalId } ) => {
|
||||
const resume = shellProcesses.has(terminalId);
|
||||
const shellProcess = getOrInsertWith(shellProcesses, terminalId, () => (
|
||||
spawnPty(shell, args, {
|
||||
rows: 30,
|
||||
cols: 80,
|
||||
cwd,
|
||||
env: env as Record<string, string>,
|
||||
name: "xterm-256color",
|
||||
// TODO: Something else is broken here so we need to force the use of winPty on windows
|
||||
useConpty: false,
|
||||
})
|
||||
));
|
||||
|
||||
logger.info(`[SHELL-SESSION]: PTY for ${terminalId} is ${resume ? "resumed" : "started"} with PID=${shellProcess.pid}`);
|
||||
|
||||
return {
|
||||
shellProcess,
|
||||
resume,
|
||||
cleanup: () => {
|
||||
shellProcess.kill();
|
||||
shellProcesses.delete(terminalId);
|
||||
},
|
||||
};
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export default ensureShellProcessInjectable;
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import cachedShellEnvInjectable from "./cached-shell-env.injectable";
|
||||
import type { GetShellEnv } from "./get-shell-env.injectable";
|
||||
import getShellEnvInjectable from "./get-shell-env.injectable";
|
||||
|
||||
const getCachedShellEnvInjectable = getInjectable({
|
||||
id: "get-cached-shell-env",
|
||||
instantiate: (di): GetShellEnv => {
|
||||
const cachedShellEnv = di.inject(cachedShellEnvInjectable);
|
||||
const getShellEnv = di.inject(getShellEnvInjectable);
|
||||
|
||||
return async (args) => {
|
||||
const { id: clusterId } = args.cluster;
|
||||
|
||||
let env = cachedShellEnv.get(clusterId);
|
||||
|
||||
if (!env) {
|
||||
env = await getShellEnv(args);
|
||||
cachedShellEnv.set(clusterId, env);
|
||||
} else {
|
||||
// refresh env in the background
|
||||
getShellEnv(args).then((shellEnv) => {
|
||||
cachedShellEnv.set(clusterId, shellEnv);
|
||||
});
|
||||
}
|
||||
|
||||
return env;
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export default getCachedShellEnvInjectable;
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import path from "path";
|
||||
import type { Cluster } from "../../common/cluster/cluster";
|
||||
import appVersionInjectable from "../../common/get-configuration-file-model/app-version/app-version.injectable";
|
||||
import resolvedShellInjectable from "../../common/user-store/resolved-shell.injectable";
|
||||
import isWindowsInjectable from "../../common/vars/is-windows.injectable";
|
||||
import appNameInjectable from "../app-paths/app-name/app-name.injectable";
|
||||
import { clearKubeconfigEnvVars } from "../utils/clear-kube-env-vars";
|
||||
import shellEnvInjectable from "../utils/shell-env.injectable";
|
||||
|
||||
export interface GetShellEnvArgs {
|
||||
cluster: Cluster;
|
||||
initialPathEntries: string[];
|
||||
kubectlBinDirP: Promise<string>;
|
||||
kubeconfigPathP: Promise<string>;
|
||||
}
|
||||
export type GetShellEnv = (args: GetShellEnvArgs) => Promise<Record<string, string | undefined>>;
|
||||
|
||||
const getShellEnvInjectable = getInjectable({
|
||||
id: "get-shell-env",
|
||||
instantiate: (di): GetShellEnv => {
|
||||
const isWindows = di.inject(isWindowsInjectable);
|
||||
const shellEnv = di.inject(shellEnvInjectable);
|
||||
const resolvedShell = di.inject(resolvedShellInjectable);
|
||||
const appName = di.inject(appNameInjectable);
|
||||
const appVersion = di.inject(appVersionInjectable);
|
||||
|
||||
return async ({ cluster, initialPathEntries, kubeconfigPathP, kubectlBinDirP }) => {
|
||||
const env = clearKubeconfigEnvVars(JSON.parse(JSON.stringify(await shellEnv())));
|
||||
const shell = resolvedShell.get();
|
||||
const initialPATH = [await kubectlBinDirP, ...initialPathEntries, process.env.PATH].join(path.delimiter);
|
||||
|
||||
delete env.DEBUG; // don't pass DEBUG into shells
|
||||
|
||||
if (isWindows) {
|
||||
env.SystemRoot = process.env.SystemRoot;
|
||||
env.PTYSHELL = shell || "powershell.exe";
|
||||
env.PATH = initialPATH;
|
||||
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 = initialPATH;
|
||||
} else {
|
||||
env.PTYSHELL = ""; // blank runs the system default shell
|
||||
}
|
||||
|
||||
if (path.basename(env.PTYSHELL) === "zsh") {
|
||||
env.OLD_ZDOTDIR = env.ZDOTDIR || env.HOME;
|
||||
env.ZDOTDIR = await kubectlBinDirP;
|
||||
env.DISABLE_AUTO_UPDATE = "true";
|
||||
}
|
||||
|
||||
env.PTYPID = process.pid.toString();
|
||||
env.KUBECONFIG = await kubeconfigPathP;
|
||||
env.TERM_PROGRAM = appName;
|
||||
env.TERM_PROGRAM_VERSION = appVersion;
|
||||
|
||||
if (cluster.preferences.httpsProxy) {
|
||||
env.HTTPS_PROXY = cluster.preferences.httpsProxy;
|
||||
}
|
||||
|
||||
env.NO_PROXY = [
|
||||
"localhost",
|
||||
"127.0.0.1",
|
||||
env.NO_PROXY,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join();
|
||||
|
||||
return env;
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export default getShellEnvInjectable;
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import { homedir } from "os";
|
||||
import statInjectable from "../../common/fs/stat.injectable";
|
||||
import isMacInjectable from "../../common/vars/is-mac.injectable";
|
||||
import isWindowsInjectable from "../../common/vars/is-windows.injectable";
|
||||
|
||||
export type GetValidCwd = (cwd: string | undefined, env: Record<string, string | undefined>) => Promise<string>;
|
||||
|
||||
const getValidCwdInjectable = getInjectable({
|
||||
id: "get-valid-cwd",
|
||||
instantiate: (di): GetValidCwd => {
|
||||
const stat = di.inject(statInjectable);
|
||||
const isWindows = di.inject(isWindowsInjectable);
|
||||
const isMac = di.inject(isMacInjectable);
|
||||
|
||||
return async (cwd, env) => {
|
||||
const cwdOptions = [cwd];
|
||||
|
||||
if (isWindows) {
|
||||
cwdOptions.push(
|
||||
env.USERPROFILE,
|
||||
homedir(),
|
||||
"C:\\",
|
||||
);
|
||||
} else {
|
||||
cwdOptions.push(
|
||||
env.HOME,
|
||||
homedir(),
|
||||
);
|
||||
|
||||
if (isMac) {
|
||||
cwdOptions.push("/Users");
|
||||
} else {
|
||||
cwdOptions.push("/home");
|
||||
}
|
||||
}
|
||||
|
||||
for (const potentialCwd of cwdOptions) {
|
||||
if (!potentialCwd) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const stats = await stat(potentialCwd);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
return potentialCwd;
|
||||
}
|
||||
} catch {
|
||||
// ignore error
|
||||
}
|
||||
}
|
||||
|
||||
return "."; // Always valid
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export default getValidCwdInjectable;
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import shellProcessesInjectable from "./shell-processes.injectable";
|
||||
|
||||
const killAllShellProcessesInjectable = getInjectable({
|
||||
id: "kill-all-shell-processes",
|
||||
instantiate: (di) => {
|
||||
const shellProcesses = di.inject(shellProcessesInjectable);
|
||||
|
||||
return () => {
|
||||
for (const shellProcess of shellProcesses.values()) {
|
||||
try {
|
||||
process.kill(shellProcess.pid);
|
||||
} catch {
|
||||
// ignore error
|
||||
}
|
||||
}
|
||||
|
||||
shellProcesses.clear();
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export default killAllShellProcessesInjectable;
|
||||
@@ -6,10 +6,10 @@
|
||||
import path from "path";
|
||||
import { UserStore } from "../../../common/user-store";
|
||||
import type { TerminalShellEnvModify } from "../shell-env-modifier/terminal-shell-env-modify.injectable";
|
||||
import type { ShellSessionArgs } from "../shell-session";
|
||||
import type { ShellSessionArgs, ShellSessionDependencies } from "../shell-session";
|
||||
import { ShellSession } from "../shell-session";
|
||||
|
||||
export interface LocalShellSessionDependencies {
|
||||
export interface LocalShellSessionDependencies extends ShellSessionDependencies {
|
||||
terminalShellEnvModify: TerminalShellEnvModify;
|
||||
readonly baseBundeledBinariesDirectory: string;
|
||||
}
|
||||
@@ -18,7 +18,7 @@ export class LocalShellSession extends ShellSession {
|
||||
ShellType = "shell";
|
||||
|
||||
constructor(protected readonly dependencies: LocalShellSessionDependencies, args: ShellSessionArgs) {
|
||||
super(args);
|
||||
super(dependencies, args);
|
||||
}
|
||||
|
||||
protected getPathEntries(): string[] {
|
||||
|
||||
@@ -6,18 +6,19 @@
|
||||
import { v4 as uuid } from "uuid";
|
||||
import { Watch, CoreV1Api } from "@kubernetes/client-node";
|
||||
import type { KubeConfig } from "@kubernetes/client-node";
|
||||
import type { ShellSessionArgs } from "../shell-session";
|
||||
import type { ShellSessionArgs, ShellSessionDependencies } from "../shell-session";
|
||||
import { ShellOpenError, ShellSession } from "../shell-session";
|
||||
import { get, once } from "lodash";
|
||||
import { Node, NodeApi } from "../../../common/k8s-api/endpoints";
|
||||
import { KubeJsonApi } from "../../../common/k8s-api/kube-json-api";
|
||||
import logger from "../../logger";
|
||||
import { TerminalChannels } from "../../../common/terminal/channels";
|
||||
|
||||
export interface NodeShellSessionArgs extends ShellSessionArgs {
|
||||
nodeName: string;
|
||||
}
|
||||
|
||||
export interface NodeShellSessionDependencies extends ShellSessionDependencies {}
|
||||
|
||||
export class NodeShellSession extends ShellSession {
|
||||
ShellType = "node-shell";
|
||||
|
||||
@@ -26,8 +27,8 @@ export class NodeShellSession extends ShellSession {
|
||||
protected readonly cwd: string | undefined = undefined;
|
||||
protected readonly nodeName: string;
|
||||
|
||||
constructor({ nodeName, ...args }: NodeShellSessionArgs) {
|
||||
super(args);
|
||||
constructor(protected readonly dependencies: NodeShellSessionDependencies, { nodeName, ...args }: NodeShellSessionArgs) {
|
||||
super(dependencies, args);
|
||||
this.nodeName = nodeName;
|
||||
}
|
||||
|
||||
@@ -39,7 +40,7 @@ export class NodeShellSession extends ShellSession {
|
||||
const cleanup = once(() => {
|
||||
coreApi
|
||||
.deleteNamespacedPod(this.podName, "kube-system")
|
||||
.catch(error => logger.warn(`[NODE-SHELL]: failed to remove pod shell`, error));
|
||||
.catch(error => this.dependencies.logger.warn(`[NODE-SHELL]: failed to remove pod shell`, error));
|
||||
});
|
||||
|
||||
this.websocket.once("close", cleanup);
|
||||
@@ -79,7 +80,7 @@ export class NodeShellSession extends ShellSession {
|
||||
|
||||
switch (nodeOs) {
|
||||
default:
|
||||
logger.warn(`[NODE-SHELL-SESSION]: could not determine node OS, falling back with assumption of linux`);
|
||||
this.dependencies.logger.warn(`[NODE-SHELL-SESSION]: could not determine node OS, falling back with assumption of linux`);
|
||||
// fallthrough
|
||||
case "linux":
|
||||
args.push("sh", "-c", "((clear && bash) || (clear && ash) || (clear && sh))");
|
||||
@@ -131,7 +132,7 @@ export class NodeShellSession extends ShellSession {
|
||||
}
|
||||
|
||||
protected waitForRunningPod(kc: KubeConfig): Promise<void> {
|
||||
logger.debug(`[NODE-SHELL]: waiting for ${this.podName} to be running`);
|
||||
this.dependencies.logger.debug(`[NODE-SHELL]: waiting for ${this.podName} to be running`);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
new Watch(kc)
|
||||
@@ -150,19 +151,19 @@ export class NodeShellSession extends ShellSession {
|
||||
},
|
||||
// done callback is called if the watch terminates normally
|
||||
(err) => {
|
||||
logger.error(`[NODE-SHELL]: ${this.podName} was not created in time`);
|
||||
this.dependencies.logger.error(`[NODE-SHELL]: ${this.podName} was not created in time`);
|
||||
reject(err);
|
||||
},
|
||||
)
|
||||
.then(req => {
|
||||
setTimeout(() => {
|
||||
logger.error(`[NODE-SHELL]: aborting wait for ${this.podName}, timing out`);
|
||||
this.dependencies.logger.error(`[NODE-SHELL]: aborting wait for ${this.podName}, timing out`);
|
||||
req.abort();
|
||||
reject("Pod creation timed out");
|
||||
}, 2 * 60 * 1000); // 2 * 60 * 1000
|
||||
})
|
||||
.catch(error => {
|
||||
logger.error(`[NODE-SHELL]: waiting for ${this.podName} failed: ${error}`);
|
||||
this.dependencies.logger.error(`[NODE-SHELL]: waiting for ${this.podName} failed: ${error}`);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import type { IPty } from "node-pty";
|
||||
|
||||
const shellProcessesInjectable = getInjectable({
|
||||
id: "shell-processes",
|
||||
instantiate: () => new Map<string, IPty>(),
|
||||
});
|
||||
|
||||
export default shellProcessesInjectable;
|
||||
@@ -6,19 +6,12 @@
|
||||
import type { Cluster } from "../../common/cluster/cluster";
|
||||
import type { Kubectl } from "../kubectl/kubectl";
|
||||
import type WebSocket from "ws";
|
||||
import { shellEnv } from "../utils/shell-env";
|
||||
import { app } from "electron";
|
||||
import { clearKubeconfigEnvVars } from "../utils/clear-kube-env-vars";
|
||||
import path from "path";
|
||||
import os from "os";
|
||||
import { isMac, isWindows } from "../../common/vars";
|
||||
import { UserStore } from "../../common/user-store";
|
||||
import * as pty from "node-pty";
|
||||
import { appEventBus } from "../../common/app-event-bus/event-bus";
|
||||
import logger from "../logger";
|
||||
import { stat } from "fs/promises";
|
||||
import { getOrInsertWith } from "../../common/utils";
|
||||
import { type TerminalMessage, TerminalChannels } from "../../common/terminal/channels";
|
||||
import type { EnsureShellProcess } from "./ensure-shell-process.injectable";
|
||||
import type { GetValidCwd } from "./get-valid-cwd.injectable";
|
||||
import type { GetShellEnv } from "./get-shell-env.injectable";
|
||||
import type { Logger } from "../../common/logger";
|
||||
|
||||
export class ShellOpenError extends Error {
|
||||
constructor(message: string, options?: ErrorOptions) {
|
||||
@@ -111,27 +104,16 @@ export interface ShellSessionArgs {
|
||||
tabId: string;
|
||||
}
|
||||
|
||||
export interface ShellSessionDependencies {
|
||||
ensureShellProcess: EnsureShellProcess;
|
||||
getValidCwd: GetValidCwd;
|
||||
getCachedShellEnv: GetShellEnv;
|
||||
readonly logger: Logger;
|
||||
}
|
||||
|
||||
export abstract class ShellSession {
|
||||
abstract readonly ShellType: string;
|
||||
|
||||
private static readonly shellEnvs = new Map<string, Record<string, string | undefined>>();
|
||||
private static readonly processes = new Map<string, pty.IPty>();
|
||||
|
||||
/**
|
||||
* Kill all remaining shell backing processes. Should be called when about to
|
||||
* quit
|
||||
*/
|
||||
public static cleanup(): void {
|
||||
for (const shellProcess of this.processes.values()) {
|
||||
try {
|
||||
process.kill(shellProcess.pid);
|
||||
} catch {
|
||||
// ignore error
|
||||
}
|
||||
}
|
||||
|
||||
this.processes.clear();
|
||||
}
|
||||
protected abstract readonly cwd: string | undefined;
|
||||
|
||||
protected running = false;
|
||||
protected readonly kubectlBinDirP: Promise<string>;
|
||||
@@ -141,28 +123,7 @@ export abstract class ShellSession {
|
||||
protected readonly websocket: WebSocket;
|
||||
protected readonly cluster: Cluster;
|
||||
|
||||
protected abstract readonly cwd: string | undefined;
|
||||
|
||||
protected ensureShellProcess(shell: string, args: string[], env: Record<string, string | undefined>, cwd: string): { shellProcess: pty.IPty; resume: boolean } {
|
||||
const resume = ShellSession.processes.has(this.terminalId);
|
||||
const shellProcess = getOrInsertWith(ShellSession.processes, this.terminalId, () => (
|
||||
pty.spawn(shell, args, {
|
||||
rows: 30,
|
||||
cols: 80,
|
||||
cwd,
|
||||
env: env as Record<string, string>,
|
||||
name: "xterm-256color",
|
||||
// TODO: Something else is broken here so we need to force the use of winPty on windows
|
||||
useConpty: false,
|
||||
})
|
||||
));
|
||||
|
||||
logger.info(`[SHELL-SESSION]: PTY for ${this.terminalId} is ${resume ? "resumed" : "started"} with PID=${shellProcess.pid}`);
|
||||
|
||||
return { shellProcess, resume };
|
||||
}
|
||||
|
||||
constructor({ cluster, kubectl, tabId, websocket }: ShellSessionArgs) {
|
||||
constructor(protected readonly dependencies: ShellSessionDependencies, { cluster, kubectl, tabId, websocket }: ShellSessionArgs) {
|
||||
this.cluster = cluster;
|
||||
this.kubectl = kubectl;
|
||||
this.websocket = websocket;
|
||||
@@ -175,50 +136,15 @@ export abstract class ShellSession {
|
||||
this.websocket.send(JSON.stringify(message));
|
||||
}
|
||||
|
||||
protected async getCwd(env: Record<string, string | undefined>): Promise<string> {
|
||||
const cwdOptions = [this.cwd];
|
||||
|
||||
if (isWindows) {
|
||||
cwdOptions.push(
|
||||
env.USERPROFILE,
|
||||
os.homedir(),
|
||||
"C:\\",
|
||||
);
|
||||
} else {
|
||||
cwdOptions.push(
|
||||
env.HOME,
|
||||
os.homedir(),
|
||||
);
|
||||
|
||||
if (isMac) {
|
||||
cwdOptions.push("/Users");
|
||||
} else {
|
||||
cwdOptions.push("/home");
|
||||
}
|
||||
}
|
||||
|
||||
for (const potentialCwd of cwdOptions) {
|
||||
if (!potentialCwd) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const stats = await stat(potentialCwd);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
return potentialCwd;
|
||||
}
|
||||
} catch {
|
||||
// ignore error
|
||||
}
|
||||
}
|
||||
|
||||
return "."; // Always valid
|
||||
}
|
||||
|
||||
protected async openShellProcess(shell: string, args: string[], env: Record<string, string | undefined>) {
|
||||
const cwd = await this.getCwd(env);
|
||||
const { shellProcess, resume } = this.ensureShellProcess(shell, args, env, cwd);
|
||||
const cwd = await this.dependencies.getValidCwd(this.cwd, env);
|
||||
const { shellProcess, resume, cleanup } = this.dependencies.ensureShellProcess({
|
||||
shell,
|
||||
args,
|
||||
env,
|
||||
cwd,
|
||||
terminalId: this.terminalId,
|
||||
});
|
||||
|
||||
if (resume) {
|
||||
this.send({ type: TerminalChannels.CONNECTED });
|
||||
@@ -227,7 +153,7 @@ export abstract class ShellSession {
|
||||
this.running = true;
|
||||
shellProcess.onData(data => this.send({ type: TerminalChannels.STDOUT, data }));
|
||||
shellProcess.onExit(({ exitCode }) => {
|
||||
logger.info(`[SHELL-SESSION]: shell has exited for ${this.terminalId} closed with exitcode=${exitCode}`);
|
||||
this.dependencies.logger.info(`[SHELL-SESSION]: shell has exited for ${this.terminalId} closed with exitcode=${exitCode}`);
|
||||
|
||||
// This might already be false because of the kill() within the websocket.on("close") handler
|
||||
if (this.running) {
|
||||
@@ -245,11 +171,11 @@ export abstract class ShellSession {
|
||||
this.websocket
|
||||
.on("message", (rawData: unknown): void => {
|
||||
if (!this.running) {
|
||||
return void logger.debug(`[SHELL-SESSION]: received message from ${this.terminalId}, but shellProcess isn't running`);
|
||||
return void this.dependencies.logger.debug(`[SHELL-SESSION]: received message from ${this.terminalId}, but shellProcess isn't running`);
|
||||
}
|
||||
|
||||
if (!(rawData instanceof Buffer)) {
|
||||
return void logger.error(`[SHELL-SESSION]: Received message non-buffer message.`, { rawData });
|
||||
return void this.dependencies.logger.error(`[SHELL-SESSION]: Received message non-buffer message.`, { rawData });
|
||||
}
|
||||
|
||||
const data = rawData.toString();
|
||||
@@ -265,18 +191,18 @@ export abstract class ShellSession {
|
||||
shellProcess.resize(message.data.width, message.data.height);
|
||||
break;
|
||||
case TerminalChannels.PING:
|
||||
logger.silly(`[SHELL-SESSION]: ${this.terminalId} ping!`);
|
||||
this.dependencies.logger.silly(`[SHELL-SESSION]: ${this.terminalId} ping!`);
|
||||
break;
|
||||
default:
|
||||
logger.warn(`[SHELL-SESSION]: unknown or unhandleable message type for ${this.terminalId}`, message);
|
||||
this.dependencies.logger.warn(`[SHELL-SESSION]: unknown or unhandleable message type for ${this.terminalId}`, message);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`[SHELL-SESSION]: failed to handle message for ${this.terminalId}`, error);
|
||||
this.dependencies.logger.error(`[SHELL-SESSION]: failed to handle message for ${this.terminalId}`, error);
|
||||
}
|
||||
})
|
||||
.once("close", code => {
|
||||
logger.info(`[SHELL-SESSION]: websocket for ${this.terminalId} closed with code=${WebSocketCloseEvent[code]}(${code})`, { cluster: this.cluster.getMeta() });
|
||||
this.dependencies.logger.info(`[SHELL-SESSION]: websocket for ${this.terminalId} closed with code=${WebSocketCloseEvent[code]}(${code})`, { cluster: this.cluster.getMeta() });
|
||||
|
||||
const stopShellSession = this.running
|
||||
&& (
|
||||
@@ -291,11 +217,10 @@ export abstract class ShellSession {
|
||||
this.running = false;
|
||||
|
||||
try {
|
||||
logger.info(`[SHELL-SESSION]: Killing shell process (pid=${shellProcess.pid}) for ${this.terminalId}`);
|
||||
shellProcess.kill();
|
||||
ShellSession.processes.delete(this.terminalId);
|
||||
this.dependencies.logger.info(`[SHELL-SESSION]: Killing shell process (pid=${shellProcess.pid}) for ${this.terminalId}`);
|
||||
cleanup();
|
||||
} catch (error) {
|
||||
logger.warn(`[SHELL-SESSION]: failed to kill shell process (pid=${shellProcess.pid}) for ${this.terminalId}`, error);
|
||||
this.dependencies.logger.warn(`[SHELL-SESSION]: failed to kill shell process (pid=${shellProcess.pid}) for ${this.terminalId}`, error);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -307,73 +232,13 @@ export abstract class ShellSession {
|
||||
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 = [await this.kubectlBinDirP, ...this.getPathEntries(), process.env.PATH].join(path.delimiter);
|
||||
const shell = UserStore.getInstance().resolvedShell;
|
||||
|
||||
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 = await 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 getCachedShellEnv() {
|
||||
return this.dependencies.getCachedShellEnv({
|
||||
cluster: this.cluster,
|
||||
initialPathEntries: this.getPathEntries(),
|
||||
kubeconfigPathP: this.kubeconfigPathP,
|
||||
kubectlBinDirP: this.kubectlBinDirP,
|
||||
});
|
||||
}
|
||||
|
||||
protected exit(code = WebSocketCloseEvent.NormalClosure) {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import { spawn } from "node-pty";
|
||||
|
||||
const spawnPtyInjectable = getInjectable({
|
||||
id: "spawn-pty",
|
||||
instantiate: () => spawn,
|
||||
causesSideEffects: true,
|
||||
});
|
||||
|
||||
export default spawnPtyInjectable;
|
||||
@@ -4,15 +4,13 @@
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import { beforeQuitOfBackEndInjectionToken } from "../runnable-tokens/before-quit-of-back-end-injection-token";
|
||||
import { ShellSession } from "../../shell-session/shell-session";
|
||||
import killAllShellProcessesInjectable from "../../shell-session/kill-all-processes.injectable";
|
||||
|
||||
const cleanUpShellSessionsInjectable = getInjectable({
|
||||
id: "clean-up-shell-sessions",
|
||||
|
||||
instantiate: () => ({
|
||||
run: () => {
|
||||
ShellSession.cleanup();
|
||||
},
|
||||
instantiate: (di) => ({
|
||||
run: di.inject(killAllShellProcessesInjectable),
|
||||
}),
|
||||
|
||||
injectionToken: beforeQuitOfBackEndInjectionToken,
|
||||
|
||||
@@ -13,7 +13,7 @@ const anyKubeconfig = /^kubeconfig$/i;
|
||||
* before KUBECONFIG and we only set KUBECONFIG.
|
||||
* @param env The current copy of env
|
||||
*/
|
||||
export function clearKubeconfigEnvVars(env: Record<string, any>): Record<string, any> {
|
||||
export function clearKubeconfigEnvVars(env: Record<string, string | undefined>): Record<string, string | undefined> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(env)
|
||||
.filter(([key]) => anyKubeconfig.exec(key) === null),
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import { shellEnv } from "./shell-env";
|
||||
|
||||
const shellEnvInjectable = getInjectable({
|
||||
id: "shell-env",
|
||||
instantiate: () => shellEnv,
|
||||
causesSideEffects: true,
|
||||
});
|
||||
|
||||
export default shellEnvInjectable;
|
||||
@@ -30,7 +30,7 @@ export const DockTabs = ({ tabs, autoFocus, selectedTab, onChangeTab }: DockTabs
|
||||
return Array.from(elem.current?.querySelectorAll(".Tabs .Tab") ?? []);
|
||||
};
|
||||
|
||||
const renderTab = (tab?: DockTabModel) => {
|
||||
const renderTab = (tab: DockTabModel | undefined, index: number) => {
|
||||
if (!tab) {
|
||||
return null;
|
||||
}
|
||||
@@ -38,14 +38,37 @@ export const DockTabs = ({ tabs, autoFocus, selectedTab, onChangeTab }: DockTabs
|
||||
switch (tab.kind) {
|
||||
case TabKind.CREATE_RESOURCE:
|
||||
case TabKind.EDIT_RESOURCE:
|
||||
return <DockTab value={tab} icon="edit" />;
|
||||
return (
|
||||
<DockTab
|
||||
value={tab}
|
||||
icon="edit"
|
||||
data-testid={`dock-tab-${index}`}
|
||||
/>
|
||||
);
|
||||
case TabKind.INSTALL_CHART:
|
||||
case TabKind.UPGRADE_CHART:
|
||||
return <DockTab value={tab} icon="install_desktop" />;
|
||||
return (
|
||||
<DockTab
|
||||
value={tab}
|
||||
icon="install_desktop"
|
||||
data-testid={`dock-tab-${index}`}
|
||||
/>
|
||||
);
|
||||
case TabKind.POD_LOGS:
|
||||
return <DockTab value={tab} icon="subject" />;
|
||||
return (
|
||||
<DockTab
|
||||
value={tab}
|
||||
icon="subject"
|
||||
data-testid={`dock-tab-${index}`}
|
||||
/>
|
||||
);
|
||||
case TabKind.TERMINAL:
|
||||
return <TerminalTab value={tab} />;
|
||||
return (
|
||||
<TerminalTab
|
||||
value={tab}
|
||||
data-testid={`dock-tab-${index}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -96,7 +119,11 @@ export const DockTabs = ({ tabs, autoFocus, selectedTab, onChangeTab }: DockTabs
|
||||
scrollable={showScrollbar}
|
||||
className={styles.tabs}
|
||||
>
|
||||
{tabs.map(tab => <Fragment key={tab.id}>{renderTab(tab)}</Fragment>)}
|
||||
{tabs.map((tab, index) => (
|
||||
<Fragment key={tab.id}>
|
||||
{renderTab(tab, index)}
|
||||
</Fragment>
|
||||
))}
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
|
||||
// This is here so that in tests we can override it to disable a warning because we are using jest-canvas-mock
|
||||
|
||||
const allowTerminalTransparencyInjectable = getInjectable({
|
||||
id: "allow-terminal-transparency",
|
||||
instantiate: () => false,
|
||||
});
|
||||
|
||||
export default allowTerminalTransparencyInjectable;
|
||||
@@ -11,6 +11,7 @@ import terminalSpawningPoolInjectable from "./terminal-spawning-pool.injectable"
|
||||
import terminalConfigInjectable from "../../../../common/user-store/terminal-config.injectable";
|
||||
import terminalCopyOnSelectInjectable from "../../../../common/user-store/terminal-copy-on-select.injectable";
|
||||
import themeStoreInjectable from "../../../themes/store.injectable";
|
||||
import allowTerminalTransparencyInjectable from "./allow-transparency.injectable";
|
||||
|
||||
export type CreateTerminal = (tabId: TabId, api: TerminalApi) => Terminal;
|
||||
|
||||
@@ -22,6 +23,7 @@ const createTerminalInjectable = getInjectable({
|
||||
terminalConfig: di.inject(terminalConfigInjectable),
|
||||
terminalCopyOnSelect: di.inject(terminalCopyOnSelectInjectable),
|
||||
themeStore: di.inject(themeStoreInjectable),
|
||||
allowTransparency: di.inject(allowTerminalTransparencyInjectable),
|
||||
};
|
||||
|
||||
return (tabId, api) => new Terminal(dependencies, { tabId, api });
|
||||
|
||||
@@ -25,6 +25,7 @@ export interface TerminalDependencies {
|
||||
readonly terminalConfig: IComputedValue<TerminalConfig>;
|
||||
readonly terminalCopyOnSelect: IComputedValue<boolean>;
|
||||
readonly themeStore: ThemeStore;
|
||||
readonly allowTransparency: boolean;
|
||||
}
|
||||
|
||||
export interface TerminalArguments {
|
||||
@@ -88,6 +89,7 @@ export class Terminal {
|
||||
cursorStyle: "bar",
|
||||
fontSize: this.fontSize,
|
||||
fontFamily: this.fontFamily,
|
||||
allowTransparency: dependencies.allowTransparency,
|
||||
});
|
||||
// enable terminal addons
|
||||
this.xterm.loadAddon(this.fitAddon);
|
||||
@@ -119,6 +121,9 @@ export class Terminal {
|
||||
() => this.api.removeAllListeners(),
|
||||
() => window.removeEventListener("resize", this.onResize),
|
||||
() => this.elem.removeEventListener("contextmenu", this.onContextMenu),
|
||||
this.xterm.onResize(({ cols, rows }) => {
|
||||
this.api.sendTerminalSize(cols, rows);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -127,21 +132,7 @@ export class Terminal {
|
||||
this.xterm.dispose();
|
||||
}
|
||||
|
||||
fit = () => {
|
||||
try {
|
||||
const { cols, rows } = this.fitAddon.proposeDimensions();
|
||||
|
||||
// attempt to resize/fit terminal when it's not visible in DOM will crash with exception
|
||||
// see: https://github.com/xtermjs/xterm.js/issues/3118
|
||||
if (isNaN(cols) || isNaN(rows)) return;
|
||||
|
||||
this.fitAddon.fit();
|
||||
this.api.sendTerminalSize(cols, rows);
|
||||
} catch (error) {
|
||||
// see https://github.com/lensapp/lens/issues/1891
|
||||
logger.error(`[TERMINAL]: failed to resize terminal to fit`, error);
|
||||
}
|
||||
};
|
||||
fit = () => this.fitAddon.fit();
|
||||
|
||||
fitLazy = debounce(this.fit, 250);
|
||||
|
||||
|
||||
@@ -66,16 +66,16 @@ type EnableExtensions<T> = (...extensions: T[]) => void;
|
||||
type DisableExtensions<T> = (...extensions: T[]) => void;
|
||||
|
||||
export interface ApplicationBuilder {
|
||||
dis: DiContainers;
|
||||
readonly dis: DiContainers;
|
||||
setEnvironmentToClusterFrame: () => ApplicationBuilder;
|
||||
|
||||
extensions: {
|
||||
renderer: {
|
||||
readonly extensions: {
|
||||
readonly renderer: {
|
||||
enable: EnableExtensions<LensRendererExtension>;
|
||||
disable: DisableExtensions<LensRendererExtension>;
|
||||
};
|
||||
|
||||
main: {
|
||||
readonly main: {
|
||||
enable: EnableExtensions<LensMainExtension>;
|
||||
disable: DisableExtensions<LensMainExtension>;
|
||||
};
|
||||
@@ -89,38 +89,42 @@ export interface ApplicationBuilder {
|
||||
beforeRender: (callback: Callback) => ApplicationBuilder;
|
||||
render: () => Promise<RenderResult>;
|
||||
|
||||
tray: {
|
||||
readonly tray: {
|
||||
click: (id: string) => Promise<void>;
|
||||
get: (id: string) => MinimalTrayMenuItem | null;
|
||||
getIconPath: () => string;
|
||||
};
|
||||
|
||||
applicationMenu: {
|
||||
readonly dock: {
|
||||
click: (index: number) => void;
|
||||
};
|
||||
|
||||
readonly applicationMenu: {
|
||||
click: (path: string) => void;
|
||||
};
|
||||
|
||||
preferences: {
|
||||
readonly preferences: {
|
||||
close: () => void;
|
||||
navigate: () => void;
|
||||
navigateTo: (route: Route<any>, params: Partial<NavigateToRouteOptions<any>>) => void;
|
||||
navigation: {
|
||||
readonly navigation: {
|
||||
click: (id: string) => void;
|
||||
};
|
||||
};
|
||||
|
||||
helmCharts: {
|
||||
readonly helmCharts: {
|
||||
navigate: () => void;
|
||||
};
|
||||
|
||||
select: {
|
||||
readonly select: {
|
||||
openMenu: (id: string) => void;
|
||||
selectOption: (menuId: string, labelText: string) => void;
|
||||
};
|
||||
}
|
||||
|
||||
interface DiContainers {
|
||||
rendererDi: DiContainer;
|
||||
mainDi: DiContainer;
|
||||
readonly rendererDi: DiContainer;
|
||||
readonly mainDi: DiContainer;
|
||||
}
|
||||
|
||||
interface Environment {
|
||||
@@ -254,6 +258,11 @@ export const getApplicationBuilder = () => {
|
||||
const enableMainExtension = enableExtensionsFor(mainExtensionsState, mainDi);
|
||||
const disableRendererExtension = disableExtensionsFor(rendererExtensionsState, rendererDi);
|
||||
const disableMainExtension = disableExtensionsFor(mainExtensionsState, mainDi);
|
||||
const dock: ApplicationBuilder["dock"] = {
|
||||
click: (index) => {
|
||||
rendered.getByTestId(`dock-tab-${index}`).click();
|
||||
},
|
||||
};
|
||||
|
||||
const builder: ApplicationBuilder = {
|
||||
dis,
|
||||
@@ -293,6 +302,14 @@ export const getApplicationBuilder = () => {
|
||||
},
|
||||
},
|
||||
|
||||
get dock() {
|
||||
if (environment === environments.clusterFrame) {
|
||||
return dock;
|
||||
}
|
||||
|
||||
throw new Error("cannot use dock in application frame");
|
||||
},
|
||||
|
||||
tray: {
|
||||
get: (id: string) => {
|
||||
const lastCall = last(traySetMenuItemsMock.mock.calls);
|
||||
|
||||
@@ -69,6 +69,7 @@ import kubeObjectDetailsClusterFrameChildComponentInjectable from "./components/
|
||||
import kubeconfigDialogClusterFrameChildComponentInjectable from "./components/kubeconfig-dialog/kubeconfig-dialog-cluster-frame-child-component.injectable";
|
||||
import portForwardDialogClusterFrameChildComponentInjectable from "./port-forward/port-forward-dialog-cluster-frame-child-component.injectable";
|
||||
import setupSystemCaInjectable from "./frames/root-frame/setup-system-ca.injectable";
|
||||
import allowTerminalTransparencyInjectable from "./components/dock/terminal/allow-transparency.injectable";
|
||||
|
||||
export const getDiForUnitTesting = (opts: { doGeneralOverrides?: boolean } = {}) => {
|
||||
const {
|
||||
@@ -185,7 +186,7 @@ export const getDiForUnitTesting = (opts: { doGeneralOverrides?: boolean } = {})
|
||||
isTableColumnHidden: () => false,
|
||||
extensionRegistryUrl: { customUrl: "some-custom-url" },
|
||||
syncKubeconfigEntries: observable.map(),
|
||||
terminalConfig: { fontSize: 42 },
|
||||
terminalConfig: { fontSize: 42, fontFamily: "RobotoMono" },
|
||||
editorConfiguration: { minimap: {}, tabSize: 42, fontSize: 42 },
|
||||
} as unknown as UserStore),
|
||||
);
|
||||
@@ -197,7 +198,7 @@ export const getDiForUnitTesting = (opts: { doGeneralOverrides?: boolean } = {})
|
||||
overrideFsWithFakes(di);
|
||||
|
||||
di.override(focusWindowInjectable, () => () => {});
|
||||
|
||||
di.override(allowTerminalTransparencyInjectable, () => true);
|
||||
di.override(loggerInjectable, () => ({
|
||||
warn: noop,
|
||||
debug: noop,
|
||||
|
||||
@@ -0,0 +1,582 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`local shell session techincal tests renders 1`] = `
|
||||
<body>
|
||||
<div>
|
||||
<div
|
||||
class="Notifications flex column align-flex-end"
|
||||
/>
|
||||
<div
|
||||
class="mainLayout"
|
||||
style="--sidebar-width: 200px;"
|
||||
>
|
||||
<div
|
||||
class="sidebar"
|
||||
>
|
||||
<div
|
||||
class="flex flex-col"
|
||||
data-testid="cluster-sidebar"
|
||||
>
|
||||
<div
|
||||
class="SidebarCluster"
|
||||
>
|
||||
<div
|
||||
class="Avatar rounded loadingAvatar"
|
||||
style="width: 40px; height: 40px;"
|
||||
>
|
||||
??
|
||||
</div>
|
||||
<div
|
||||
class="loadingClusterName"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="sidebarNav sidebar-active-status"
|
||||
>
|
||||
<div
|
||||
class="SidebarItem"
|
||||
data-is-active-test="true"
|
||||
data-testid="sidebar-item-workloads"
|
||||
>
|
||||
<a
|
||||
aria-current="page"
|
||||
class="nav-item flex gaps align-center expandable active"
|
||||
data-testid="sidebar-item-link-for-workloads"
|
||||
href="/"
|
||||
>
|
||||
<i
|
||||
class="Icon svg focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
/>
|
||||
</i>
|
||||
<span
|
||||
class="link-text box grow"
|
||||
>
|
||||
Workloads
|
||||
</span>
|
||||
<i
|
||||
class="Icon expand-icon box right material focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="keyboard_arrow_down"
|
||||
>
|
||||
keyboard_arrow_down
|
||||
</span>
|
||||
</i>
|
||||
</a>
|
||||
</div>
|
||||
<div
|
||||
class="SidebarItem"
|
||||
data-is-active-test="false"
|
||||
data-testid="sidebar-item-config"
|
||||
>
|
||||
<a
|
||||
class="nav-item flex gaps align-center"
|
||||
data-testid="sidebar-item-link-for-config"
|
||||
href="/"
|
||||
>
|
||||
<i
|
||||
class="Icon material focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="list"
|
||||
>
|
||||
list
|
||||
</span>
|
||||
</i>
|
||||
<span
|
||||
class="link-text box grow"
|
||||
>
|
||||
Config
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
<div
|
||||
class="SidebarItem"
|
||||
data-is-active-test="false"
|
||||
data-testid="sidebar-item-network"
|
||||
>
|
||||
<a
|
||||
class="nav-item flex gaps align-center expandable"
|
||||
data-testid="sidebar-item-link-for-network"
|
||||
href="/"
|
||||
>
|
||||
<i
|
||||
class="Icon material focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="device_hub"
|
||||
>
|
||||
device_hub
|
||||
</span>
|
||||
</i>
|
||||
<span
|
||||
class="link-text box grow"
|
||||
>
|
||||
Network
|
||||
</span>
|
||||
<i
|
||||
class="Icon expand-icon box right material focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="keyboard_arrow_down"
|
||||
>
|
||||
keyboard_arrow_down
|
||||
</span>
|
||||
</i>
|
||||
</a>
|
||||
</div>
|
||||
<div
|
||||
class="SidebarItem"
|
||||
data-is-active-test="false"
|
||||
data-testid="sidebar-item-storage"
|
||||
>
|
||||
<a
|
||||
class="nav-item flex gaps align-center"
|
||||
data-testid="sidebar-item-link-for-storage"
|
||||
href="/"
|
||||
>
|
||||
<i
|
||||
class="Icon material focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="storage"
|
||||
>
|
||||
storage
|
||||
</span>
|
||||
</i>
|
||||
<span
|
||||
class="link-text box grow"
|
||||
>
|
||||
Storage
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
<div
|
||||
class="SidebarItem"
|
||||
data-is-active-test="false"
|
||||
data-testid="sidebar-item-helm"
|
||||
>
|
||||
<a
|
||||
class="nav-item flex gaps align-center expandable"
|
||||
data-testid="sidebar-item-link-for-helm"
|
||||
href="/"
|
||||
>
|
||||
<i
|
||||
class="Icon svg focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
/>
|
||||
</i>
|
||||
<span
|
||||
class="link-text box grow"
|
||||
>
|
||||
Helm
|
||||
</span>
|
||||
<i
|
||||
class="Icon expand-icon box right material focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="keyboard_arrow_down"
|
||||
>
|
||||
keyboard_arrow_down
|
||||
</span>
|
||||
</i>
|
||||
</a>
|
||||
</div>
|
||||
<div
|
||||
class="SidebarItem"
|
||||
data-is-active-test="false"
|
||||
data-testid="sidebar-item-user-management"
|
||||
>
|
||||
<a
|
||||
class="nav-item flex gaps align-center"
|
||||
data-testid="sidebar-item-link-for-user-management"
|
||||
href="/"
|
||||
>
|
||||
<i
|
||||
class="Icon material focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="security"
|
||||
>
|
||||
security
|
||||
</span>
|
||||
</i>
|
||||
<span
|
||||
class="link-text box grow"
|
||||
>
|
||||
Access Control
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
<div
|
||||
class="SidebarItem"
|
||||
data-is-active-test="false"
|
||||
data-testid="sidebar-item-custom-resources"
|
||||
>
|
||||
<a
|
||||
class="nav-item flex gaps align-center expandable"
|
||||
data-testid="sidebar-item-link-for-custom-resources"
|
||||
href="/"
|
||||
>
|
||||
<i
|
||||
class="Icon material focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="extension"
|
||||
>
|
||||
extension
|
||||
</span>
|
||||
</i>
|
||||
<span
|
||||
class="link-text box grow"
|
||||
>
|
||||
Custom Resources
|
||||
</span>
|
||||
<i
|
||||
class="Icon expand-icon box right material focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="keyboard_arrow_down"
|
||||
>
|
||||
keyboard_arrow_down
|
||||
</span>
|
||||
</i>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="ResizingAnchor horizontal trailing"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="contents"
|
||||
>
|
||||
<div
|
||||
class="TabLayout"
|
||||
data-testid="tab-layout"
|
||||
>
|
||||
<div
|
||||
class="Tabs center scrollable"
|
||||
>
|
||||
<div
|
||||
class="Tab flex gaps align-center active"
|
||||
data-is-active-test="true"
|
||||
data-testid="tab-link-for-overview"
|
||||
role="tab"
|
||||
tabindex="0"
|
||||
>
|
||||
<div
|
||||
class="label"
|
||||
>
|
||||
Overview
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<main>
|
||||
<div
|
||||
class="WorkloadsOverview flex column gaps"
|
||||
>
|
||||
<div
|
||||
class="header flex gaps align-center"
|
||||
>
|
||||
<h5
|
||||
class="box grow"
|
||||
>
|
||||
Overview
|
||||
</h5>
|
||||
<div>
|
||||
<div
|
||||
class="Select theme-dark NamespaceSelect NamespaceSelectFilter css-b62m3t-container"
|
||||
>
|
||||
<span
|
||||
class="css-1f43avz-a11yText-A11yText"
|
||||
id="react-select-overview-namespace-select-filter-input-live-region"
|
||||
/>
|
||||
<span
|
||||
aria-atomic="false"
|
||||
aria-live="polite"
|
||||
aria-relevant="additions text"
|
||||
class="css-1f43avz-a11yText-A11yText"
|
||||
/>
|
||||
<div
|
||||
class="Select__control css-1s2u09g-control"
|
||||
>
|
||||
<div
|
||||
class="Select__value-container Select__value-container--is-multi css-319lph-ValueContainer"
|
||||
>
|
||||
<div
|
||||
class="Select__placeholder css-14el2xx-placeholder"
|
||||
id="react-select-overview-namespace-select-filter-input-placeholder"
|
||||
>
|
||||
All namespaces
|
||||
</div>
|
||||
<div
|
||||
class="Select__input-container css-6j8wv5-Input"
|
||||
data-value=""
|
||||
>
|
||||
<input
|
||||
aria-autocomplete="list"
|
||||
aria-describedby="react-select-overview-namespace-select-filter-input-placeholder"
|
||||
aria-expanded="false"
|
||||
aria-haspopup="true"
|
||||
autocapitalize="none"
|
||||
autocomplete="off"
|
||||
autocorrect="off"
|
||||
class="Select__input"
|
||||
id="overview-namespace-select-filter-input"
|
||||
role="combobox"
|
||||
spellcheck="false"
|
||||
style="opacity: 1; width: 100%; grid-area: 1 / 2; min-width: 2px; border: 0px; margin: 0px; outline: 0; padding: 0px;"
|
||||
tabindex="0"
|
||||
type="text"
|
||||
value=""
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="Select__indicators css-1hb7zxy-IndicatorsContainer"
|
||||
>
|
||||
<span
|
||||
class="Select__indicator-separator css-1okebmr-indicatorSeparator"
|
||||
/>
|
||||
<div
|
||||
aria-hidden="true"
|
||||
class="Select__indicator Select__dropdown-indicator css-tlfecz-indicatorContainer"
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
class="css-tj5bde-Svg"
|
||||
focusable="false"
|
||||
height="20"
|
||||
viewBox="0 0 20 20"
|
||||
width="20"
|
||||
>
|
||||
<path
|
||||
d="M4.516 7.548c0.436-0.446 1.043-0.481 1.576 0l3.908 3.747 3.908-3.747c0.533-0.481 1.141-0.446 1.574 0 0.436 0.445 0.408 1.197 0 1.615-0.406 0.418-4.695 4.502-4.695 4.502-0.217 0.223-0.502 0.335-0.787 0.335s-0.57-0.112-0.789-0.335c0 0-4.287-4.084-4.695-4.502s-0.436-1.17 0-1.615z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="OverviewStatuses"
|
||||
>
|
||||
<div
|
||||
class="workloads"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="footer"
|
||||
>
|
||||
<div
|
||||
class="Dock isOpen"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div
|
||||
class="ResizingAnchor vertical leading"
|
||||
/>
|
||||
<div
|
||||
class="tabs-container flex align-center"
|
||||
>
|
||||
<div
|
||||
class="dockTabs"
|
||||
role="tablist"
|
||||
>
|
||||
<div
|
||||
class="Tabs tabs"
|
||||
>
|
||||
<div
|
||||
class="Tab flex gaps align-center DockTab TerminalTab active"
|
||||
data-testid="dock-tab-0"
|
||||
id="tab-terminal"
|
||||
role="tab"
|
||||
tabindex="0"
|
||||
>
|
||||
<i
|
||||
class="Icon material focusable"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="terminal"
|
||||
>
|
||||
terminal
|
||||
</span>
|
||||
</i>
|
||||
<div
|
||||
class="label"
|
||||
>
|
||||
<div
|
||||
class="flex align-center"
|
||||
>
|
||||
<span
|
||||
class="title"
|
||||
>
|
||||
Terminal
|
||||
</span>
|
||||
<div
|
||||
class="close"
|
||||
>
|
||||
<i
|
||||
class="Icon material interactive focusable small"
|
||||
id="tooltip_target_13"
|
||||
tabindex="0"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="close"
|
||||
>
|
||||
close
|
||||
</span>
|
||||
<div />
|
||||
</i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="toolbar flex gaps align-center box grow"
|
||||
>
|
||||
<div
|
||||
class="dock-menu box grow"
|
||||
>
|
||||
<i
|
||||
class="Icon new-dock-tab material interactive focusable"
|
||||
id="menu_actions_14"
|
||||
tabindex="0"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="add"
|
||||
>
|
||||
add
|
||||
</span>
|
||||
<div />
|
||||
</i>
|
||||
</div>
|
||||
<i
|
||||
class="Icon material interactive focusable"
|
||||
id="tooltip_target_16"
|
||||
tabindex="0"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="fullscreen"
|
||||
>
|
||||
fullscreen
|
||||
</span>
|
||||
<div />
|
||||
</i>
|
||||
<i
|
||||
class="Icon material interactive focusable"
|
||||
id="tooltip_target_17"
|
||||
tabindex="0"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="keyboard_arrow_down"
|
||||
>
|
||||
keyboard_arrow_down
|
||||
</span>
|
||||
<div />
|
||||
</i>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="tab-content terminal"
|
||||
style="flex-basis: 300px;"
|
||||
>
|
||||
<div
|
||||
class="TerminalWindow dark"
|
||||
>
|
||||
<div
|
||||
class="terminal xterm focus"
|
||||
dir="ltr"
|
||||
tabindex="0"
|
||||
>
|
||||
<div
|
||||
class="xterm-viewport"
|
||||
style="background-color: rgb(0, 0, 0);"
|
||||
>
|
||||
<div
|
||||
class="xterm-scroll-area"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="xterm-screen"
|
||||
>
|
||||
<div
|
||||
class="xterm-helpers"
|
||||
>
|
||||
<textarea
|
||||
aria-label="Terminal input"
|
||||
aria-multiline="false"
|
||||
autocapitalize="off"
|
||||
autocorrect="off"
|
||||
class="xterm-helper-textarea"
|
||||
spellcheck="false"
|
||||
tabindex="0"
|
||||
/>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
class="xterm-char-measure-element"
|
||||
style="font-family: RobotoMono; font-size: 42px;"
|
||||
>
|
||||
W
|
||||
</span>
|
||||
<div
|
||||
class="composition-view"
|
||||
/>
|
||||
</div>
|
||||
<canvas
|
||||
class="xterm-text-layer"
|
||||
style="z-index: 0;"
|
||||
/>
|
||||
<canvas
|
||||
class="xterm-selection-layer"
|
||||
style="z-index: 1;"
|
||||
/>
|
||||
<canvas
|
||||
class="xterm-link-layer"
|
||||
style="z-index: 2;"
|
||||
/>
|
||||
<canvas
|
||||
class="xterm-cursor-layer"
|
||||
style="z-index: 3;"
|
||||
/>
|
||||
<div
|
||||
class="xterm-decoration-container"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
`;
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { RenderResult } from "@testing-library/react";
|
||||
import type { ApplicationBuilder } from "../../renderer/components/test-utils/get-application-builder";
|
||||
import { getApplicationBuilder } from "../../renderer/components/test-utils/get-application-builder";
|
||||
import getShellAuthTokenChannelHandlerInjectable from "../../main/lens-proxy/proxy-functions/shell/auth-token-channel-handler.injectable";
|
||||
import type { GetShellAuthToken } from "../../common/shell-authentication/get-auth-token.injectable";
|
||||
|
||||
describe("local shell session techincal tests", () => {
|
||||
let builder: ApplicationBuilder;
|
||||
let result: RenderResult;
|
||||
let authenticationSpy: jest.SpyInstance<Uint8Array | Promise<Uint8Array>, Parameters<GetShellAuthToken>>;
|
||||
|
||||
beforeEach(async () => {
|
||||
builder = getApplicationBuilder()
|
||||
.beforeRender(() => {
|
||||
const shellAuthentication = builder.dis.mainDi.inject(getShellAuthTokenChannelHandlerInjectable);
|
||||
|
||||
authenticationSpy = jest.spyOn(shellAuthentication, "handler");
|
||||
});
|
||||
builder.setEnvironmentToClusterFrame();
|
||||
|
||||
result = await builder.render();
|
||||
builder.dock.click(0);
|
||||
});
|
||||
|
||||
it("renders", () => {
|
||||
expect(result.baseElement).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("should call the authentication function", () => {
|
||||
expect(authenticationSpy).toBeCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user