Merge branch 'master' into fix/reload-dashboard-only

This commit is contained in:
Alex Andreev committed 2020-09-02 09:37:01 +03:00
commit 35d66c4cf7
14 files changed
+296 -96

No files matched your search

+1
View File
@@ -46,6 +46,7 @@ export class HelmRepoManager extends Singleton {
}
async init() {
helmCli.setLogger(logger)
await helmCli.ensureBinary();
if (!this.initialized) {
this.helmEnv = await this.parseHelmEnv()
+4 -3
View File
@@ -21,7 +21,7 @@ import logger from "./logger"
const workingDir = path.join(app.getPath("appData"), appName);
app.setName(appName);
if(!process.env.CICD) {
if (!process.env.CICD) {
app.setPath("userData", workingDir);
}
@@ -49,7 +49,8 @@ async function main() {
try {
proxyPort = await getFreePort()
} catch (error) {
await dialog.showErrorBox("Lens Error", "Could not find a free port for the cluster proxy")
logger.error(error)
dialog.showErrorBox("Lens Error", "Could not find a free port for the cluster proxy")
app.quit();
}
@@ -68,7 +69,7 @@ async function main() {
proxyServer = LensProxy.create(proxyPort, clusterManager);
} catch (error) {
logger.error(`Could not start proxy (127.0.0:${proxyPort}): ${error.message}`)
await dialog.showErrorBox("Lens Error", `Could not start proxy (127.0.0:${proxyPort}): ${error.message || "unknown error"}`)
dialog.showErrorBox("Lens Error", `Could not start proxy (127.0.0:${proxyPort}): ${error.message || "unknown error"}`)
app.quit();
}
+4
View File
@@ -44,6 +44,10 @@ export class KubeAuthProxy {
}
logger.debug(`spawning kubectl proxy with args: ${args}`)
this.proxyProcess = spawn(proxyBin, args, { env: this.env, })
this.proxyProcess.on("error", (error) => {
this.sendIpcLogMessage({ data: error.message, error: true })
this.exit()
})
this.proxyProcess.on("exit", (code) => {
this.sendIpcLogMessage({ data: `proxy exited with code: ${code}`, error: code > 0 })
+44 -16
View File
@@ -9,7 +9,7 @@ import { helmCli } from "./helm/helm-cli"
import { userStore } from "../common/user-store"
import { customRequest } from "../common/request";
import { getBundledKubectlVersion } from "../common/utils/app-version"
import { isDevelopment, isWindows } from "../common/vars";
import { isDevelopment, isWindows, isTestEnv } from "../common/vars";
const bundledVersion = getBundledKubectlVersion()
const kubectlMap: Map<string, string> = new Map([
@@ -22,9 +22,10 @@ const kubectlMap: Map<string, string> = new Map([
["1.13", "1.13.12"],
["1.14", "1.14.10"],
["1.15", "1.15.11"],
["1.16", "1.16.8"],
["1.16", "1.16.14"],
["1.17", bundledVersion],
["1.18", "1.18.0"]
["1.18", "1.18.8"],
["1.19", "1.19.0"]
])
const packageMirrors: Map<string, string> = new Map([
@@ -35,8 +36,9 @@ const packageMirrors: Map<string, string> = new Map([
let bundledPath: string
const initScriptVersionString = "# lens-initscript v3\n"
if (isDevelopment) {
bundledPath = path.join(process.cwd(), "binaries", "client", process.platform, process.arch, "kubectl")
if (isDevelopment || isTestEnv) {
const platformName = isWindows ? "windows" : process.platform
bundledPath = path.join(process.cwd(), "binaries", "client", platformName, process.arch, "kubectl")
} else {
bundledPath = path.join(process.resourcesPath, process.arch, "kubectl")
}
@@ -58,6 +60,7 @@ export class Kubectl {
public static readonly bundledKubectlPath = bundledPath
public static readonly bundledKubectlVersion: string = bundledVersion
public static invalidBundle = false
private static bundledInstance: Kubectl;
// Returns the single bundled Kubectl instance
@@ -98,9 +101,22 @@ export class Kubectl {
this.path = path.join(this.dirname, binaryName)
}
public async getPath(): Promise<string> {
public getBundledPath() {
return Kubectl.bundledKubectlPath
}
public async getPath(bundled = false): Promise<string> {
// return binary name if bundled path is not functional
if (!await this.checkBinary(this.getBundledPath(), false)) {
Kubectl.invalidBundle = true
return path.basename(bundledPath)
}
try {
await this.ensureKubectl()
if (!await this.ensureKubectl()) {
logger.error("Failed to ensure kubectl, fallback to the bundled version")
return Kubectl.bundledKubectlPath
}
return this.path
} catch (err) {
logger.error("Failed to ensure kubectl, fallback to the bundled version")
@@ -119,16 +135,15 @@ export class Kubectl {
}
}
public async checkBinary(checkVersion = true) {
const exists = await pathExists(this.path)
public async checkBinary(path: string, checkVersion = true) {
const exists = await pathExists(path)
if (exists) {
if (!checkVersion) {
return true
}
try {
const { stdout } = await promiseExec(`"${this.path}" version --client=true -o json`)
const { stdout } = await promiseExec(`"${path}" version --client=true -o json`)
const output = JSON.parse(stdout)
if (!checkVersion) {
return true
}
let version: string = output.clientVersion.gitVersion
if (version[0] === 'v') {
version = version.slice(1)
@@ -165,15 +180,28 @@ export class Kubectl {
}
public async ensureKubectl(): Promise<boolean> {
if (Kubectl.invalidBundle) {
logger.error(`Detected invalid bundle binary, returning ...`)
return false
}
await ensureDir(this.dirname, 0o755)
return lockFile.lock(this.dirname).then(async (release) => {
logger.debug(`Acquired a lock for ${this.kubectlVersion}`)
const bundled = await this.checkBundled()
const isValid = await this.checkBinary(!bundled)
if (!isValid) {
let isValid = await this.checkBinary(this.path, !bundled)
if (!isValid && !bundled) {
await this.downloadKubectl().catch((error) => {
logger.error(error)
logger.debug(`Releasing lock for ${this.kubectlVersion}`)
release()
return false
});
isValid = !await this.checkBinary(this.path, false)
}
if(!isValid) {
logger.debug(`Releasing lock for ${this.kubectlVersion}`)
release()
return false
}
await this.writeInitScripts().catch((error) => {
logger.error("Failed to write init scripts");
+28
View File
@@ -1,5 +1,7 @@
import packageInfo from "../../package.json"
import path from "path"
import { bundledKubectl, Kubectl } from "../../src/main/kubectl";
import { isWindows } from "../common/vars";
jest.mock("../common/user-store");
@@ -15,3 +17,29 @@ describe("kubectlVersion", () => {
expect(kubectl.kubectlVersion).toBe(bundledKubectl.kubectlVersion)
})
})
describe("getPath()", () => {
it("returns path to downloaded kubectl binary", async () => {
const { bundledKubectlVersion } = packageInfo.config;
const kubectl = new Kubectl(bundledKubectlVersion);
const kubectlPath = await kubectl.getPath()
let binaryName = "kubectl"
if (isWindows) {
binaryName += ".exe"
}
const expectedPath = path.join(Kubectl.kubectlDir, Kubectl.bundledKubectlVersion, binaryName)
expect(kubectlPath).toBe(expectedPath)
})
it("returns plain binary name if bundled kubectl is non-functional", async () => {
const { bundledKubectlVersion } = packageInfo.config;
const kubectl = new Kubectl(bundledKubectlVersion);
jest.spyOn(kubectl, "getBundledPath").mockReturnValue("/invalid/path/kubectl")
const kubectlPath = await kubectl.getPath()
let binaryName = "kubectl"
if (isWindows) {
binaryName += ".exe"
}
expect(kubectlPath).toBe(binaryName)
})
})
+16 -11
View File
@@ -1,10 +1,10 @@
import path from "path"
import fs from "fs"
import request from "request"
import logger from "./logger"
import { ensureDir, pathExists } from "fs-extra"
import * as tar from "tar"
import { isWindows } from "../common/vars";
import winston from "winston"
export type LensBinaryOpts = {
version: string;
@@ -27,6 +27,7 @@ export class LensBinary {
protected arch: string
protected originalBinaryName: string
protected requestOpts: request.Options
protected logger: Console | winston.Logger
constructor(opts: LensBinaryOpts) {
const baseDir = opts.baseDir
@@ -34,7 +35,7 @@ export class LensBinary {
this.binaryName = opts.newBinaryName || opts.originalBinaryName
this.binaryVersion = opts.version
this.requestOpts = opts.requestOpts
this.logger = console
let arch = null
if (process.arch == "x64") {
@@ -59,6 +60,10 @@ export class LensBinary {
}
}
public setLogger(logger: Console | winston.Logger) {
this.logger = logger
}
protected binaryDir() {
throw new Error("binaryDir not implemented")
}
@@ -93,7 +98,7 @@ export class LensBinary {
await this.ensureBinary()
return this.dirname
} catch (err) {
logger.error(err)
this.logger.error(err)
return ""
}
}
@@ -107,17 +112,17 @@ export class LensBinary {
const isValid = await this.checkBinary()
if (!isValid) {
await this.downloadBinary().catch((error) => {
logger.error(error)
this.logger.error(error)
});
if (this.tarPath) await this.untarBinary()
if (this.originalBinaryName != this.binaryName) await this.renameBinary()
logger.info(`${this.originalBinaryName} has been downloaded to ${this.getBinaryPath()}`)
this.logger.info(`${this.originalBinaryName} has been downloaded to ${this.getBinaryPath()}`)
}
}
protected async untarBinary() {
return new Promise<void>((resolve, reject) => {
logger.debug(`Extracting ${this.originalBinaryName} binary`)
this.logger.debug(`Extracting ${this.originalBinaryName} binary`)
tar.x({
file: this.tarPath,
cwd: this.dirname
@@ -129,7 +134,7 @@ export class LensBinary {
protected async renameBinary() {
return new Promise<void>((resolve, reject) => {
logger.debug(`Renaming ${this.originalBinaryName} binary to ${this.binaryName}`)
this.logger.debug(`Renaming ${this.originalBinaryName} binary to ${this.binaryName}`)
fs.rename(this.getOriginalBinaryPath(), this.getBinaryPath(), (err) => {
if (err) {
reject(err)
@@ -148,7 +153,7 @@ export class LensBinary {
const file = fs.createWriteStream(binaryPath)
const url = this.getUrl()
logger.info(`Downloading ${this.originalBinaryName} ${this.binaryVersion} from ${url} to ${binaryPath}`)
this.logger.info(`Downloading ${this.originalBinaryName} ${this.binaryVersion} from ${url} to ${binaryPath}`)
const requestOpts: request.UriOptions & request.CoreOptions = {
uri: url,
gzip: true,
@@ -158,12 +163,12 @@ export class LensBinary {
const stream = request(requestOpts)
stream.on("complete", () => {
logger.info(`Download of ${this.originalBinaryName} finished`)
this.logger.info(`Download of ${this.originalBinaryName} finished`)
file.end()
})
stream.on("error", (error) => {
logger.error(error)
this.logger.error(error)
fs.unlink(binaryPath, () => {
// do nothing
})
@@ -171,7 +176,7 @@ export class LensBinary {
})
return new Promise((resolve, reject) => {
file.on("close", () => {
logger.debug(`${this.originalBinaryName} binary download closed`)
this.logger.debug(`${this.originalBinaryName} binary download closed`)
if (!this.tarPath) fs.chmod(binaryPath, 0o755, (err) => {
if (err) reject(err);
})
+14 -4
View File
@@ -1,20 +1,30 @@
import { app, remote } from "electron";
import winston from "winston"
import { isDebugging } from "../common/vars";
const options = {
colorize: true,
const consoleOptions: winston.transports.ConsoleTransportOptions = {
handleExceptions: false,
json: false,
level: isDebugging ? "debug" : "info",
}
const fileOptions: winston.transports.FileTransportOptions = {
handleExceptions: false,
level: isDebugging ? "debug" : "info",
filename: "lens.log",
dirname: (app || remote.app).getPath("logs"),
maxsize: 16 * 1024,
maxFiles: 16,
tailable: true,
}
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple(),
),
transports: [
new winston.transports.Console(options),
new winston.transports.Console(consoleOptions),
new winston.transports.File(fileOptions),
],
});
+3 -1
View File
@@ -121,6 +121,8 @@ export function lookupApiLink(ref: IKubeObjectRef, parentObject: KubeObject): st
namespace = parentObject.getNs()
} = ref;
if (!kind) return "";
// search in registered apis by 'kind' & 'apiVersion'
const api = apiManager.getApi(api => api.kind === kind && api.apiVersionWithGroup == apiVersion)
if (api) {
@@ -129,7 +131,7 @@ export function lookupApiLink(ref: IKubeObjectRef, parentObject: KubeObject): st
// lookup api by generated resource link
const apiPrefixes = ["/apis", "/api"];
const resource = kind.toLowerCase() + kind.endsWith("s") ? "es" : "s";
const resource = kind.endsWith("s") ? `${kind.toLowerCase()}es` : `${kind.toLowerCase()}s`;
for (const apiPrefix of apiPrefixes) {
const apiLink = createKubeApiURL({ apiPrefix, apiVersion, name, namespace, resource });
if (apiManager.getApi(apiLink)) {
+1
View File
@@ -69,6 +69,7 @@ export function getSelectedDetails() {
}
export function getDetailsUrl(details: string) {
if (!details) return "";
return getQueryString({
details: details,
selected: getSelectedDetails(),