From 2943175dd1f054fb3e12ce3a9007317057f33b30 Mon Sep 17 00:00:00 2001 From: Jari Kolehmainen Date: Tue, 11 May 2021 11:15:24 +0300 Subject: [PATCH] tweak resource applier/stack Signed-off-by: Jari Kolehmainen --- src/common/cluster-ipc.ts | 8 ++--- src/common/k8s/resource-stack.ts | 58 +++++++++++++++++++++++++------- src/main/resource-applier.ts | 16 +++++---- 3 files changed, 59 insertions(+), 23 deletions(-) diff --git a/src/common/cluster-ipc.ts b/src/common/cluster-ipc.ts index f543dc34f7..abf698c37a 100644 --- a/src/common/cluster-ipc.ts +++ b/src/common/cluster-ipc.ts @@ -47,7 +47,7 @@ if (ipcMain) { } }); - handleRequest(clusterKubectlApplyAllHandler, async (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); @@ -55,7 +55,7 @@ if (ipcMain) { const applier = new ResourceApplier(cluster); try { - const stdout = await applier.kubectlApplyAll(resources); + const stdout = await applier.kubectlApplyAll(resources, extraArgs); return { stdout }; } catch (error: any) { @@ -66,7 +66,7 @@ if (ipcMain) { } }); - handleRequest(clusterKubectlDeleteAllHandler, async (event, clusterId: ClusterId, resources: string[]) => { + handleRequest(clusterKubectlDeleteAllHandler, async (event, clusterId: ClusterId, resources: string[], extraArgs: string[]) => { appEventBus.emit({name: "cluster", action: "kubectl-delete-all"}); const cluster = ClusterStore.getInstance().getById(clusterId); @@ -74,7 +74,7 @@ if (ipcMain) { const applier = new ResourceApplier(cluster); try { - const stdout = await applier.kubectlApplyAll(resources); + const stdout = await applier.kubectlDeleteAll(resources, extraArgs); return { stdout }; } catch (error: any) { diff --git a/src/common/k8s/resource-stack.ts b/src/common/k8s/resource-stack.ts index 392cfab258..f344dba07b 100644 --- a/src/common/k8s/resource-stack.ts +++ b/src/common/k8s/resource-stack.ts @@ -8,19 +8,21 @@ 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) {} + 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): Promise { + async kubectlApplyFolder(folderPath: string, templateContext?: any, extraArgs?: string[]): Promise { const resources = this.renderTemplates(folderPath, templateContext); - return this.applyResources(resources); + return this.applyResources(resources, extraArgs); } /** @@ -28,23 +30,27 @@ export class ResourceStack { * @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): Promise { + async kubectlDeleteFolder(folderPath: string, templateContext?: any, extraArgs?: string[]): Promise { const resources = this.renderTemplates(folderPath, templateContext); - return this.deleteResources(resources); + return this.deleteResources(resources, extraArgs); } - protected async applyResources(resources: string[]): Promise { + protected async applyResources(resources: string[], extraArgs?: string[]): Promise { 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); + return await new ResourceApplier(clusterModel).kubectlApplyAll(resources, kubectlArgs); } else { - const response = await requestMain(clusterKubectlApplyAllHandler, this.cluster.metadata.uid, resources); + const response = await requestMain(clusterKubectlApplyAllHandler, this.cluster.metadata.uid, resources, kubectlArgs); if (response.stderr) { throw new Error(response.stderr); @@ -54,17 +60,21 @@ export class ResourceStack { } } - protected async deleteResources(resources: string[]): Promise { + protected async deleteResources(resources: string[], extraArgs?: string[]): Promise { 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); + return await new ResourceApplier(clusterModel).kubectlDeleteAll(resources, kubectlArgs); } else { - const response = await requestMain(clusterKubectlDeleteAllHandler, this.cluster.metadata.uid, resources); + const response = await requestMain(clusterKubectlDeleteAllHandler, this.cluster.metadata.uid, resources, kubectlArgs); if (response.stderr) { throw new Error(response.stderr); @@ -74,6 +84,14 @@ export class ResourceStack { } } + protected appendKubectlArgs(kubectlArgs: string[]) { + if (!kubectlArgs.includes("-l") && !kubectlArgs.includes("--label")) { + return kubectlArgs.concat(["-l", `app.kubernetes.io/name=${this.name}`]); + } + + return kubectlArgs; + } + protected renderTemplates(folderPath: string, templateContext: any): string[] { const resources: string[] = []; @@ -81,14 +99,28 @@ export class ResourceStack { fs.readdirSync(folderPath).forEach(filename => { const file = path.join(folderPath, filename); const raw = fs.readFileSync(file); + let resourceData: string; if (filename.endsWith(".hb")) { const template = hb.compile(raw.toString()); - resources.push(template(templateContext)); + resourceData = template(templateContext); } else { - resources.push(raw.toString()); + resourceData = raw.toString(); } + + if (!resourceData.trim()) return; + + const resource = yaml.safeLoad(resourceData.toString()); + + 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; diff --git a/src/main/resource-applier.ts b/src/main/resource-applier.ts index 963b906689..4bc4c2c8d3 100644 --- a/src/main/resource-applier.ts +++ b/src/main/resource-applier.ts @@ -52,18 +52,19 @@ export class ResourceApplier { }); } - public async kubectlApplyAll(resources: string[]): Promise { - return this.kubectlCmdAll("apply", resources); + public async kubectlApplyAll(resources: string[], extraArgs = ["-o", "json"]): Promise { + return this.kubectlCmdAll("apply", resources, extraArgs); } - public async kubectlDeleteAll(resources: string[]): Promise { - return this.kubectlCmdAll("delete", resources); + public async kubectlDeleteAll(resources: string[], extraArgs?: string[]): Promise { + return this.kubectlCmdAll("delete", resources, extraArgs); } - protected async kubectlCmdAll(subCmd: string, resources: string[]): Promise { + protected async kubectlCmdAll(subCmd: string, resources: string[], args?: string[]): Promise { const { kubeCtl } = this.cluster; const kubectlPath = await kubeCtl.getPath(); const proxyKubeconfigPath = await this.cluster.getProxyKubeconfigPath(); + let kubectlArgs = args || []; return new Promise((resolve, reject) => { const tmpDir = tempy.directory(); @@ -72,10 +73,13 @@ export class ResourceApplier { resources.forEach((resource, index) => { fs.writeFileSync(path.join(tmpDir, `${index}.yaml`), resource); }); - const cmd = `"${kubectlPath}" ${subCmd} --kubeconfig "${proxyKubeconfigPath}" -o json -f "${tmpDir}"`; + kubectlArgs = kubectlArgs.concat(["-f", `"${tmpDir}"`]); + const cmd = `"${kubectlPath}" ${subCmd} --kubeconfig "${proxyKubeconfigPath}" ${kubectlArgs.join(" ")}`; + logger.info(`[RESOURCE-APPLIER] running cmd ${cmd}`); exec(cmd, (error, stdout) => { if (error) { + logger.error(`[RESOURCE-APPLIER] cmd errored: ${error}`); const splittedError = error.toString().split(`.yaml": `); if (splittedError[1]) {