Merge branch 'master' into fix/namespace-selector-gradients

This commit is contained in:
Alex Andreev committed 2021-05-20 10:19:32 +03:00
commit 550c678dc8
379 files changed
+4772 -2105

No files matched your search

+156 -35
View File
@@ -20,10 +20,30 @@
*/
import mockFs from "mock-fs";
import { CatalogEntityItem } from "../../renderer/components/+catalog/catalog-entity.store";
import { ClusterStore } from "../cluster-store";
import { HotbarStore } from "../hotbar-store";
jest.mock("../../renderer/api/catalog-entity-registry", () => ({
catalogEntityRegistry: {
items: [
{
metadata: {
uid: "1dfa26e2ebab15780a3547e9c7fa785c",
name: "mycluster",
source: "local"
}
},
{
metadata: {
uid: "55b42c3c7ba3b04193416cda405269a5",
name: "my_shiny_cluster",
source: "remote"
}
}
]
}
}));
const testCluster = {
uid: "test",
name: "test",
@@ -87,6 +107,17 @@ const awsCluster = {
}
};
jest.mock("electron", () => {
return {
app: {
getVersion: () => "99.99.99",
getPath: () => "tmp",
getLocale: () => "en",
setLoginItemSettings: (): void => void 0,
}
};
});
describe("HotbarStore", () => {
beforeEach(() => {
ClusterStore.resetInstance();
@@ -127,10 +158,9 @@ describe("HotbarStore", () => {
it("adds items", () => {
const hotbarStore = HotbarStore.createInstance();
const entity = new CatalogEntityItem(testCluster);
hotbarStore.load();
hotbarStore.addToHotbar(entity);
hotbarStore.addToHotbar(testCluster);
const items = hotbarStore.getActive().items.filter(Boolean);
expect(items.length).toEqual(1);
@@ -138,10 +168,9 @@ describe("HotbarStore", () => {
it("removes items", () => {
const hotbarStore = HotbarStore.createInstance();
const entity = new CatalogEntityItem(testCluster);
hotbarStore.load();
hotbarStore.addToHotbar(entity);
hotbarStore.addToHotbar(testCluster);
hotbarStore.removeFromHotbar("test");
const items = hotbarStore.getActive().items.filter(Boolean);
@@ -150,10 +179,9 @@ describe("HotbarStore", () => {
it("does nothing if removing with invalid uid", () => {
const hotbarStore = HotbarStore.createInstance();
const entity = new CatalogEntityItem(testCluster);
hotbarStore.load();
hotbarStore.addToHotbar(entity);
hotbarStore.addToHotbar(testCluster);
hotbarStore.removeFromHotbar("invalid uid");
const items = hotbarStore.getActive().items.filter(Boolean);
@@ -162,14 +190,11 @@ describe("HotbarStore", () => {
it("moves item to empty cell", () => {
const hotbarStore = HotbarStore.createInstance();
const test = new CatalogEntityItem(testCluster);
const minikube = new CatalogEntityItem(minikubeCluster);
const aws = new CatalogEntityItem(awsCluster);
hotbarStore.load();
hotbarStore.addToHotbar(test);
hotbarStore.addToHotbar(minikube);
hotbarStore.addToHotbar(aws);
hotbarStore.addToHotbar(testCluster);
hotbarStore.addToHotbar(minikubeCluster);
hotbarStore.addToHotbar(awsCluster);
expect(hotbarStore.getActive().items[5]).toBeNull();
@@ -181,14 +206,11 @@ describe("HotbarStore", () => {
it("moves items down", () => {
const hotbarStore = HotbarStore.createInstance();
const test = new CatalogEntityItem(testCluster);
const minikube = new CatalogEntityItem(minikubeCluster);
const aws = new CatalogEntityItem(awsCluster);
hotbarStore.load();
hotbarStore.addToHotbar(test);
hotbarStore.addToHotbar(minikube);
hotbarStore.addToHotbar(aws);
hotbarStore.addToHotbar(testCluster);
hotbarStore.addToHotbar(minikubeCluster);
hotbarStore.addToHotbar(awsCluster);
// aws -> test
hotbarStore.restackItems(2, 0);
@@ -200,14 +222,11 @@ describe("HotbarStore", () => {
it("moves items up", () => {
const hotbarStore = HotbarStore.createInstance();
const test = new CatalogEntityItem(testCluster);
const minikube = new CatalogEntityItem(minikubeCluster);
const aws = new CatalogEntityItem(awsCluster);
hotbarStore.load();
hotbarStore.addToHotbar(test);
hotbarStore.addToHotbar(minikube);
hotbarStore.addToHotbar(aws);
hotbarStore.addToHotbar(testCluster);
hotbarStore.addToHotbar(minikubeCluster);
hotbarStore.addToHotbar(awsCluster);
// test -> aws
hotbarStore.restackItems(0, 2);
@@ -219,10 +238,9 @@ describe("HotbarStore", () => {
it("does nothing when item moved to same cell", () => {
const hotbarStore = HotbarStore.createInstance();
const test = new CatalogEntityItem(testCluster);
hotbarStore.load();
hotbarStore.addToHotbar(test);
hotbarStore.addToHotbar(testCluster);
hotbarStore.restackItems(0, 0);
expect(hotbarStore.getActive().items[0].entity.uid).toEqual("test");
@@ -230,15 +248,12 @@ describe("HotbarStore", () => {
it("new items takes first empty cell", () => {
const hotbarStore = HotbarStore.createInstance();
const test = new CatalogEntityItem(testCluster);
const minikube = new CatalogEntityItem(minikubeCluster);
const aws = new CatalogEntityItem(awsCluster);
hotbarStore.load();
hotbarStore.addToHotbar(test);
hotbarStore.addToHotbar(aws);
hotbarStore.addToHotbar(testCluster);
hotbarStore.addToHotbar(awsCluster);
hotbarStore.restackItems(0, 3);
hotbarStore.addToHotbar(minikube);
hotbarStore.addToHotbar(minikubeCluster);
expect(hotbarStore.getActive().items[0].entity.uid).toEqual("minikube");
});
@@ -250,10 +265,9 @@ describe("HotbarStore", () => {
console.error = jest.fn();
const hotbarStore = HotbarStore.createInstance();
const test = new CatalogEntityItem(testCluster);
hotbarStore.load();
hotbarStore.addToHotbar(test);
hotbarStore.addToHotbar(testCluster);
expect(() => hotbarStore.restackItems(-5, 0)).toThrow();
expect(() => hotbarStore.restackItems(2, -1)).toThrow();
@@ -264,4 +278,111 @@ describe("HotbarStore", () => {
console.error = err;
});
});
describe("pre beta-5 migrations", () => {
beforeEach(() => {
HotbarStore.resetInstance();
const mockOpts = {
"tmp": {
"lens-hotbar-store.json": JSON.stringify({
__internal__: {
migrations: {
version: "5.0.0-beta.3"
}
},
"hotbars": [
{
"id": "3caac17f-aec2-4723-9694-ad204465d935",
"name": "myhotbar",
"items": [
{
"entity": {
"uid": "1dfa26e2ebab15780a3547e9c7fa785c"
}
},
{
"entity": {
"uid": "55b42c3c7ba3b04193416cda405269a5"
}
},
{
"entity": {
"uid": "176fd331968660832f62283219d7eb6e"
}
},
{
"entity": {
"uid": "61c4fb45528840ebad1badc25da41d14",
"name": "user1-context",
"source": "local"
}
},
{
"entity": {
"uid": "27d6f99fe9e7548a6e306760bfe19969",
"name": "foo2",
"source": "local"
}
},
null,
{
"entity": {
"uid": "c0b20040646849bb4dcf773e43a0bf27",
"name": "multinode-demo",
"source": "local"
}
},
null,
null,
null,
null,
null
]
}
],
})
}
};
mockFs(mockOpts);
return HotbarStore.createInstance().load();
});
afterEach(() => {
mockFs.restore();
});
it("allows to retrieve a hotbar", () => {
const hotbar = HotbarStore.getInstance().getById("3caac17f-aec2-4723-9694-ad204465d935");
expect(hotbar.id).toBe("3caac17f-aec2-4723-9694-ad204465d935");
});
it("clears cells without entity", () => {
const items = HotbarStore.getInstance().hotbars[0].items;
expect(items[2]).toBeNull();
});
it("adds extra data to cells with according entity", () => {
const items = HotbarStore.getInstance().hotbars[0].items;
expect(items[0]).toEqual({
entity: {
name: "mycluster",
source: "local",
uid: "1dfa26e2ebab15780a3547e9c7fa785c"
}
});
expect(items[1]).toEqual({
entity: {
name: "my_shiny_cluster",
source: "remote",
uid: "55b42c3c7ba3b04193416cda405269a5"
}
});
});
});
});
@@ -23,6 +23,12 @@ import { SearchStore } from "../search-store";
import { Console } from "console";
import { stdout, stderr } from "process";
jest.mock("electron", () => ({
app: {
getPath: () => "/foo",
},
}));
console = new Console(stdout, stderr);
let searchStore: SearchStore = null;
+1 -1
View File
@@ -21,7 +21,7 @@
import path from "path";
import Config from "conf";
import { Options as ConfOptions } from "conf/dist/source/types";
import type { Options as ConfOptions } from "conf/dist/source/types";
import { app, ipcMain, IpcMainEvent, ipcRenderer, IpcRendererEvent, remote } from "electron";
import { IReactionOptions, observable, reaction, runInAction, when } from "mobx";
import Singleton from "./utils/singleton";
@@ -21,15 +21,31 @@
import { catalogCategoryRegistry } from "../catalog/catalog-category-registry";
import { CatalogEntity, CatalogEntityActionContext, CatalogEntityAddMenuContext, CatalogEntityContextMenuContext, CatalogEntityMetadata, CatalogEntityStatus } from "../catalog";
import { clusterDisconnectHandler } from "../cluster-ipc";
import { clusterActivateHandler, clusterDisconnectHandler } from "../cluster-ipc";
import { ClusterStore } from "../cluster-store";
import { requestMain } from "../ipc";
import { productName } from "../vars";
import { CatalogCategory, CatalogCategorySpec } from "../catalog";
import { app } from "electron";
export type KubernetesClusterPrometheusMetrics = {
address?: {
namespace: string;
service: string;
port: number;
prefix: string;
};
type?: string;
};
export type KubernetesClusterSpec = {
kubeconfigPath: string;
kubeconfigContext: string;
metrics?: {
source: string;
prometheus?: KubernetesClusterPrometheusMetrics;
}
};
export interface KubernetesClusterStatus extends CatalogEntityStatus {
@@ -40,6 +56,38 @@ export class KubernetesCluster extends CatalogEntity<CatalogEntityMetadata, Kube
public readonly apiVersion = "entity.k8slens.dev/v1alpha1";
public readonly kind = "KubernetesCluster";
async connect(): Promise<void> {
if (app) {
const cluster = ClusterStore.getInstance().getById(this.metadata.uid);
if (!cluster) return;
await cluster.activate();
return;
}
await requestMain(clusterActivateHandler, this.metadata.uid, false);
return;
}
async disconnect(): Promise<void> {
if (app) {
const cluster = ClusterStore.getInstance().getById(this.metadata.uid);
if (!cluster) return;
cluster.disconnect();
return;
}
await requestMain(clusterDisconnectHandler, this.metadata.uid, false);
return;
}
async onRun(context: CatalogEntityActionContext) {
context.navigate(`/cluster/${this.metadata.uid}`);
}
@@ -55,7 +103,6 @@ export class KubernetesCluster extends CatalogEntity<CatalogEntityMetadata, Kube
async onContextMenuOpen(context: CatalogEntityContextMenuContext) {
context.menuItems = [
{
icon: "settings",
title: "Settings",
onlyVisibleForSource: "local",
onClick: async () => context.navigate(`/entity/${this.metadata.uid}/settings`)
@@ -64,7 +111,6 @@ export class KubernetesCluster extends CatalogEntity<CatalogEntityMetadata, Kube
if (this.metadata.labels["file"]?.startsWith(ClusterStore.storedKubeConfigFolder)) {
context.menuItems.push({
icon: "delete",
title: "Delete",
onlyVisibleForSource: "local",
onClick: async () => ClusterStore.getInstance().removeById(this.metadata.uid),
@@ -75,14 +121,20 @@ export class KubernetesCluster extends CatalogEntity<CatalogEntityMetadata, Kube
}
if (this.status.phase == "connected") {
context.menuItems.unshift({
icon: "link_off",
context.menuItems.push({
title: "Disconnect",
onClick: async () => {
ClusterStore.getInstance().deactivate(this.metadata.uid);
requestMain(clusterDisconnectHandler, this.metadata.uid);
}
});
} else {
context.menuItems.push({
title: "Connect",
onClick: async () => {
context.navigate(`/cluster/${this.metadata.uid}`);
}
});
}
const category = catalogCategoryRegistry.getCategoryForEntity<KubernetesClusterCategory>(this);
+1 -1
View File
@@ -32,7 +32,7 @@ export type WebLinkSpec = {
export class WebLink extends CatalogEntity<CatalogEntityMetadata, WebLinkStatus, WebLinkSpec> {
public readonly apiVersion = "entity.k8slens.dev/v1alpha1";
public readonly kind = "KubernetesCluster";
public readonly kind = "WebLink";
async onRun() {
window.open(this.spec.url, "_blank");
+23 -17
View File
@@ -19,26 +19,38 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { action, computed, observable, toJS } from "mobx";
import { action, computed, observable } from "mobx";
import { Disposer, ExtendedMap } from "../utils";
import { CatalogCategory, CatalogEntityData, CatalogEntityKindData } from "./catalog-entity";
export class CatalogCategoryRegistry {
@observable protected categories: CatalogCategory[] = [];
protected categories = observable.set<CatalogCategory>();
@action add(category: CatalogCategory) {
this.categories.push(category);
@action add(category: CatalogCategory): Disposer {
this.categories.add(category);
return () => this.categories.delete(category);
}
@action remove(category: CatalogCategory) {
this.categories = this.categories.filter((cat) => cat.apiVersion !== category.apiVersion && cat.kind !== category.kind);
@computed private get groupKindLookup(): Map<string, Map<string, CatalogCategory>> {
// ExtendedMap has the convenience methods `getOrInsert` and `strictSet`
const res = new ExtendedMap<string, ExtendedMap<string, CatalogCategory>>();
for (const category of this.categories) {
res
.getOrInsert(category.spec.group, ExtendedMap.new)
.strictSet(category.spec.names.kind, category);
}
return res;
}
@computed get items() {
return toJS(this.categories);
return Array.from(this.categories);
}
getForGroupKind<T extends CatalogCategory>(group: string, kind: string) {
return this.categories.find((c) => c.spec.group === group && c.spec.names.kind === kind) as T;
getForGroupKind<T extends CatalogCategory>(group: string, kind: string): T | undefined {
return this.groupKindLookup.get(group)?.get(kind) as T;
}
getEntityForData(data: CatalogEntityData & CatalogEntityKindData) {
@@ -60,17 +72,11 @@ export class CatalogCategoryRegistry {
return new specVersion.entityClass(data);
}
getCategoryForEntity<T extends CatalogCategory>(data: CatalogEntityData & CatalogEntityKindData) {
getCategoryForEntity<T extends CatalogCategory>(data: CatalogEntityData & CatalogEntityKindData): T | undefined {
const splitApiVersion = data.apiVersion.split("/");
const group = splitApiVersion[0];
const category = this.categories.find((category) => {
return category.spec.group === group && category.spec.names.kind === data.kind;
});
if (!category) return null;
return category as T;
return this.getForGroupKind(group, data.kind);
}
}
@@ -20,7 +20,7 @@
*/
import { action, computed, observable, IComputedValue, IObservableArray } from "mobx";
import { CatalogEntity } from "./catalog-entity";
import type { CatalogEntity } from "./catalog-entity";
import { iter } from "../utils";
export class CatalogEntityRegistry {
+5 -2
View File
@@ -83,7 +83,6 @@ export interface CatalogEntityActionContext {
}
export interface CatalogEntityContextMenu {
icon: string;
title: string;
onlyVisibleForSource?: string; // show only if empty or if matches with entity source
onClick: () => void | Promise<void>;
@@ -92,6 +91,10 @@ export interface CatalogEntityContextMenu {
}
}
export interface CatalogEntityAddMenu extends CatalogEntityContextMenu {
icon: string;
}
export interface CatalogEntitySettingsMenu {
group?: string;
title: string;
@@ -111,7 +114,7 @@ export interface CatalogEntitySettingsContext {
export interface CatalogEntityAddMenuContext {
navigate: (url: string) => void;
menuItems: CatalogEntityContextMenu[];
menuItems: CatalogEntityAddMenu[];
}
export type CatalogEntitySpec = Record<string, any>;
+35 -12
View File
@@ -31,14 +31,13 @@ export const clusterSetFrameIdHandler = "cluster:set-frame-id";
export const clusterRefreshHandler = "cluster:refresh";
export const clusterDisconnectHandler = "cluster:disconnect";
export const clusterKubectlApplyAllHandler = "cluster:kubectl-apply-all";
export const clusterKubectlDeleteAllHandler = "cluster:kubectl-delete-all";
if (ipcMain) {
handleRequest(clusterActivateHandler, (event, clusterId: ClusterId, force = false) => {
const cluster = ClusterStore.getInstance().getById(clusterId);
if (cluster) {
return cluster.activate(force);
}
return ClusterStore.getInstance()
.getById(clusterId)
?.activate(force);
});
handleRequest(clusterSetFrameIdHandler, (event: IpcMainInvokeEvent, clusterId: ClusterId) => {
@@ -46,15 +45,14 @@ if (ipcMain) {
if (cluster) {
clusterFrameMap.set(cluster.id, { frameId: event.frameId, processId: event.processId });
return cluster.pushState();
cluster.pushState();
}
});
handleRequest(clusterRefreshHandler, (event, clusterId: ClusterId) => {
const cluster = ClusterStore.getInstance().getById(clusterId);
if (cluster) return cluster.refresh({ refreshMetadata: true });
return ClusterStore.getInstance()
.getById(clusterId)
?.refresh({ refreshMetadata: true });
});
handleRequest(clusterDisconnectHandler, (event, clusterId: ClusterId) => {
@@ -67,14 +65,39 @@ if (ipcMain) {
}
});
handleRequest(clusterKubectlApplyAllHandler, (event, clusterId: ClusterId, resources: string[]) => {
handleRequest(clusterKubectlApplyAllHandler, async (event, clusterId: ClusterId, resources: string[], extraArgs: string[]) => {
appEventBus.emit({name: "cluster", action: "kubectl-apply-all"});
const cluster = ClusterStore.getInstance().getById(clusterId);
if (cluster) {
const applier = new ResourceApplier(cluster);
applier.kubectlApplyAll(resources);
try {
const stdout = await applier.kubectlApplyAll(resources, extraArgs);
return { stdout };
} catch (error: any) {
return { stderr: error };
}
} else {
throw `${clusterId} is not a valid cluster id`;
}
});
handleRequest(clusterKubectlDeleteAllHandler, async (event, clusterId: ClusterId, resources: string[], extraArgs: string[]) => {
appEventBus.emit({name: "cluster", action: "kubectl-delete-all"});
const cluster = ClusterStore.getInstance().getById(clusterId);
if (cluster) {
const applier = new ResourceApplier(cluster);
try {
const stdout = await applier.kubectlDeleteAll(resources, extraArgs);
return { stdout };
} catch (error: any) {
return { stderr: error };
}
} else {
throw `${clusterId} is not a valid cluster id`;
}
+2 -2
View File
@@ -30,9 +30,9 @@ import logger from "../main/logger";
import { appEventBus } from "./event-bus";
import { dumpConfigYaml } from "./kube-helpers";
import { saveToAppFiles } from "./utils/saveToAppFiles";
import { KubeConfig } from "@kubernetes/client-node";
import type { KubeConfig } from "@kubernetes/client-node";
import { handleRequest, requestMain, subscribeToBroadcast, unsubscribeAllFromBroadcast } from "./ipc";
import { ResourceType } from "../renderer/components/cluster-settings/components/cluster-metrics-setting";
import type { ResourceType } from "../renderer/components/cluster-settings/components/cluster-metrics-setting";
import { disposer, noop } from "./utils";
export interface ClusterIconUpload {
+4 -5
View File
@@ -53,12 +53,11 @@ export class EventEmitter<D extends [...any[]]> {
emit(...data: D) {
[...this.listeners].every(([callback, options]) => {
if (options.once) this.removeListener(callback);
const result = callback(...data);
if (options.once) {
this.removeListener(callback);
}
if (result === false) return; // break cycle
return true;
return callback(...data) !== false;
});
}
}
+17 -5
View File
@@ -23,12 +23,14 @@ import { action, comparer, observable, toJS } from "mobx";
import { BaseStore } from "./base-store";
import migrations from "../migrations/hotbar-store";
import * as uuid from "uuid";
import { CatalogEntityItem } from "../renderer/components/+catalog/catalog-entity.store";
import isNull from "lodash/isNull";
import { CatalogEntity } from "./catalog";
export interface HotbarItem {
entity: {
uid: string;
name?: string;
source?: string;
};
params?: {
[key: string]: string;
@@ -79,8 +81,12 @@ export class HotbarStore extends BaseStore<HotbarStoreModel> {
}
}
hotbarIndex(id: string) {
return this.hotbars.findIndex((hotbar) => hotbar.id === id);
}
get activeHotbarIndex() {
return this.hotbars.findIndex((hotbar) => hotbar.id === this.activeHotbarId);
return this.hotbarIndex(this.activeHotbarId);
}
get initialItems() {
@@ -144,11 +150,16 @@ export class HotbarStore extends BaseStore<HotbarStoreModel> {
}
}
addToHotbar(item: CatalogEntityItem, cellIndex = -1) {
@action
addToHotbar(item: CatalogEntity, cellIndex = -1) {
const hotbar = this.getActive();
const newItem = { entity: { uid: item.id }};
const newItem = { entity: {
uid: item.metadata.uid,
name: item.metadata.name,
source: item.metadata.source
}};
if (hotbar.items.find(i => i?.entity.uid === item.id)) {
if (hotbar.items.find(i => i?.entity.uid === item.metadata.uid)) {
return;
}
@@ -167,6 +178,7 @@ export class HotbarStore extends BaseStore<HotbarStoreModel> {
}
}
@action
removeFromHotbar(uid: string) {
const hotbar = this.getActive();
const index = hotbar.items.findIndex((i) => i?.entity.uid === uid);
+19 -21
View File
@@ -42,35 +42,33 @@ function getSubFrames(): ClusterFrameInfo[] {
return toJS(Array.from(clusterFrameMap.values()), { recurseEverything: true });
}
export async function broadcastMessage(channel: string, ...args: any[]) {
export function broadcastMessage(channel: string, ...args: any[]) {
const views = (webContents || remote?.webContents)?.getAllWebContents();
if (!views) return;
if (ipcRenderer) {
ipcRenderer.send(channel, ...args);
} else if (ipcMain) {
ipcMain.emit(channel, ...args);
}
ipcRenderer?.send(channel, ...args);
ipcMain?.emit(channel, ...args);
for (const view of views) {
const type = view.getType();
const subFramesP = ipcRenderer
? requestMain(subFramesChannel)
: Promise.resolve(getSubFrames());
logger.silly(`[IPC]: broadcasting "${channel}" to ${type}=${view.id}`, { args });
view.send(channel, ...args);
subFramesP
.then(subFrames => {
for (const view of views) {
try {
logger.silly(`[IPC]: broadcasting "${channel}" to ${view.getType()}=${view.id}`, { args });
view.send(channel, ...args);
try {
const subFrames: ClusterFrameInfo[] = ipcRenderer
? await requestMain(subFramesChannel)
: getSubFrames();
for (const frameInfo of subFrames) {
view.sendToFrame([frameInfo.processId, frameInfo.frameId], channel, ...args);
for (const frameInfo of subFrames) {
view.sendToFrame([frameInfo.processId, frameInfo.frameId], channel, ...args);
}
} catch (error) {
logger.error("[IPC]: failed to send IPC message", { error: String(error) });
}
}
} catch (error) {
logger.error("[IPC]: failed to send IPC message", { error: String(error) });
}
}
});
}
export function subscribeToBroadcast(channel: string, listener: (...args: any[]) => any) {
+50 -20
View File
@@ -19,10 +19,12 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { EventEmitter } from "events";
import type { EventEmitter } from "events";
import { ipcMain } from "electron";
import logger from "../../main/logger";
import type { Disposer } from "../utils";
export type HandlerEvent<EM extends EventEmitter> = Parameters<Parameters<EM["on"]>[1]>[0];
export type ListenerEvent<EM extends EventEmitter> = Parameters<Parameters<EM["on"]>[1]>[0];
export type ListVerifier<T extends any[]> = (args: unknown[]) => args is T;
export type Rest<T> = T extends [any, ...infer R] ? R : [];
@@ -34,22 +36,22 @@ export type Rest<T> = T extends [any, ...infer R] ? R : [];
* @param verifier The function to be called to verify that the args are the correct type
*/
export function onceCorrect<
EM extends EventEmitter,
L extends (event: HandlerEvent<EM>, ...args: any[]) => any
IPC extends EventEmitter,
Listener extends (event: ListenerEvent<IPC>, ...args: any[]) => any
>({
source,
channel,
listener,
verifier,
}: {
source: EM,
channel: string | symbol,
listener: L,
verifier: ListVerifier<Rest<Parameters<L>>>,
source: IPC,
channel: string,
listener: Listener,
verifier: ListVerifier<Rest<Parameters<Listener>>>,
}): void {
function handler(event: HandlerEvent<EM>, ...args: unknown[]): void {
function wrappedListener(event: ListenerEvent<IPC>, ...args: unknown[]): void {
if (verifier(args)) {
source.removeListener(channel, handler); // remove immediately
source.removeListener(channel, wrappedListener); // remove immediately
(async () => (listener(event, ...args)))() // might return a promise, or throw, or reject
.catch((error: any) => logger.error("[IPC]: channel once handler threw error", { channel, error }));
@@ -58,7 +60,7 @@ export function onceCorrect<
}
}
source.on(channel, handler);
source.on(channel, wrappedListener);
}
/**
@@ -68,25 +70,53 @@ export function onceCorrect<
* @param verifier The function to be called to verify that the args are the correct type
*/
export function onCorrect<
EM extends EventEmitter,
L extends (event: HandlerEvent<EM>, ...args: any[]) => any
IPC extends EventEmitter,
Listener extends (event: ListenerEvent<IPC>, ...args: any[]) => any
>({
source,
channel,
listener,
verifier,
}: {
source: EM,
channel: string | symbol,
listener: L,
verifier: ListVerifier<Rest<Parameters<L>>>,
}): void {
source.on(channel, (event, ...args: unknown[]) => {
source: IPC,
channel: string,
listener: Listener,
verifier: ListVerifier<Rest<Parameters<Listener>>>,
}): Disposer {
function wrappedListener(event: ListenerEvent<IPC>, ...args: unknown[]) {
if (verifier(args)) {
(async () => (listener(event, ...args)))() // might return a promise, or throw, or reject
.catch(error => logger.error("[IPC]: channel on handler threw error", { channel, error }));
} else {
logger.error("[IPC]: channel was emitted with invalid data", { channel, args });
}
});
}
source.on(channel, wrappedListener);
return () => source.off(channel, wrappedListener);
}
export function handleCorrect<
Handler extends (event: Electron.IpcMainInvokeEvent, ...args: any[]) => any,
>({
channel,
handler,
verifier,
}: {
channel: string,
handler: Handler,
verifier: ListVerifier<Rest<Parameters<Handler>>>,
}): Disposer {
function wrappedHandler(event: Electron.IpcMainInvokeEvent, ...args: unknown[]): ReturnType<Handler> {
if (verifier(args)) {
return handler(event, ...args);
}
throw new TypeError(`Invalid args for invoke on channel: ${channel}`);
}
ipcMain.handle(channel, wrappedHandler);
return () => ipcMain.removeHandler(channel);
}
+1 -1
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { UpdateInfo } from "electron-updater";
import type { UpdateInfo } from "electron-updater";
export const UpdateAvailableChannel = "update-available";
export const AutoUpdateLogPrefix = "[UPDATE-CHECKER]";
+152
View File
@@ -0,0 +1,152 @@
/**
* 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 fse from "fs-extra";
import path from "path";
import hb from "handlebars";
import { ResourceApplier } from "../../main/resource-applier";
import type { KubernetesCluster } from "../catalog-entities";
import logger from "../../main/logger";
import { app } from "electron";
import { requestMain } from "../ipc";
import { clusterKubectlApplyAllHandler, clusterKubectlDeleteAllHandler } from "../cluster-ipc";
import { ClusterStore } from "../cluster-store";
import yaml from "js-yaml";
import { productName } from "../vars";
export class ResourceStack {
constructor(protected cluster: KubernetesCluster, protected name: string) {}
/**
*
* @param folderPath folder path that is searched for files defining kubernetes resources.
* @param templateContext sets the template parameters that are to be applied to any templated kubernetes resources that are to be applied.
*/
async kubectlApplyFolder(folderPath: string, templateContext?: any, extraArgs?: string[]): Promise<string> {
const resources = await this.renderTemplates(folderPath, templateContext);
return this.applyResources(resources, extraArgs);
}
/**
*
* @param folderPath folder path that is searched for files defining kubernetes resources.
* @param templateContext sets the template parameters that are to be applied to any templated kubernetes resources that are to be applied.
*/
async kubectlDeleteFolder(folderPath: string, templateContext?: any, extraArgs?: string[]): Promise<string> {
const resources = await this.renderTemplates(folderPath, templateContext);
return this.deleteResources(resources, extraArgs);
}
protected async applyResources(resources: string[], extraArgs?: string[]): Promise<string> {
const clusterModel = ClusterStore.getInstance().getById(this.cluster.metadata.uid);
if (!clusterModel) {
throw new Error(`cluster not found`);
}
let kubectlArgs = extraArgs || [];
kubectlArgs = this.appendKubectlArgs(kubectlArgs);
if (app) {
return await new ResourceApplier(clusterModel).kubectlApplyAll(resources, kubectlArgs);
} else {
const response = await requestMain(clusterKubectlApplyAllHandler, this.cluster.metadata.uid, resources, kubectlArgs);
if (response.stderr) {
throw new Error(response.stderr);
}
return response.stdout;
}
}
protected async deleteResources(resources: string[], extraArgs?: string[]): Promise<string> {
const clusterModel = ClusterStore.getInstance().getById(this.cluster.metadata.uid);
if (!clusterModel) {
throw new Error(`cluster not found`);
}
let kubectlArgs = extraArgs || [];
kubectlArgs = this.appendKubectlArgs(kubectlArgs);
if (app) {
return await new ResourceApplier(clusterModel).kubectlDeleteAll(resources, kubectlArgs);
} else {
const response = await requestMain(clusterKubectlDeleteAllHandler, this.cluster.metadata.uid, resources, kubectlArgs);
if (response.stderr) {
throw new Error(response.stderr);
}
return response.stdout;
}
}
protected appendKubectlArgs(kubectlArgs: string[]) {
if (!kubectlArgs.includes("-l") && !kubectlArgs.includes("--label")) {
return kubectlArgs.concat(["-l", `app.kubernetes.io/name=${this.name}`]);
}
return kubectlArgs;
}
protected async renderTemplates(folderPath: string, templateContext: any): Promise<string[]> {
const resources: string[] = [];
logger.info(`[RESOURCE-STACK]: render templates from ${folderPath}`);
const files = await fse.readdir(folderPath);
for(const filename of files) {
const file = path.join(folderPath, filename);
const raw = await fse.readFile(file);
let resourceData: string;
if (filename.endsWith(".hb")) {
const template = hb.compile(raw.toString());
resourceData = template(templateContext);
} else {
resourceData = raw.toString();
}
if (!resourceData.trim()) continue;
const resourceArray = yaml.safeLoadAll(resourceData.toString());
resourceArray.forEach((resource) => {
if (resource?.metadata) {
resource.metadata.labels ||= {};
resource.metadata.labels["app.kubernetes.io/name"] = this.name;
resource.metadata.labels["app.kubernetes.io/managed-by"] = productName;
resource.metadata.labels["app.kubernetes.io/created-by"] = "resource-stack";
}
resources.push(yaml.safeDump(resource));
});
}
return resources;
}
}
+1 -1
View File
@@ -230,7 +230,7 @@ export function getNodeWarningConditions(node: V1Node) {
*
* Note: This function returns an error instead of throwing it, returning `undefined` if the validation passes
*/
export function validateKubeConfig(config: KubeConfig, contextName: string, validationOpts: KubeConfigValidationOpts = {}): Error | undefined {
export function validateKubeConfig(config: KubeConfig, contextName: string, validationOpts: KubeConfigValidationOpts = {}): Error | void {
try {
// we only receive a single context, cluster & user object here so lets validate them as this
// will be called when we add a new cluster to Lens
+3 -1
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Url from "url-parse";
import type Url from "url-parse";
export enum RoutingErrorType {
INVALID_PROTOCOL = "invalid-protocol",
@@ -52,6 +52,8 @@ export class RoutingError extends Error {
return "no extension ID";
case RoutingErrorType.MISSING_EXTENSION:
return "extension not found";
default:
return `unknown error: ${this.type}`;
}
}
}
+3 -3
View File
@@ -24,12 +24,12 @@ import { countBy } from "lodash";
import { Singleton } from "../utils";
import { pathToRegexp } from "path-to-regexp";
import logger from "../../main/logger";
import Url from "url-parse";
import type Url from "url-parse";
import { RoutingError, RoutingErrorType } from "./error";
import { ExtensionsStore } from "../../extensions/extensions-store";
import { ExtensionLoader } from "../../extensions/extension-loader";
import { LensExtension } from "../../extensions/lens-extension";
import { RouteHandler, RouteParams } from "../../extensions/registries/protocol-handler-registry";
import type { LensExtension } from "../../extensions/lens-extension";
import type { RouteHandler, RouteParams } from "../../extensions/registries/protocol-handler-registry";
// IPC channel for protocol actions. Main broadcasts the open-url events to this channel.
export const ProtocolHandlerIpcPrefix = "protocol-handler";
+1 -1
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { AbortController } from "abort-controller";
import type { AbortController } from "abort-controller";
/**
* Return a promise that will be resolved after at least `timeout` ms have
+29 -14
View File
@@ -22,19 +22,17 @@
import { action, IEnhancer, IObservableMapInitialValues, ObservableMap } from "mobx";
export class ExtendedMap<K, V> extends Map<K, V> {
constructor(protected getDefault: () => V, entries?: readonly (readonly [K, V])[] | null) {
super(entries);
static new<K, V>(entries?: readonly (readonly [K, V])[] | null): ExtendedMap<K, V> {
return new ExtendedMap<K, V>(entries);
}
getOrInsert(key: K, val: V): V {
if (this.has(key)) {
return this.get(key);
}
return this.set(key, val).get(key);
}
getOrInsertWith(key: K, getVal: () => V): V {
/**
* Get the value behind `key`. If it was not pressent, first insert the value returned by `getVal`
* @param key The key to insert into the map with
* @param getVal A function that returns a new instance of `V`.
* @returns The value in the map
*/
getOrInsert(key: K, getVal: () => V): V {
if (this.has(key)) {
return this.get(key);
}
@@ -42,12 +40,29 @@ export class ExtendedMap<K, V> extends Map<K, V> {
return this.set(key, getVal()).get(key);
}
getOrDefault(key: K): V {
/**
* Set the value associated with `key` iff there was not a previous value
* @throws if `key` already in map
* @returns `this` so that `strictSet` can be chained
*/
strictSet(key: K, val: V): this {
if (this.has(key)) {
return this.get(key);
throw new TypeError("Duplicate key in map");
}
return this.set(key, this.getDefault()).get(key);
return this.set(key, val);
}
/**
* Get the value associated with `key`
* @throws if `key` did not a value associated with it
*/
strictGet(key: K): V {
if (!this.has(key)) {
throw new TypeError("key not in map");
}
return this.get(key);
}
}
+34 -2
View File
@@ -19,6 +19,8 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
export type Falsey = false | 0 | "" | null | undefined;
/**
* Create a new type safe empty Iterable
* @returns An `Iterable` that yields 0 items
@@ -57,6 +59,36 @@ export function* map<T, U>(src: Iterable<T>, fn: (from: T) => U): Iterable<U> {
}
}
/**
* The single layer flattening of an iterator, discarding `Falsey` values.
* @param src A type that can be iterated over
* @param fn The function that returns either an iterable over items that should be filtered out or a `Falsey` value indicating that it should be ignored
*/
export function* filterFlatMap<T, U>(src: Iterable<T>, fn: (from: T) => Iterable<U | Falsey> | Falsey): Iterable<U> {
for (const from of src) {
if (!from) {
continue;
}
const mapping = fn(from);
if (!mapping) {
continue;
}
for (const mapped of mapping) {
if (mapped) {
yield mapped;
}
}
}
}
/**
* Returns a new iterator that yields the items that each call to `fn` would produce
* @param src A type that can be iterated over
* @param fn A function that returns an iterator
*/
export function* flatMap<T, U>(src: Iterable<T>, fn: (from: T) => Iterable<U>): Iterable<U> {
for (const from of src) {
yield* fn(from);
@@ -83,7 +115,7 @@ export function* filter<T>(src: Iterable<T>, fn: (from: T) => any): Iterable<T>
* @param src A type that can be iterated over
* @param fn The function that is called for each value
*/
export function* filterMap<T, U>(src: Iterable<T>, fn: (from: T) => U): Iterable<U> {
export function* filterMap<T, U>(src: Iterable<T>, fn: (from: T) => U | Falsey): Iterable<U> {
for (const from of src) {
const res = fn(from);
@@ -99,7 +131,7 @@ export function* filterMap<T, U>(src: Iterable<T>, fn: (from: T) => U): Iterable
* @param src A type that can be iterated over
* @param fn The function that is called for each value
*/
export function* filterMapStrict<T, U>(src: Iterable<T>, fn: (from: T) => U): Iterable<U> {
export function* filterMapStrict<T, U>(src: Iterable<T>, fn: (from: T) => U | null | undefined): Iterable<U> {
for (const from of src) {
const res = fn(from);
+1 -1
View File
@@ -23,7 +23,7 @@
import path from "path";
import { app, remote } from "electron";
import { ensureDirSync, writeFileSync } from "fs-extra";
import { WriteFileOptions } from "fs";
import type { WriteFileOptions } from "fs";
export function saveToAppFiles(filePath: string, contents: any, options?: WriteFileOptions): string {
const absPath = path.resolve((app || remote.app).getPath("userData"), filePath);
@@ -77,6 +77,8 @@ jest.mock(
],
];
}
return [];
}),
on: jest.fn(
(channel: string, listener: (event: any, ...args: any[]) => void) => {
-156
View File
@@ -1,156 +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 fs from "fs";
import path from "path";
import hb from "handlebars";
import { observable } from "mobx";
import { ResourceApplier } from "../main/resource-applier";
import { KubernetesCluster } from "./core-api/catalog";
import logger from "../main/logger";
import { app } from "electron";
import { requestMain } from "../common/ipc";
import { clusterKubectlApplyAllHandler } from "../common/cluster-ipc";
import { ClusterStore } from "../common/cluster-store";
export interface ClusterFeatureStatus {
/** feature's current version, as set by the implementation */
currentVersion: string;
/** feature's latest version, as set by the implementation */
latestVersion: string;
/** whether the feature is installed or not, as set by the implementation */
installed: boolean;
/** whether the feature can be upgraded or not, as set by the implementation */
canUpgrade: boolean;
}
export abstract class ClusterFeature {
/**
* this field sets the template parameters that are to be applied to any templated kubernetes resources that are to be installed for the feature.
* See the renderTemplates() method for more details
*/
templateContext: any;
/**
* this field holds the current feature status, is accessed directly by Lens
*/
@observable status: ClusterFeatureStatus = {
currentVersion: null,
installed: false,
latestVersion: null,
canUpgrade: false
};
/**
* to be implemented in the derived class, this method is typically called by Lens when a user has indicated that this feature is to be installed. The implementation
* of this method should install kubernetes resources using the applyResources() method, or by directly accessing the kubernetes api (K8sApi)
*
* @param cluster the cluster that the feature is to be installed on
*/
abstract install(cluster: KubernetesCluster): Promise<void>;
/**
* to be implemented in the derived class, this method is typically called by Lens when a user has indicated that this feature is to be upgraded. The implementation
* of this method should upgrade the kubernetes resources already installed, if relevant to the feature
*
* @param cluster the cluster that the feature is to be upgraded on
*/
abstract upgrade(cluster: KubernetesCluster): Promise<void>;
/**
* to be implemented in the derived class, this method is typically called by Lens when a user has indicated that this feature is to be uninstalled. The implementation
* of this method should uninstall kubernetes resources using the kubernetes api (K8sApi)
*
* @param cluster the cluster that the feature is to be uninstalled from
*/
abstract uninstall(cluster: KubernetesCluster): Promise<void>;
/**
* to be implemented in the derived class, this method is called periodically by Lens to determine details about the feature's current status. The implementation
* of this method should provide the current status information. The currentVersion and latestVersion fields may be displayed by Lens in describing the feature.
* The installed field should be set to true if the feature has been installed, otherwise false. Also, Lens relies on the canUpgrade field to determine if the feature
* can be upgraded so the implementation should set the canUpgrade field according to specific rules for the feature, if relevant.
*
* @param cluster the cluster that the feature may be installed on
*
* @return a promise, resolved with the updated ClusterFeatureStatus
*/
abstract updateStatus(cluster: KubernetesCluster): Promise<ClusterFeatureStatus>;
/**
* this is a helper method that conveniently applies kubernetes resources to the cluster.
*
* @param cluster the cluster that the resources are to be applied to
* @param resourceSpec as a string type this is a folder path that is searched for files specifying kubernetes resources. The files are read and if any of the resource
* files are templated, the template parameters are filled using the templateContext field (See renderTemplate() method). Finally the resources are applied to the
* cluster. As a string[] type resourceSpec is treated as an array of fully formed (not templated) kubernetes resources that are applied to the cluster
*/
protected async applyResources(cluster: KubernetesCluster, resourceSpec: string | string[]) {
let resources: string[];
const clusterModel = ClusterStore.getInstance().getById(cluster.metadata.uid);
if (!clusterModel) {
throw new Error(`cluster not found`);
}
if ( typeof resourceSpec === "string" ) {
resources = this.renderTemplates(resourceSpec);
} else {
resources = resourceSpec;
}
if (app) {
await new ResourceApplier(clusterModel).kubectlApplyAll(resources);
} else {
await requestMain(clusterKubectlApplyAllHandler, cluster.metadata.uid, resources);
}
}
/**
* this is a helper method that conveniently reads kubernetes resource files into a string array. It also fills templated resource files with the template parameter values
* specified by the templateContext field. Templated files must end with the extension '.hb' and the template syntax must be compatible with handlebars.js
*
* @param folderPath this is a folder path that is searched for files defining kubernetes resources.
*
* @return an array of strings, each string being the contents of a resource file found in the folder path. This can be passed directly to applyResources()
*/
protected renderTemplates(folderPath: string): string[] {
const resources: string[] = [];
logger.info(`[FEATURE]: render templates from ${folderPath}`);
fs.readdirSync(folderPath).forEach(filename => {
const file = path.join(folderPath, filename);
const raw = fs.readFileSync(file);
if (filename.endsWith(".hb")) {
const template = hb.compile(raw.toString());
resources.push(template(this.templateContext));
} else {
resources.push(raw.toString());
}
});
return resources;
}
}
+2 -2
View File
@@ -28,16 +28,16 @@ import * as App from "./app";
import * as EventBus from "./event-bus";
import * as Store from "./stores";
import * as Util from "./utils";
import * as ClusterFeature from "./cluster-feature";
import * as Interface from "../interfaces";
import * as Catalog from "./catalog";
import * as Types from "./types";
export {
App,
EventBus,
Catalog,
ClusterFeature,
Interface,
Store,
Types,
Util,
};
+2
View File
@@ -20,3 +20,5 @@
*/
export { ExtensionStore } from "../extension-store";
export { MainIpcStore } from "../main-ipc-store";
export { RendererIpcStore } from "../renderer-ipc-store";
@@ -19,5 +19,6 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
export { ClusterFeature as Feature } from "../cluster-feature";
export type { ClusterFeatureStatus as FeatureStatus } from "../cluster-feature";
export type IpcMainInvokeEvent = Electron.IpcMainInvokeEvent;
export type IpcRendererEvent = Electron.IpcRendererEvent;
export type IpcMainEvent = Electron.IpcMainEvent;
+4 -1
View File
@@ -342,10 +342,13 @@ export class ExtensionDiscovery extends Singleton {
const manifest = await fse.readJson(manifestPath);
const installedManifestPath = this.getInstalledManifestPath(manifest.name);
const isEnabled = isBundled || ExtensionsStore.getInstance().isEnabled(installedManifestPath);
const extensionDir = path.dirname(manifestPath);
const npmPackage = path.join(extensionDir, `${manifest.name}-${manifest.version}.tgz`);
const absolutePath = (await fse.pathExists(npmPackage)) ? npmPackage : extensionDir;
return {
id: installedManifestPath,
absolutePath: path.dirname(manifestPath),
absolutePath,
manifestPath: installedManifestPath,
manifest,
isBundled,
+2
View File
@@ -325,6 +325,8 @@ export class ExtensionLoader extends Singleton {
} catch (error) {
logger.error(`${logModule}: can't load extension main at ${extAbsolutePath}: ${error}`, { extension, error });
}
return null;
}
getExtension(extId: LensExtensionId): InstalledExtension {
+1 -1
View File
@@ -21,7 +21,7 @@
import { BaseStore } from "../common/base-store";
import * as path from "path";
import { LensExtension } from "./lens-extension";
import type { LensExtension } from "./lens-extension";
export abstract class ExtensionStore<T> extends BaseStore<T> {
protected extension: LensExtension;
+39
View File
@@ -0,0 +1,39 @@
/**
* 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 { Singleton } from "../common/utils";
import type { LensExtension } from "./lens-extension";
import { createHash } from "crypto";
import { broadcastMessage } from "../common/ipc";
export const IpcPrefix = Symbol();
export abstract class IpcStore extends Singleton {
readonly [IpcPrefix]: string;
constructor(protected extension: LensExtension) {
super();
this[IpcPrefix] = createHash("sha256").update(extension.id).digest("hex");
}
broadcastIpc(channel: string, ...args: any[]): void {
broadcastMessage(`extensions@${this[IpcPrefix]}:${channel}`, ...args);
}
}
+16 -11
View File
@@ -23,7 +23,8 @@ import type { InstalledExtension } from "./extension-discovery";
import { action, observable, reaction } from "mobx";
import { FilesystemProvisionerStore } from "../main/extension-filesystem";
import logger from "../main/logger";
import { ProtocolHandlerRegistration } from "./registries/protocol-handler-registry";
import type { ProtocolHandlerRegistration } from "./registries";
import { disposer } from "../common/utils";
export type LensExtensionId = string; // path to manifest (package.json)
export type LensExtensionConstructor = new (...args: ConstructorParameters<typeof LensExtension>) => LensExtension;
@@ -37,6 +38,8 @@ export interface LensExtensionManifest {
lens?: object; // fixme: add more required fields for validation
}
export const Disposers = Symbol();
export class LensExtension {
readonly id: LensExtensionId;
readonly manifest: LensExtensionManifest;
@@ -46,6 +49,7 @@ export class LensExtension {
protocolHandlers: ProtocolHandlerRegistration[] = [];
@observable private isEnabled = false;
[Disposers] = disposer();
constructor({ id, manifest, manifestPath, isBundled }: InstalledExtension) {
this.id = id;
@@ -62,6 +66,10 @@ export class LensExtension {
return this.manifest.version;
}
get description() {
return this.manifest.description;
}
/**
* getExtensionFileFolder returns the path to an already created folder. This
* folder is for the sole use of this extension.
@@ -73,15 +81,11 @@ export class LensExtension {
return FilesystemProvisionerStore.getInstance().requestDirectory(this.id);
}
get description() {
return this.manifest.description;
}
@action
async enable() {
if (this.isEnabled) return;
this.isEnabled = true;
this.onActivate();
this.onActivate?.();
logger.info(`[EXTENSION]: enabled ${this.name}@${this.version}`);
}
@@ -89,7 +93,8 @@ export class LensExtension {
async disable() {
if (!this.isEnabled) return;
this.isEnabled = false;
this.onDeactivate();
this.onDeactivate?.();
this[Disposers]();
logger.info(`[EXTENSION]: disabled ${this.name}@${this.version}`);
}
@@ -125,12 +130,12 @@ export class LensExtension {
};
}
protected onActivate() {
// mock
protected onActivate(): void {
return;
}
protected onDeactivate() {
// mock
protected onDeactivate(): void {
return;
}
}
+2 -2
View File
@@ -19,12 +19,12 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import type { MenuRegistration } from "./registries/menu-registry";
import { LensExtension } from "./lens-extension";
import { WindowManager } from "../main/window-manager";
import { getExtensionPageUrl } from "./registries/page-registry";
import { CatalogEntity, catalogEntityRegistry } from "../common/catalog";
import { IObservableArray } from "mobx";
import type { IObservableArray } from "mobx";
import type { MenuRegistration } from "./registries";
export class LensMainExtension extends LensExtension {
appMenus: MenuRegistration[] = [];
+2 -2
View File
@@ -26,8 +26,8 @@ import type {
import type { Cluster } from "../main/cluster";
import { LensExtension } from "./lens-extension";
import { getExtensionPageUrl } from "./registries/page-registry";
import { CommandRegistration } from "./registries/command-registry";
import { EntitySettingRegistration } from "./registries/entity-setting-registry";
import type { CommandRegistration } from "./registries/command-registry";
import type { EntitySettingRegistration } from "./registries/entity-setting-registry";
export class LensRendererExtension extends LensExtension {
globalPages: PageRegistration[] = [];
+45
View File
@@ -0,0 +1,45 @@
/**
* 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 { ipcMain } from "electron";
import { IpcPrefix, IpcStore } from "./ipc-store";
import { Disposers } from "./lens-extension";
import type { LensMainExtension } from "./lens-main-extension";
export abstract class MainIpcStore extends IpcStore {
constructor(extension: LensMainExtension) {
super(extension);
extension[Disposers].push(() => MainIpcStore.resetInstance());
}
handleIpc(channel: string, handler: (event: Electron.IpcMainInvokeEvent, ...args: any[]) => any): void {
const prefixedChannel = `extensions@${this[IpcPrefix]}:${channel}`;
ipcMain.handle(prefixedChannel, handler);
this.extension[Disposers].push(() => ipcMain.removeHandler(prefixedChannel));
}
listenIpc(channel: string, listener: (event: Electron.IpcMainEvent, ...args: any[]) => any): void {
const prefixedChannel = `extensions@${this[IpcPrefix]}:${channel}`;
ipcMain.addListener(prefixedChannel, listener);
this.extension[Disposers].push(() => ipcMain.removeListener(prefixedChannel, listener));
}
}
@@ -20,7 +20,7 @@
*/
import type React from "react";
import { CatalogEntity } from "../../common/catalog";
import type { CatalogEntity } from "../../common/catalog";
import { BaseRegistry } from "./base-registry";
export interface EntitySettingViewProps {
@@ -32,13 +32,14 @@ export interface EntitySettingComponents {
}
export interface EntitySettingRegistration {
title: string;
kind: string;
apiVersions: string[];
source?: string;
kind: string;
title: string;
components: EntitySettingComponents;
source?: string;
id?: string;
priority?: number;
group?: string;
}
export interface RegisteredEntitySetting extends EntitySettingRegistration {
+1
View File
@@ -32,3 +32,4 @@ export * from "./kube-object-status-registry";
export * from "./command-registry";
export * from "./entity-setting-registry";
export * from "./welcome-menu-registry";
export * from "./protocol-handler-registry";
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from "react";
import type React from "react";
import { BaseRegistry } from "./base-registry";
export interface KubeObjectDetailComponents {
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from "react";
import type React from "react";
import { BaseRegistry } from "./base-registry";
export interface KubeObjectMenuComponents {
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { KubeObject, KubeObjectStatus } from "../renderer-api/k8s-api";
import type { KubeObject, KubeObjectStatus } from "../renderer-api/k8s-api";
import { BaseRegistry } from "./base-registry";
export interface KubeObjectStatusRegistration {
+3 -3
View File
@@ -25,7 +25,7 @@ import React from "react";
import { observer } from "mobx-react";
import { BaseRegistry } from "./base-registry";
import { LensExtension, sanitizeExtensionName } from "../lens-extension";
import { PageParam, PageParamInit } from "../../renderer/navigation/page-param";
import type { PageParam, PageParamInit } from "../../renderer/navigation/page-param";
import { createPageParam } from "../../renderer/navigation/helpers";
export interface PageRegistration {
@@ -119,9 +119,9 @@ export class PageRegistry extends BaseRegistry<PageRegistration, RegisteredPage>
return components;
}
protected normalizeParams(params?: PageParams<string | ExtensionPageParamInit>): PageParams<PageParam> {
protected normalizeParams(params?: PageParams<string | ExtensionPageParamInit>): PageParams<PageParam> | undefined {
if (!params) {
return;
return undefined;
}
Object.entries(params).forEach(([name, value]) => {
const paramInit: PageParamInit = typeof value === "object"
@@ -21,7 +21,7 @@
// Extensions API -> Status bar customizations
import React from "react";
import type React from "react";
import { BaseRegistry } from "./base-registry";
interface StatusBarComponents {
@@ -30,6 +30,7 @@ export * from "../../renderer/components/checkbox";
export * from "../../renderer/components/radio";
export * from "../../renderer/components/select";
export * from "../../renderer/components/slider";
export * from "../../renderer/components/switch";
export * from "../../renderer/components/input/input";
// command-overlay
+11 -4
View File
@@ -20,11 +20,12 @@
*/
export { isAllowedResource } from "../../common/rbac";
export { ResourceStack } from "../../common/k8s/resource-stack";
export { apiManager } from "../../renderer/api/api-manager";
export { KubeObjectStore } from "../../renderer/kube-object.store";
export { KubeApi, forCluster, IKubeApiCluster } from "../../renderer/api/kube-api";
export { KubeApi, forCluster } from "../../renderer/api/kube-api";
export { KubeObject } from "../../renderer/api/kube-object";
export { Pod, podsApi, PodsApi, IPodContainer, IPodContainerStatus } from "../../renderer/api/endpoints";
export { Pod, podsApi, PodsApi } from "../../renderer/api/endpoints";
export { Node, nodesApi, NodesApi } from "../../renderer/api/endpoints";
export { Deployment, deploymentApi, DeploymentApi } from "../../renderer/api/endpoints";
export { DaemonSet, daemonSetApi } from "../../renderer/api/endpoints";
@@ -32,7 +33,7 @@ export { StatefulSet, statefulSetApi } from "../../renderer/api/endpoints";
export { Job, jobApi } from "../../renderer/api/endpoints";
export { CronJob, cronJobApi } from "../../renderer/api/endpoints";
export { ConfigMap, configMapApi } from "../../renderer/api/endpoints";
export { Secret, secretsApi, ISecretRef } from "../../renderer/api/endpoints";
export { Secret, secretsApi } from "../../renderer/api/endpoints";
export { ReplicaSet, replicaSetApi } from "../../renderer/api/endpoints";
export { ResourceQuota, resourceQuotaApi } from "../../renderer/api/endpoints";
export { LimitRange, limitRangeApi } from "../../renderer/api/endpoints";
@@ -53,7 +54,13 @@ export { RoleBinding, roleBindingApi } from "../../renderer/api/endpoints";
export { ClusterRole, clusterRoleApi } from "../../renderer/api/endpoints";
export { ClusterRoleBinding, clusterRoleBindingApi } from "../../renderer/api/endpoints";
export { CustomResourceDefinition, crdApi } from "../../renderer/api/endpoints";
export { KubeObjectStatus, KubeObjectStatusLevel } from "./kube-object-status";
export { KubeObjectStatusLevel } from "./kube-object-status";
// types
export type { IKubeApiCluster } from "../../renderer/api/kube-api";
export type { IPodContainer, IPodContainerStatus } from "../../renderer/api/endpoints";
export type { ISecretRef } from "../../renderer/api/endpoints";
export type { KubeObjectStatus } from "./kube-object-status";
// stores
export type { EventStore } from "../../renderer/components/+events/event.store";
+1 -1
View File
@@ -25,7 +25,7 @@ import { navigation } from "../../renderer/navigation";
export type { PageParamInit, PageParam } from "../../renderer/navigation/page-param";
export { navigate, isActiveRoute } from "../../renderer/navigation/helpers";
export { hideDetails, showDetails, getDetailsUrl } from "../../renderer/components/kube-object/kube-object-details";
export { IURLParams } from "../../common/utils/buildUrl";
export type { IURLParams } from "../../common/utils/buildUrl";
// exporting to extensions-api version of helper without `isSystem` flag
export function createPageParam<V = string>(init: PageParamInit<V>) {
+44
View File
@@ -0,0 +1,44 @@
/**
* 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 { ipcRenderer } from "electron";
import { IpcPrefix, IpcStore } from "./ipc-store";
import { Disposers } from "./lens-extension";
import type { LensRendererExtension } from "./lens-renderer-extension";
export abstract class RendererIpcStore extends IpcStore {
constructor(extension: LensRendererExtension) {
super(extension);
extension[Disposers].push(() => RendererIpcStore.resetInstance());
}
listenIpc(channel: string, listener: (event: Electron.IpcRendererEvent, ...args: any[]) => any): void {
const prefixedChannel = `extensions@${this[IpcPrefix]}:${channel}`;
ipcRenderer.addListener(prefixedChannel, listener);
this.extension[Disposers].push(() => ipcRenderer.removeListener(prefixedChannel, listener));
}
invokeIpc(channel: string, ...args: any[]): Promise<any> {
const prefixedChannel = `extensions@${this[IpcPrefix]}:${channel}`;
return ipcRenderer.invoke(prefixedChannel, ...args);
}
}
+21
View File
@@ -1,3 +1,24 @@
/**
* 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 fetchMock from "jest-fetch-mock";
// rewire global.fetch to call 'fetchMock'
fetchMock.enableMocks();
+7 -1
View File
@@ -44,6 +44,12 @@ jest.mock("winston", () => ({
}
}));
jest.mock("electron", () => ({
app: {
getPath: () => "/foo",
},
}));
jest.mock("../../common/ipc");
jest.mock("child_process");
jest.mock("tcp-port-used");
@@ -56,7 +62,7 @@ import { ChildProcess, spawn } from "child_process";
import { bundledKubectlPath, Kubectl } from "../kubectl";
import { mock, MockProxy } from "jest-mock-extended";
import { waitUntilUsed } from "tcp-port-used";
import { Readable } from "stream";
import type { Readable } from "stream";
import { UserStore } from "../../common/user-store";
import { Console } from "console";
import { stdout, stderr } from "process";
+11 -3
View File
@@ -28,6 +28,12 @@ const logger = {
crit: jest.fn(),
};
jest.mock("electron", () => ({
app: {
getPath: () => `/tmp`,
},
}));
jest.mock("winston", () => ({
format: {
colorize: jest.fn(),
@@ -47,7 +53,7 @@ jest.mock("winston", () => ({
import { KubeconfigManager } from "../kubeconfig-manager";
import mockFs from "mock-fs";
import { Cluster } from "../cluster";
import { ContextHandler } from "../context-handler";
import type { ContextHandler } from "../context-handler";
import fse from "fs-extra";
import { loadYaml } from "@kubernetes/client-node";
import { Console } from "console";
@@ -91,7 +97,9 @@ describe("kubeconfig manager tests", () => {
contextName: "minikube",
kubeConfigPath: "minikube-config.yml",
});
contextHandler = jest.fn() as any;
contextHandler = {
ensureServer: () => Promise.resolve(),
} as any;
jest.spyOn(KubeconfigManager.prototype, "resolveProxyUrl", "get").mockReturnValue("http://127.0.0.1:9191/foo");
});
@@ -103,7 +111,7 @@ describe("kubeconfig manager tests", () => {
const kubeConfManager = new KubeconfigManager(cluster, contextHandler);
expect(logger.error).not.toBeCalled();
expect(await kubeConfManager.getPath()).toBe(`tmp${path.sep}kubeconfig-foo`);
expect(await kubeConfManager.getPath()).toBe(`${path.sep}tmp${path.sep}kubeconfig-foo`);
// this causes an intermittent "ENXIO: no such device or address, read" error
// const file = await fse.readFile(await kubeConfManager.getPath());
const file = fse.readFileSync(await kubeConfManager.getPath());
+2 -2
View File
@@ -21,9 +21,9 @@
import { reaction, toJS } from "mobx";
import { broadcastMessage, subscribeToBroadcast, unsubscribeFromBroadcast } from "../common/ipc";
import { CatalogEntityRegistry} from "../common/catalog";
import type { CatalogEntityRegistry} from "../common/catalog";
import "../common/catalog-entities/kubernetes-cluster";
import { Disposer } from "../common/utils";
import type { Disposer } from "../common/utils";
export class CatalogPusher {
static init(catalog: CatalogEntityRegistry) {
@@ -20,9 +20,9 @@
*/
import { ObservableMap } from "mobx";
import { CatalogEntity } from "../../../common/catalog";
import type { CatalogEntity } from "../../../common/catalog";
import { loadFromOptions } from "../../../common/kube-helpers";
import { Cluster } from "../../cluster";
import type { Cluster } from "../../cluster";
import { computeDiff, configToModels } from "../kubeconfig-sync";
import mockFs from "mock-fs";
import fs from "fs";
+2 -2
View File
@@ -24,10 +24,10 @@ import { CatalogEntity, catalogEntityRegistry } from "../../common/catalog";
import { watch } from "chokidar";
import fs from "fs";
import fse from "fs-extra";
import stream from "stream";
import type stream from "stream";
import { Disposer, ExtendedObservableMap, iter, Singleton } from "../../common/utils";
import logger from "../logger";
import { KubeConfig } from "@kubernetes/client-node";
import type { KubeConfig } from "@kubernetes/client-node";
import { loadConfigFromString, splitConfig, validateKubeConfig } from "../../common/kube-helpers";
import { Cluster } from "../cluster";
import { catalogEntityFromCluster } from "../cluster-manager";
@@ -19,8 +19,8 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { RequestPromiseOptions } from "request-promise-native";
import { Cluster } from "../cluster";
import type { RequestPromiseOptions } from "request-promise-native";
import type { Cluster } from "../cluster";
import { k8sRequest } from "../k8s-request";
export type ClusterDetectionResult = {
@@ -20,9 +20,9 @@
*/
import { observable } from "mobx";
import { ClusterMetadata } from "../../common/cluster-store";
import { Cluster } from "../cluster";
import { BaseClusterDetector, ClusterDetectionResult } from "./base-cluster-detector";
import type { ClusterMetadata } from "../../common/cluster-store";
import type { Cluster } from "../cluster";
import type { BaseClusterDetector, ClusterDetectionResult } from "./base-cluster-detector";
import { ClusterIdDetector } from "./cluster-id-detector";
import { DistributionDetector } from "./distribution-detector";
import { LastSeenDetector } from "./last-seen-detector";
+14 -3
View File
@@ -24,12 +24,12 @@ import type http from "http";
import { ipcMain } from "electron";
import { action, autorun, reaction, toJS } from "mobx";
import { ClusterStore, getClusterIdFromHost } from "../common/cluster-store";
import { Cluster } from "./cluster";
import type { Cluster } from "./cluster";
import logger from "./logger";
import { apiKubePrefix } from "../common/vars";
import { Singleton } from "../common/utils";
import { catalogEntityRegistry } from "../common/catalog";
import { KubernetesCluster } from "../common/catalog-entities/kubernetes-cluster";
import { KubernetesCluster, KubernetesClusterPrometheusMetrics } from "../common/catalog-entities/kubernetes-cluster";
export class ClusterManager extends Singleton {
constructor() {
@@ -68,7 +68,7 @@ export class ClusterManager extends Singleton {
const index = catalogEntityRegistry.items.findIndex((entity) => entity.metadata.uid === cluster.id);
if (index !== -1) {
const entity = catalogEntityRegistry.items[index];
const entity = catalogEntityRegistry.items[index] as KubernetesCluster;
entity.status.phase = cluster.disconnected ? "disconnected" : "connected";
entity.status.active = !cluster.disconnected;
@@ -76,6 +76,17 @@ export class ClusterManager extends Singleton {
if (cluster.preferences?.clusterName) {
entity.metadata.name = cluster.preferences.clusterName;
}
entity.spec.metrics ||= { source: "local" };
if (entity.spec.metrics.source === "local") {
const prometheus: KubernetesClusterPrometheusMetrics = entity.spec?.metrics?.prometheus || {};
prometheus.type = cluster.preferences.prometheusProvider?.type;
prometheus.address = cluster.preferences.prometheus;
entity.spec.metrics.prometheus = prometheus;
}
catalogEntityRegistry.items.splice(index, 1, entity);
}
}
+5 -6
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import type { PrometheusProvider, PrometheusService } from "./prometheus/provider-registry";
import type { PrometheusService } from "./prometheus/provider-registry";
import type { ClusterPrometheusPreferences } from "../common/cluster-store";
import type { Cluster } from "./cluster";
import type httpProxy from "http-proxy";
@@ -75,16 +75,15 @@ export class ContextHandler {
return prometheusProviders.find(p => p.id === this.prometheusProvider);
}
async getPrometheusService(): Promise<PrometheusService> {
async getPrometheusService(): Promise<PrometheusService | void> {
const providers = this.prometheusProvider ? prometheusProviders.filter(provider => provider.id == this.prometheusProvider) : prometheusProviders;
const prometheusPromises: Promise<PrometheusService>[] = providers.map(async (provider: PrometheusProvider): Promise<PrometheusService> => {
const prometheusPromises: Promise<PrometheusService | void>[] = providers.map(async provider => {
const apiClient = (await this.cluster.getProxyKubeconfig()).makeApiClient(CoreV1Api);
return await provider.getPrometheusService(apiClient);
return provider.getPrometheusService(apiClient);
});
const resolvedPrometheusServices = await Promise.all(prometheusPromises);
return resolvedPrometheusServices.filter(n => n)[0];
return (await Promise.all(prometheusPromises)).find(Boolean);
}
async getPrometheusPath(): Promise<string> {
+1 -1
View File
@@ -26,7 +26,7 @@ import fse from "fs-extra";
import { action, observable, toJS } from "mobx";
import path from "path";
import { BaseStore } from "../common/base-store";
import { LensExtensionId } from "../extensions/lens-extension";
import type { LensExtensionId } from "../extensions/lens-extension";
interface FSProvisionModel {
extensions: Record<string, string>; // extension names to paths
@@ -22,7 +22,7 @@
import { HelmRepo, HelmRepoManager } from "../helm-repo-manager";
export class HelmChartManager {
private cache: any = {};
cache: any = {};
private repo: HelmRepo;
constructor(repo: HelmRepo){
+1 -1
View File
@@ -24,7 +24,7 @@ import fse from "fs-extra";
import * as yaml from "js-yaml";
import { promiseExec} from "../promise-exec";
import { helmCli } from "./helm-cli";
import { Cluster } from "../cluster";
import type { Cluster } from "../cluster";
import { toCamelCase } from "../../common/utils/camelCase";
export async function listReleases(pathToKubeconfig: string, namespace?: string) {
+2 -2
View File
@@ -20,11 +20,11 @@
*/
import semver from "semver";
import { Cluster } from "../cluster";
import type { Cluster } from "../cluster";
import logger from "../logger";
import { HelmRepoManager } from "./helm-repo-manager";
import { HelmChartManager } from "./helm-chart-manager";
import { HelmChartList, RepoHelmChartList } from "../../renderer/api/endpoints/helm-charts.api";
import type { HelmChartList, RepoHelmChartList } from "../../renderer/api/endpoints/helm-charts.api";
import { deleteRelease, getHistory, getRelease, getValues, installChart, listReleases, rollback, upgradeRelease } from "./helm-release-manager";
class HelmService {
+2 -2
View File
@@ -21,9 +21,9 @@
import request, { RequestPromiseOptions } from "request-promise-native";
import { apiKubePrefix } from "../common/vars";
import { IMetricsReqParams } from "../renderer/api/endpoints/metrics.api";
import type { IMetricsReqParams } from "../renderer/api/endpoints/metrics.api";
import { LensProxy } from "./proxy/lens-proxy";
import { Cluster } from "./cluster";
import type { Cluster } from "./cluster";
export async function k8sRequest<T = any>(cluster: Cluster, path: string, options: RequestPromiseOptions = {}): Promise<T> {
const kubeProxyUrl = `http://localhost:${LensProxy.getInstance().port}${apiKubePrefix}`;
+2 -1
View File
@@ -71,6 +71,7 @@ export class KubeconfigManager {
await this.contextHandler.ensureServer();
this.tempFile = await this.createProxyKubeconfig();
} catch (err) {
console.log(err);
logger.error(`Failed to created temp config for auth-proxy`, { err });
}
}
@@ -86,7 +87,7 @@ export class KubeconfigManager {
protected async createProxyKubeconfig(): Promise<string> {
const { configDir, cluster } = this;
const { contextName, kubeConfigPath, id } = cluster;
const tempFile = path.join(configDir, `kubeconfig-${id}`);
const tempFile = path.normalize(path.join(configDir, `kubeconfig-${id}`));
const kubeConfig = loadConfig(kubeConfigPath);
const proxyConfig: Partial<KubeConfig> = {
currentContext: contextName,
+2 -1
View File
@@ -47,7 +47,8 @@ const kubectlMap: Map<string, string> = new Map([
["1.17", "1.17.17"],
["1.18", bundledVersion],
["1.19", "1.19.7"],
["1.20", "1.20.2"]
["1.20", "1.20.2"],
["1.21", "1.21.1"]
]);
const packageMirrors: Map<string, string> = new Map([
["default", "https://storage.googleapis.com/kubernetes-release/release"],
+2 -2
View File
@@ -25,7 +25,7 @@ import request from "request";
import { ensureDir, pathExists } from "fs-extra";
import * as tar from "tar";
import { isWindows } from "../common/vars";
import winston from "winston";
import type winston from "winston";
export type LensBinaryOpts = {
version: string;
@@ -204,7 +204,7 @@ export class LensBinary {
throw(error);
});
return new Promise((resolve, reject) => {
return new Promise<void>((resolve, reject) => {
file.on("close", () => {
this.logger.debug(`${this.originalBinaryName} binary download closed`);
if (!this.tarPath) fs.chmod(binaryPath, 0o755, (err) => {
+1 -1
View File
@@ -21,7 +21,7 @@
import { app, BrowserWindow, dialog, ipcMain, IpcMainEvent, Menu, MenuItem, MenuItemConstructorOptions, webContents, shell } from "electron";
import { autorun } from "mobx";
import { WindowManager } from "./window-manager";
import type { WindowManager } from "./window-manager";
import { appName, isMac, isWindows, isTestEnv, docsUrl, supportUrl, productName } from "../common/vars";
import { addClusterURL } from "../renderer/components/+add-cluster/add-cluster.route";
import { preferencesURL } from "../renderer/components/+preferences/preferences.route";
+3 -3
View File
@@ -20,8 +20,8 @@
*/
import { PrometheusLens } from "./lens";
import { CoreV1Api } from "@kubernetes/client-node";
import { PrometheusService } from "./provider-registry";
import type { CoreV1Api } from "@kubernetes/client-node";
import type { PrometheusService } from "./provider-registry";
import logger from "../logger";
export class PrometheusHelm extends PrometheusLens {
@@ -29,7 +29,7 @@ export class PrometheusHelm extends PrometheusLens {
name = "Helm";
rateAccuracy = "5m";
public async getPrometheusService(client: CoreV1Api): Promise<PrometheusService> {
public async getPrometheusService(client: CoreV1Api): Promise<PrometheusService | void> {
const labelSelector = "app=prometheus,component=server,heritage=Helm";
try {
+4 -4
View File
@@ -19,8 +19,8 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { PrometheusProvider, PrometheusQueryOpts, PrometheusQuery, PrometheusService } from "./provider-registry";
import { CoreV1Api } from "@kubernetes/client-node";
import type { PrometheusProvider, PrometheusQueryOpts, PrometheusQuery, PrometheusService } from "./provider-registry";
import type { CoreV1Api } from "@kubernetes/client-node";
import logger from "../logger";
export class PrometheusLens implements PrometheusProvider {
@@ -28,7 +28,7 @@ export class PrometheusLens implements PrometheusProvider {
name = "Lens";
rateAccuracy = "1m";
public async getPrometheusService(client: CoreV1Api): Promise<PrometheusService> {
public async getPrometheusService(client: CoreV1Api): Promise<PrometheusService | void> {
try {
const resp = await client.readNamespacedService("prometheus", "lens-metrics");
const service = resp.body;
@@ -44,7 +44,7 @@ export class PrometheusLens implements PrometheusProvider {
}
}
public getQueries(opts: PrometheusQueryOpts): PrometheusQuery {
public getQueries(opts: PrometheusQueryOpts): PrometheusQuery | void {
switch(opts.category) {
case "cluster":
return {
+4 -4
View File
@@ -19,8 +19,8 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { PrometheusProvider, PrometheusQueryOpts, PrometheusQuery, PrometheusService } from "./provider-registry";
import { CoreV1Api, V1Service } from "@kubernetes/client-node";
import type { PrometheusProvider, PrometheusQueryOpts, PrometheusQuery, PrometheusService } from "./provider-registry";
import type { CoreV1Api, V1Service } from "@kubernetes/client-node";
import logger from "../logger";
export class PrometheusOperator implements PrometheusProvider {
@@ -28,7 +28,7 @@ export class PrometheusOperator implements PrometheusProvider {
id = "operator";
name = "Prometheus Operator";
public async getPrometheusService(client: CoreV1Api): Promise<PrometheusService> {
public async getPrometheusService(client: CoreV1Api): Promise<PrometheusService | void> {
try {
let service: V1Service;
@@ -54,7 +54,7 @@ export class PrometheusOperator implements PrometheusProvider {
}
}
public getQueries(opts: PrometheusQueryOpts): PrometheusQuery {
public getQueries(opts: PrometheusQueryOpts): PrometheusQuery | void {
switch(opts.category) {
case "cluster":
return {
+3 -3
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { CoreV1Api } from "@kubernetes/client-node";
import type { CoreV1Api } from "@kubernetes/client-node";
export type PrometheusClusterQuery = {
memoryUsage: string;
@@ -83,8 +83,8 @@ export type PrometheusService = {
export interface PrometheusProvider {
id: string;
name: string;
getQueries(opts: PrometheusQueryOpts): PrometheusQuery;
getPrometheusService(client: CoreV1Api): Promise<PrometheusService>;
getQueries(opts: PrometheusQueryOpts): PrometheusQuery | void;
getPrometheusService(client: CoreV1Api): Promise<PrometheusService | void>;
}
export type PrometheusProviderList = {
+4 -4
View File
@@ -19,8 +19,8 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { PrometheusProvider, PrometheusQueryOpts, PrometheusQuery, PrometheusService } from "./provider-registry";
import { CoreV1Api } from "@kubernetes/client-node";
import type { PrometheusProvider, PrometheusQueryOpts, PrometheusQuery, PrometheusService } from "./provider-registry";
import type { CoreV1Api } from "@kubernetes/client-node";
import logger from "../logger";
export class PrometheusStacklight implements PrometheusProvider {
@@ -28,7 +28,7 @@ export class PrometheusStacklight implements PrometheusProvider {
name = "Stacklight";
rateAccuracy = "1m";
public async getPrometheusService(client: CoreV1Api): Promise<PrometheusService> {
public async getPrometheusService(client: CoreV1Api): Promise<PrometheusService | void> {
try {
const resp = await client.readNamespacedService("prometheus-server", "stacklight");
const service = resp.body;
@@ -44,7 +44,7 @@ export class PrometheusStacklight implements PrometheusProvider {
}
}
public getQueries(opts: PrometheusQueryOpts): PrometheusQuery {
public getQueries(opts: PrometheusQueryOpts): PrometheusQuery | void {
switch(opts.category) {
case "cluster":
return {
+1 -1
View File
@@ -22,7 +22,7 @@
import logger from "../logger";
import * as proto from "../../common/protocol-handler";
import Url from "url-parse";
import { LensExtension } from "../../extensions/lens-extension";
import type { LensExtension } from "../../extensions/lens-extension";
import { broadcastMessage } from "../../common/ipc";
import { observable, when } from "mobx";
+2
View File
@@ -21,3 +21,5 @@
// Don't export the contents here
// It will break the extension webpack
export default {};
+4 -4
View File
@@ -20,13 +20,13 @@
*/
import net from "net";
import http from "http";
import type http from "http";
import spdy from "spdy";
import httpProxy from "http-proxy";
import url from "url";
import { apiPrefix, apiKubePrefix } from "../../common/vars";
import { Router } from "../router";
import { ContextHandler } from "../context-handler";
import type { ContextHandler } from "../context-handler";
import logger from "../logger";
import { Singleton } from "../../common/utils";
import { ClusterManager } from "../cluster-manager";
@@ -205,13 +205,13 @@ export class LensProxy extends Singleton {
return proxy;
}
protected async getProxyTarget(req: http.IncomingMessage, contextHandler: ContextHandler): Promise<httpProxy.ServerOptions> {
protected async getProxyTarget(req: http.IncomingMessage, contextHandler: ContextHandler): Promise<httpProxy.ServerOptions | void> {
if (req.url.startsWith(apiKubePrefix)) {
delete req.headers.authorization;
req.url = req.url.replace(apiKubePrefix, "");
const isWatchRequest = req.url.includes("watch=");
return await contextHandler.getApiTarget(isWatchRequest);
return contextHandler.getApiTarget(isWatchRequest);
}
}
+2 -2
View File
@@ -26,8 +26,8 @@
*/
import * as WebSocket from "ws";
import http from "http";
import net from "net";
import type http from "http";
import type net from "net";
import url from "url";
import { NodeShellSession, LocalShellSession } from "../shell-session";
import { ClusterManager } from "../cluster-manager";
+22 -9
View File
@@ -20,7 +20,7 @@
*/
import type { Cluster } from "./cluster";
import { KubernetesObject } from "@kubernetes/client-node";
import type { KubernetesObject } from "@kubernetes/client-node";
import { exec } from "child_process";
import fs from "fs";
import * as yaml from "js-yaml";
@@ -73,7 +73,15 @@ export class ResourceApplier {
});
}
public async kubectlApplyAll(resources: string[]): Promise<string> {
public async kubectlApplyAll(resources: string[], extraArgs = ["-o", "json"]): Promise<string> {
return this.kubectlCmdAll("apply", resources, extraArgs);
}
public async kubectlDeleteAll(resources: string[], extraArgs?: string[]): Promise<string> {
return this.kubectlCmdAll("delete", resources, extraArgs);
}
protected async kubectlCmdAll(subCmd: string, resources: string[], args: string[] = []): Promise<string> {
const { kubeCtl } = this.cluster;
const kubectlPath = await kubeCtl.getPath();
const proxyKubeconfigPath = await this.cluster.getProxyKubeconfigPath();
@@ -85,19 +93,24 @@ export class ResourceApplier {
resources.forEach((resource, index) => {
fs.writeFileSync(path.join(tmpDir, `${index}.yaml`), resource);
});
const cmd = `"${kubectlPath}" apply --kubeconfig "${proxyKubeconfigPath}" -o json -f "${tmpDir}"`;
args.push("-f", `"${tmpDir}"`);
const cmd = `"${kubectlPath}" ${subCmd} --kubeconfig "${proxyKubeconfigPath}" ${args.join(" ")}`;
console.log("shooting manifests with:", cmd);
exec(cmd, (error, stdout, stderr) => {
logger.info(`[RESOURCE-APPLIER] running cmd ${cmd}`);
exec(cmd, (error, stdout) => {
if (error) {
reject(`Error applying manifests:${error}`);
}
logger.error(`[RESOURCE-APPLIER] cmd errored: ${error}`);
const splitError = error.toString().split(`.yaml": `);
if (stderr != "") {
reject(stderr);
if (splitError[1]) {
reject(splitError[1]);
} else {
reject(error);
}
return;
}
resolve(stdout);
});
});
+2 -2
View File
@@ -21,10 +21,10 @@
import Call from "@hapi/call";
import Subtext from "@hapi/subtext";
import http from "http";
import type http from "http";
import path from "path";
import { readFile } from "fs-extra";
import { Cluster } from "./cluster";
import type { Cluster } from "./cluster";
import { apiPrefix, appName, publicPath, isDevelopment, webpackDevServerPort } from "../common/vars";
import { HelmApiRoute, KubeconfigRoute, MetricsRoute, PortForwardRoute, ResourceApplierApiRoute, VersionRoute } from "./routes";
import logger from "./logger";
+1 -1
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { LensApiRequest } from "../router";
import type { LensApiRequest } from "../router";
import { helmService } from "../helm/helm-service";
import { respondJson, respondText } from "../utils/http-responses";
import logger from "../logger";
+2 -2
View File
@@ -19,9 +19,9 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { LensApiRequest } from "../router";
import type { LensApiRequest } from "../router";
import { respondJson } from "../utils/http-responses";
import { Cluster } from "../cluster";
import type { Cluster } from "../cluster";
import { CoreV1Api, V1Secret } from "@kubernetes/client-node";
function generateKubeConfig(username: string, secret: V1Secret, cluster: Cluster) {
+2 -2
View File
@@ -20,10 +20,10 @@
*/
import _ from "lodash";
import { LensApiRequest } from "../router";
import type { LensApiRequest } from "../router";
import { respondJson } from "../utils/http-responses";
import { Cluster, ClusterMetadataKey } from "../cluster";
import { ClusterPrometheusMetadata } from "../../common/cluster-store";
import type { ClusterPrometheusMetadata } from "../../common/cluster-store";
import logger from "../logger";
import { getMetrics } from "../k8s-request";
+1 -1
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { LensApiRequest } from "../router";
import type { LensApiRequest } from "../router";
import { spawn, ChildProcessWithoutNullStreams } from "child_process";
import { Kubectl } from "../kubectl";
import { shell } from "electron";
+1 -1
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { LensApiRequest } from "../router";
import type { LensApiRequest } from "../router";
import { respondJson, respondText } from "../utils/http-responses";
import { ResourceApplier } from "../resource-applier";
+1 -1
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { LensApiRequest } from "../router";
import type { LensApiRequest } from "../router";
import { respondJson } from "../utils/http-responses";
import { getAppVersion } from "../../common/utils";
+9 -4
View File
@@ -19,11 +19,11 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import * as WebSocket from "ws";
import type * 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 type { KubeConfig } from "@kubernetes/client-node";
import type { Cluster } from "../cluster";
import { ShellOpenError, ShellSession } from "./shell-session";
export class NodeShellSession extends ShellSession {
@@ -77,7 +77,7 @@ export class NodeShellSession extends ShellSession {
}],
containers: [{
name: "shell",
image: "docker.io/alpine:3.12",
image: "docker.io/alpine:3.13",
securityContext: {
privileged: true,
},
@@ -120,6 +120,11 @@ export class NodeShellSession extends ShellSession {
});
}
protected exit() {
super.exit();
this.deleteNodeShellPod();
}
protected deleteNodeShellPod() {
this
.kc
+2 -2
View File
@@ -19,9 +19,9 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { Cluster } from "../cluster";
import type { Cluster } from "../cluster";
import { Kubectl } from "../kubectl";
import * as WebSocket from "ws";
import type * as WebSocket from "ws";
import shellEnv from "shell-env";
import { app } from "electron";
import { clearKubeconfigEnvVars } from "../utils/clear-kube-env-vars";
+1 -1
View File
@@ -25,7 +25,7 @@ import { Menu, Tray } from "electron";
import { autorun } from "mobx";
import { showAbout } from "./menu";
import { checkForUpdates, isAutoUpdateEnabled } from "./app-updater";
import { WindowManager } from "./window-manager";
import type { WindowManager } from "./window-manager";
import { preferencesURL } from "../renderer/components/+preferences/preferences.route";
import logger from "./logger";
import { isDevelopment, isWindows, productName } from "../common/vars";
+1 -1
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { Readable } from "stream";
import type { Readable } from "stream";
import URLParse from "url-parse";
interface GetPortArgs {
+1 -1
View File
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import http from "http";
import type http from "http";
export function respondJson(res: http.ServerResponse, content: any, status = 200) {
respond(res, JSON.stringify(content), "application/json", status);
@@ -1,3 +1,24 @@
/**
* 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.
*/
/* Early store format had the kubeconfig directly under context name, this moves
it under the kubeConfig key */
+21
View File
@@ -1,3 +1,24 @@
/**
* 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.
*/
// Cleans up a store that had the state related data stored
import { migration } from "../migration-wrapper";
@@ -1,3 +1,24 @@
/**
* 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.
*/
// Move cluster icon from root to preferences
import { migration } from "../migration-wrapper";
+21 -1
View File
@@ -1,3 +1,24 @@
/**
* 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 { migration } from "../migration-wrapper";
import yaml from "js-yaml";
@@ -42,4 +63,3 @@ export default migration({
}
}
});
@@ -1,3 +1,24 @@
/**
* 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.
*/
// Add existing clusters to "default" workspace
import { migration } from "../migration-wrapper";
@@ -1,3 +1,24 @@
/**
* 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.
*/
// Add id for clusters and store them to array
import { migration } from "../migration-wrapper";
import { v4 as uuid } from "uuid";
@@ -1,3 +1,24 @@
/**
* 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.
*/
// Move embedded kubeconfig into separate file and add reference to it to cluster settings
// convert file path cluster icons to their base64 encoded versions
+21
View File
@@ -1,3 +1,24 @@
/**
* 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.
*/
// Cluster store migrations
import version200Beta2 from "./2.0.0-beta.2";
+22 -1
View File
@@ -1,7 +1,28 @@
/**
* 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.
*/
// Fix embedded kubeconfig paths under snap config
import { migration } from "../migration-wrapper";
import { ClusterModel } from "../../common/cluster-store";
import type { ClusterModel } from "../../common/cluster-store";
import { getAppVersion } from "../../common/utils/app-version";
import fs from "fs";
+22 -1
View File
@@ -1,5 +1,26 @@
/**
* 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.
*/
// Cleans up a store that had the state related data stored
import { Hotbar } from "../../common/hotbar-store";
import type { Hotbar } from "../../common/hotbar-store";
import { ClusterStore } from "../../common/cluster-store";
import { migration } from "../migration-wrapper";
import { v4 as uuid } from "uuid";
+22 -1
View File
@@ -1,5 +1,26 @@
/**
* 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.
*/
// Cleans up a store that had the state related data stored
import { Hotbar } from "../../common/hotbar-store";
import type { Hotbar } from "../../common/hotbar-store";
import { migration } from "../migration-wrapper";
import * as uuid from "uuid";
@@ -0,0 +1,51 @@
/**
* 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 type { Hotbar } from "../../common/hotbar-store";
import { migration } from "../migration-wrapper";
import { catalogEntityRegistry } from "../../renderer/api/catalog-entity-registry";
export default migration({
version: "5.0.0-beta.5",
run(store) {
const hotbars: Hotbar[] = store.get("hotbars");
hotbars.forEach((hotbar, hotbarIndex) => {
hotbar.items.forEach((item, itemIndex) => {
const entity = catalogEntityRegistry.items.find((entity) => entity.metadata.uid === item?.entity.uid);
if (!entity) {
// Clear disabled item
hotbars[hotbarIndex].items[itemIndex] = null;
} else {
// Save additional data
hotbars[hotbarIndex].items[itemIndex].entity = {
...item.entity,
name: entity.metadata.name,
source: entity.metadata.source
};
}
});
});
store.set("hotbars", hotbars);
}
});
Loaded 100 of 379 files, more files were not shown because too many files have changed in this diff. Show more