Merge remote-tracking branch 'origin/master' into eliminate-gst-from-app-paths

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>
This commit is contained in:
Janne Savolainen committed 2022-01-11 13:56:23 +02:00
commit 8d87bd0985
80 files changed
+1822 -1271

No files matched your search

+5 -8
View File
@@ -18,8 +18,6 @@
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { getDiForUnitTesting } from "../getDiForUnitTesting";
const logger = {
silly: jest.fn(),
debug: jest.fn(),
@@ -47,6 +45,7 @@ jest.mock("winston", () => ({
},
}));
import { getDiForUnitTesting } from "../getDiForUnitTesting";
import { KubeconfigManager } from "../kubeconfig-manager/kubeconfig-manager";
import mockFs from "mock-fs";
import type { Cluster } from "../../common/cluster/cluster";
@@ -69,7 +68,7 @@ describe("kubeconfig manager tests", () => {
di.override(directoryForTempInjectable, () => "some-directory-for-temp");
const mockOpts = {
mockFs({
"minikube-config.yml": JSON.stringify({
apiVersion: "v1",
clusters: [{
@@ -91,9 +90,7 @@ describe("kubeconfig manager tests", () => {
kind: "Config",
preferences: {},
}),
};
mockFs(mockOpts);
});
await di.runSetups();
@@ -110,7 +107,7 @@ describe("kubeconfig manager tests", () => {
cluster.contextHandler = {
ensureServer: () => Promise.resolve(),
} as any;
jest.spyOn(KubeconfigManager.prototype, "resolveProxyUrl", "get").mockReturnValue("http://127.0.0.1:9191/foo");
});
@@ -135,7 +132,7 @@ describe("kubeconfig manager tests", () => {
it("should remove 'temp' kube config on unlink and remove reference from inside class", async () => {
const kubeConfManager = createKubeconfigManager(cluster);
const configPath = await kubeConfManager.getPath();
expect(await fse.pathExists(configPath)).toBe(true);
@@ -22,25 +22,33 @@ import electronAppInjectable from "./electron-app/electron-app.injectable";
import getElectronAppPathInjectable from "./get-electron-app-path.injectable";
import { getDiForUnitTesting } from "../../getDiForUnitTesting";
import type { App } from "electron";
import registerChannelInjectable from "../register-channel/register-channel.injectable";
describe("get-electron-app-path", () => {
let getElectronAppPath: (name: string) => string | null;
beforeEach(() => {
const di = getDiForUnitTesting();
beforeEach(async () => {
const di = getDiForUnitTesting({ doGeneralOverrides: false });
const appStub = {
name: "some-app-name",
getPath: (name: string) => {
if (name !== "some-existing-name") {
throw new Error("irrelevant");
}
return "some-existing-app-path";
},
// eslint-disable-next-line unused-imports/no-unused-vars-ts
setPath: (_, __) => undefined,
} as App;
di.override(electronAppInjectable, () => appStub);
di.override(registerChannelInjectable, () => () => undefined);
await di.runSetups();
getElectronAppPath = di.inject(getElectronAppPathInjectable);
});
@@ -54,6 +62,6 @@ describe("get-electron-app-path", () => {
it("given app path does not exist, when called, returns null", () => {
const actual = getElectronAppPath("some-non-existing-name");
expect(actual).toBe(null);
expect(actual).toBe("");
});
});
@@ -31,6 +31,6 @@ export const getElectronAppPath =
try {
return app.getPath(name);
} catch (e) {
return null;
return "";
}
};
@@ -1,36 +0,0 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { when } from "mobx";
import { catalogCategoryRegistry } from "../../../common/catalog";
import { catalogEntityRegistry } from "../../../renderer/api/catalog-entity-registry";
import { isActiveRoute } from "../../../renderer/navigation";
export async function setEntityOnRouteMatch() {
await when(() => catalogEntityRegistry.entities.size > 0);
const entities = catalogEntityRegistry.getItemsForCategory(catalogCategoryRegistry.getByName("General"));
const activeEntity = entities.find(entity => isActiveRoute(entity.spec.path));
if (activeEntity) {
catalogEntityRegistry.activeEntity = activeEntity;
}
}
+69 -79
View File
@@ -26,11 +26,13 @@ import logger from "../logger";
import { ensureDir, pathExists } from "fs-extra";
import * as lockFile from "proper-lockfile";
import { helmCli } from "../helm/helm-cli";
import { customRequest } from "../../common/request";
import { getBundledKubectlVersion } from "../../common/utils/app-version";
import { isDevelopment, isWindows, isTestEnv } from "../../common/vars";
import { SemVer } from "semver";
import { defaultPackageMirror, packageMirrors } from "../../common/user-store/preferences-helpers";
import got from "got/dist/source";
import { promisify } from "util";
import stream from "stream";
const bundledVersion = getBundledKubectlVersion();
const kubectlMap: Map<string, string> = new Map([
@@ -51,7 +53,7 @@ const kubectlMap: Map<string, string> = new Map([
["1.21", bundledVersion],
]);
let bundledPath: string;
const initScriptVersionString = "# lens-initscript v3\n";
const initScriptVersionString = "# lens-initscript v3";
export function bundledKubectlPath(): string {
if (bundledPath) { return bundledPath; }
@@ -308,99 +310,87 @@ export class Kubectl {
logger.info(`Downloading kubectl ${this.kubectlVersion} from ${this.url} to ${this.path}`);
return new Promise<void>((resolve, reject) => {
const stream = customRequest({
url: this.url,
gzip: true,
});
const file = fs.createWriteStream(this.path);
const downloadStream = got.stream({ url: this.url, decompress: true });
const fileWriteStream = fs.createWriteStream(this.path, { mode: 0o755 });
const pipeline = promisify(stream.pipeline);
stream.on("complete", () => {
logger.debug("kubectl binary download finished");
file.end();
});
stream.on("error", (error) => {
logger.error(error);
fs.unlink(this.path, () => {
// do nothing
});
reject(error);
});
file.on("close", () => {
logger.debug("kubectl binary download closed");
fs.chmod(this.path, 0o755, (err) => {
if (err) reject(err);
});
resolve();
});
stream.pipe(file);
});
await pipeline(downloadStream, fileWriteStream);
logger.debug("kubectl binary download finished");
}
protected async writeInitScripts() {
const kubectlPath = this.dependencies.userStore.downloadKubectlBinaries ? this.dirname : path.dirname(this.getPathFromPreferences());
const kubectlPath = this.dependencies.userStore.downloadKubectlBinaries
? this.dirname
: path.dirname(this.getPathFromPreferences());
const helmPath = helmCli.getBinaryDir();
const fsPromises = fs.promises;
const bashScriptPath = path.join(this.dirname, ".bash_set_path");
let bashScript = `${initScriptVersionString}`;
bashScript += "tempkubeconfig=\"$KUBECONFIG\"\n";
bashScript += "test -f \"/etc/profile\" && . \"/etc/profile\"\n";
bashScript += "if test -f \"$HOME/.bash_profile\"; then\n";
bashScript += " . \"$HOME/.bash_profile\"\n";
bashScript += "elif test -f \"$HOME/.bash_login\"; then\n";
bashScript += " . \"$HOME/.bash_login\"\n";
bashScript += "elif test -f \"$HOME/.profile\"; then\n";
bashScript += " . \"$HOME/.profile\"\n";
bashScript += "fi\n";
bashScript += `export PATH="${helmPath}:${kubectlPath}:$PATH"\n`;
bashScript += "export KUBECONFIG=\"$tempkubeconfig\"\n";
bashScript += `NO_PROXY=",\${NO_PROXY:-localhost},"\n`;
bashScript += `NO_PROXY="\${NO_PROXY//,localhost,/,}"\n`;
bashScript += `NO_PROXY="\${NO_PROXY//,127.0.0.1,/,}"\n`;
bashScript += `NO_PROXY="localhost,127.0.0.1\${NO_PROXY%,}"\n`;
bashScript += "export NO_PROXY\n";
bashScript += "unset tempkubeconfig\n";
await fsPromises.writeFile(bashScriptPath, bashScript.toString(), { mode: 0o644 });
const bashScript = [
initScriptVersionString,
"tempkubeconfig=\"$KUBECONFIG\"",
"test -f \"/etc/profile\" && . \"/etc/profile\"",
"if test -f \"$HOME/.bash_profile\"; then",
" . \"$HOME/.bash_profile\"",
"elif test -f \"$HOME/.bash_login\"; then",
" . \"$HOME/.bash_login\"",
"elif test -f \"$HOME/.profile\"; then",
" . \"$HOME/.profile\"",
"fi",
`export PATH="${helmPath}:${kubectlPath}:$PATH"`,
'export KUBECONFIG="$tempkubeconfig"',
`NO_PROXY=",\${NO_PROXY:-localhost},"`,
`NO_PROXY="\${NO_PROXY//,localhost,/,}"`,
`NO_PROXY="\${NO_PROXY//,127.0.0.1,/,}"`,
`NO_PROXY="localhost,127.0.0.1\${NO_PROXY%,}"`,
"export NO_PROXY",
"unset tempkubeconfig",
].join("\n");
const zshScriptPath = path.join(this.dirname, ".zlogin");
let zshScript = `${initScriptVersionString}`;
const zshScript = [
initScriptVersionString,
"tempkubeconfig=\"$KUBECONFIG\"",
zshScript += "tempkubeconfig=\"$KUBECONFIG\"\n";
// restore previous ZDOTDIR
zshScript += "export ZDOTDIR=\"$OLD_ZDOTDIR\"\n";
// source all the files
zshScript += "test -f \"$OLD_ZDOTDIR/.zshenv\" && . \"$OLD_ZDOTDIR/.zshenv\"\n";
zshScript += "test -f \"$OLD_ZDOTDIR/.zprofile\" && . \"$OLD_ZDOTDIR/.zprofile\"\n";
zshScript += "test -f \"$OLD_ZDOTDIR/.zlogin\" && . \"$OLD_ZDOTDIR/.zlogin\"\n";
zshScript += "test -f \"$OLD_ZDOTDIR/.zshrc\" && . \"$OLD_ZDOTDIR/.zshrc\"\n";
// restore previous ZDOTDIR
"export ZDOTDIR=\"$OLD_ZDOTDIR\"",
// voodoo to replace any previous occurrences of kubectl path in the PATH
zshScript += `kubectlpath="${kubectlPath}"\n`;
zshScript += `helmpath="${helmPath}"\n`;
zshScript += "p=\":$kubectlpath:\"\n";
zshScript += "d=\":$PATH:\"\n";
zshScript += `d=\${d//$p/:}\n`;
zshScript += `d=\${d/#:/}\n`;
zshScript += `export PATH="$helmpath:$kubectlpath:\${d/%:/}"\n`;
zshScript += "export KUBECONFIG=\"$tempkubeconfig\"\n";
zshScript += `NO_PROXY=",\${NO_PROXY:-localhost},"\n`;
zshScript += `NO_PROXY="\${NO_PROXY//,localhost,/,}"\n`;
zshScript += `NO_PROXY="\${NO_PROXY//,127.0.0.1,/,}"\n`;
zshScript += `NO_PROXY="localhost,127.0.0.1\${NO_PROXY%,}"\n`;
zshScript += "export NO_PROXY\n";
zshScript += "unset tempkubeconfig\n";
zshScript += "unset OLD_ZDOTDIR\n";
await fsPromises.writeFile(zshScriptPath, zshScript.toString(), { mode: 0o644 });
// source all the files
"test -f \"$OLD_ZDOTDIR/.zshenv\" && . \"$OLD_ZDOTDIR/.zshenv\"",
"test -f \"$OLD_ZDOTDIR/.zprofile\" && . \"$OLD_ZDOTDIR/.zprofile\"",
"test -f \"$OLD_ZDOTDIR/.zlogin\" && . \"$OLD_ZDOTDIR/.zlogin\"",
"test -f \"$OLD_ZDOTDIR/.zshrc\" && . \"$OLD_ZDOTDIR/.zshrc\"",
// voodoo to replace any previous occurrences of kubectl path in the PATH
`kubectlpath="${kubectlPath}"`,
`helmpath="${helmPath}"`,
"p=\":$kubectlpath:\"",
"d=\":$PATH:\"",
`d=\${d//$p/:}`,
`d=\${d/#:/}`,
`export PATH="$helmpath:$kubectlpath:\${d/%:/}"`,
"export KUBECONFIG=\"$tempkubeconfig\"",
`NO_PROXY=",\${NO_PROXY:-localhost},"`,
`NO_PROXY="\${NO_PROXY//,localhost,/,}"`,
`NO_PROXY="\${NO_PROXY//,127.0.0.1,/,}"`,
`NO_PROXY="localhost,127.0.0.1\${NO_PROXY%,}"`,
"export NO_PROXY",
"unset tempkubeconfig",
"unset OLD_ZDOTDIR",
].join("\n");
await Promise.all([
fs.promises.writeFile(bashScriptPath, bashScript, { mode: 0o644 }),
fs.promises.writeFile(zshScriptPath, zshScript, { mode: 0o644 }),
]);
}
protected getDownloadMirror(): string {
// MacOS packages are only available from default
const mirror = packageMirrors.get(this.dependencies.userStore.downloadMirror)
const { url } = packageMirrors.get(this.dependencies.userStore.downloadMirror)
?? packageMirrors.get(defaultPackageMirror);
return mirror.url;
return url;
}
}
+10 -2
View File
@@ -216,8 +216,16 @@ export function getAppMenu(
label: "Command Palette...",
accelerator: "Shift+CmdOrCtrl+P",
id: "command-palette",
click() {
broadcastMessage("command-palette:open");
click(_m, _b, event) {
/**
* Don't broadcast unless it was triggered by menu iteration so that
* there aren't double events in renderer
*
* NOTE: this `?` is required because of a bug in playwright. https://github.com/microsoft/playwright/issues/10554
*/
if (!event?.triggeredByAccelerator) {
broadcastMessage("command-palette:open");
}
},
},
{ type: "separator" },
-1
View File
@@ -186,7 +186,6 @@ export class Router {
// Port-forward API (the container port and local forwarding port are obtained from the query parameters)
this.router.add({ method: "post", path: `${apiPrefix}/pods/port-forward/{namespace}/{resourceType}/{resourceName}` }, this.dependencies.routePortForward);
this.router.add({ method: "get", path: `${apiPrefix}/pods/port-forward/{namespace}/{resourceType}/{resourceName}` }, PortForwardRoute.routeCurrentPortForward);
this.router.add({ method: "get", path: `${apiPrefix}/pods/port-forwards` }, PortForwardRoute.routeAllPortForwards);
this.router.add({ method: "delete", path: `${apiPrefix}/pods/port-forward/{namespace}/{resourceType}/{resourceName}` }, PortForwardRoute.routeCurrentPortForwardStop);
// Helm API
+1 -26
View File
@@ -22,7 +22,7 @@
import type { LensApiRequest } from "../router";
import logger from "../logger";
import { respondJson } from "../utils/http-responses";
import { PortForward, PortForwardArgs } from "./port-forward/port-forward";
import { PortForward } from "./port-forward/port-forward";
export class PortForwardRoute {
static async routeCurrentPortForward(request: LensApiRequest) {
@@ -40,31 +40,6 @@ export class PortForwardRoute {
respondJson(response, { port: portForward?.forwardPort ?? null });
}
static async routeAllPortForwards(request: LensApiRequest) {
const { query, response } = request;
const clusterId = query.get("clusterId");
let portForwards: PortForwardArgs[] = PortForward.portForwards.map(f => (
{
clusterId: f.clusterId,
kind: f.kind,
namespace: f.namespace,
name: f.name,
port: f.port,
forwardPort: f.forwardPort,
protocol: f.protocol,
}),
);
if (clusterId) {
// filter out any not for this cluster
portForwards = portForwards.filter(pf => pf.clusterId == clusterId);
}
respondJson(response, { portForwards });
}
static async routeCurrentPortForwardStop(request: LensApiRequest) {
const { params, query, response, cluster } = request;
const { namespace, resourceType, resourceName } = params;
+4 -2
View File
@@ -32,8 +32,10 @@ describe("tray-menu-items", () => {
let trayMenuItems: IComputedValue<TrayMenuRegistration[]>;
let extensionsStub: ObservableMap<string, LensMainExtension>;
beforeEach(() => {
di = getDiForUnitTesting();
beforeEach(async () => {
di = getDiForUnitTesting({ doGeneralOverrides: true });
await di.runSetups();
extensionsStub = new ObservableMap();