mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
remove depricated package request from our code
Signed-off-by: Sebastian Malton <smalton@mirantis.com>
This commit is contained in:
1 parent
33c405bdcf
commit
47fbf629ea
19 files changed
+397
-269
No files matched your search
@@ -0,0 +1,31 @@
|
||||
import { Options } from "got/dist/source";
|
||||
import { HttpsProxyAgent } from "hpagent";
|
||||
import { userStore } from "./user-store";
|
||||
|
||||
declare type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;
|
||||
declare type Merge<FirstType, SecondType> = Except<FirstType, Extract<keyof FirstType, keyof SecondType>> & SecondType;
|
||||
export type GotStreamFunctionOptions = Merge<Options, {
|
||||
isStream?: true;
|
||||
}>;
|
||||
|
||||
export function defaultGotOptions(): Options {
|
||||
const { httpsProxy, allowUntrustedCAs } = userStore.preferences;
|
||||
const rejectUnauthorized = !allowUntrustedCAs;
|
||||
|
||||
if (!httpsProxy) {
|
||||
return { rejectUnauthorized };
|
||||
}
|
||||
|
||||
const https = new HttpsProxyAgent({
|
||||
keepAlive: true,
|
||||
keepAliveMsecs: 1000,
|
||||
maxSockets: 256,
|
||||
maxFreeSockets: 256,
|
||||
proxy: httpsProxy,
|
||||
});
|
||||
|
||||
return {
|
||||
agent: { https },
|
||||
rejectUnauthorized,
|
||||
};
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import request from "request";
|
||||
import requestPromise from "request-promise-native";
|
||||
import { userStore } from "./user-store";
|
||||
|
||||
// todo: get rid of "request" (deprecated)
|
||||
// https://github.com/lensapp/lens/issues/459
|
||||
|
||||
function getDefaultRequestOpts(): Partial<request.Options> {
|
||||
const { httpsProxy, allowUntrustedCAs } = userStore.preferences;
|
||||
|
||||
return {
|
||||
proxy: httpsProxy || undefined,
|
||||
rejectUnauthorized: !allowUntrustedCAs,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
export function customRequest(opts: request.Options) {
|
||||
return request.defaults(getDefaultRequestOpts())(opts);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
export function customRequestPromise(opts: requestPromise.Options) {
|
||||
return requestPromise.defaults(getDefaultRequestOpts())(opts);
|
||||
}
|
||||
@@ -26,7 +26,7 @@ export class BaseClusterDetector {
|
||||
timeout: 30000,
|
||||
...options,
|
||||
headers: {
|
||||
Host: `${this.cluster.id}.${new URL(this.cluster.kubeProxyUrl).host}`, // required in ClusterManager.getClusterForRequest()
|
||||
Host: `${this.cluster.id}.${this.cluster.kubeProxyUrl.host}`, // required in ClusterManager.getClusterForRequest()
|
||||
...(options.headers || {}),
|
||||
},
|
||||
});
|
||||
|
||||
+22
-22
@@ -1,6 +1,5 @@
|
||||
import { ipcMain } from "electron";
|
||||
import type { ClusterId, ClusterMetadata, ClusterModel, ClusterPreferences, ClusterPrometheusPreferences } from "../common/cluster-store";
|
||||
import type { IMetricsReqParams } from "../renderer/api/endpoints/metrics.api";
|
||||
import type { WorkspaceId } from "../common/workspace-store";
|
||||
import { action, comparer, computed, observable, reaction, toJS, when } from "mobx";
|
||||
import { apiKubePrefix } from "../common/vars";
|
||||
@@ -10,12 +9,13 @@ import { AuthorizationV1Api, CoreV1Api, HttpError, KubeConfig, V1ResourceAttribu
|
||||
import { Kubectl } from "./kubectl";
|
||||
import { KubeconfigManager } from "./kubeconfig-manager";
|
||||
import { loadConfig, validateKubeConfig } from "../common/kube-helpers";
|
||||
import request, { RequestPromiseOptions } from "request-promise-native";
|
||||
import { apiResources, KubeApiResource } from "../common/rbac";
|
||||
import logger from "./logger";
|
||||
import { VersionDetector } from "./cluster-detectors/version-detector";
|
||||
import { detectorRegistry } from "./cluster-detectors/detector-registry";
|
||||
import plimit from "p-limit";
|
||||
import got, { OptionsOfJSONResponseBody } from "got";
|
||||
import { URL } from "url";
|
||||
|
||||
export enum ClusterStatus {
|
||||
AccessGranted = 2,
|
||||
@@ -86,7 +86,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
whenReady = when(() => this.ready);
|
||||
|
||||
/**
|
||||
* Is cluster object initializinng on-going
|
||||
* Is cluster object initializing on-going
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@@ -128,7 +128,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
* @observable
|
||||
* @internal
|
||||
*/
|
||||
@observable kubeProxyUrl: string; // lens-proxy to kube-api url
|
||||
@observable kubeProxyUrl: URL; // lens-proxy to kube-api url
|
||||
/**
|
||||
* Is cluster instance enabled (disabled clusters are currently hidden)
|
||||
*
|
||||
@@ -298,7 +298,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
this.initializing = true;
|
||||
this.contextHandler = new ContextHandler(this);
|
||||
this.kubeconfigManager = await KubeconfigManager.create(this, this.contextHandler, port);
|
||||
this.kubeProxyUrl = `http://localhost:${port}${apiKubePrefix}`;
|
||||
this.kubeProxyUrl = new URL(`http://localhost:${port}${apiKubePrefix}`);
|
||||
this.initialized = true;
|
||||
logger.info(`[CLUSTER]: "${this.contextName}" init success`, {
|
||||
id: this.id,
|
||||
@@ -495,31 +495,31 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
return this.kubeconfigManager.getPath();
|
||||
}
|
||||
|
||||
protected async k8sRequest<T = any>(path: string, options: RequestPromiseOptions = {}): Promise<T> {
|
||||
options.headers ??= {};
|
||||
options.json ??= true;
|
||||
options.timeout ??= 30000;
|
||||
options.headers.Host = `${this.id}.${new URL(this.kubeProxyUrl).host}`; // required in ClusterManager.getClusterForRequest()
|
||||
private getUrlTo(path: string): URL {
|
||||
const url = new URL(this.kubeProxyUrl.toString());
|
||||
|
||||
return request(this.kubeProxyUrl + path, options);
|
||||
url.pathname += path;
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param prometheusPath path to prometheus service
|
||||
* @param queryParams query parameters
|
||||
* @internal
|
||||
*/
|
||||
getMetrics(prometheusPath: string, queryParams: IMetricsReqParams & { query: string }) {
|
||||
protected k8sRequest<T = any>(url: URL, options: OptionsOfJSONResponseBody = {}): Promise<T> {
|
||||
options.timeout ??= 5000;
|
||||
options.headers ??= {};
|
||||
options.headers["content-type"] ??= "application/json";
|
||||
options.headers.host ??= `${this.id}.${this.kubeProxyUrl.host}`; // required in ClusterManager.getClusterForRequest()
|
||||
|
||||
return got<T>(url, options).json();
|
||||
}
|
||||
|
||||
getMetrics(prometheusPath: string, searchParams: Record<string, any>) {
|
||||
const prometheusPrefix = this.preferences.prometheus?.prefix || "";
|
||||
const metricsPath = `/api/v1/namespaces/${prometheusPath}/proxy${prometheusPrefix}/api/v1/query_range`;
|
||||
|
||||
return this.k8sRequest(metricsPath, {
|
||||
return this.k8sRequest(this.getUrlTo(metricsPath), {
|
||||
timeout: 0,
|
||||
resolveWithFullResponse: false,
|
||||
json: true,
|
||||
method: "POST",
|
||||
form: queryParams,
|
||||
form: searchParams,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
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";
|
||||
@@ -58,14 +58,14 @@ export class ContextHandler {
|
||||
|
||||
async getPrometheusService(): Promise<PrometheusService> {
|
||||
const providers = this.prometheusProvider ? prometheusProviders.filter(provider => provider.id == this.prometheusProvider) : prometheusProviders;
|
||||
const prometheusPromises: Promise<PrometheusService>[] = providers.map(async (provider: PrometheusProvider): Promise<PrometheusService> => {
|
||||
const apiClient = (await this.cluster.getProxyKubeconfig()).makeApiClient(CoreV1Api);
|
||||
|
||||
return await provider.getPrometheusService(apiClient);
|
||||
});
|
||||
const prometheusPromises = providers.map(provider => (
|
||||
this.cluster.getProxyKubeconfig()
|
||||
.then(kubeConfig => kubeConfig.makeApiClient(CoreV1Api))
|
||||
.then(apiClient => provider.getPrometheusService(apiClient))
|
||||
));
|
||||
const resolvedPrometheusServices = await Promise.all(prometheusPromises);
|
||||
|
||||
return resolvedPrometheusServices.filter(n => n)[0];
|
||||
return resolvedPrometheusServices.find(n => n);
|
||||
}
|
||||
|
||||
async getPrometheusPath(): Promise<string> {
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import yaml from "js-yaml";
|
||||
import { readFile } from "fs-extra";
|
||||
import { promiseExec } from "../promise-exec";
|
||||
import { promiseExec, stdOptimizedPromiseExec } from "../promise-exec";
|
||||
import { helmCli } from "./helm-cli";
|
||||
import { Singleton } from "../../common/utils/singleton";
|
||||
import { customRequestPromise } from "../../common/request";
|
||||
import { defaultGotOptions } from "../../common/got-opts";
|
||||
import orderBy from "lodash/orderBy";
|
||||
import logger from "../logger";
|
||||
import got, { OptionsOfJSONResponseBody } from "got";
|
||||
import { filter } from "lodash";
|
||||
|
||||
export type HelmEnv = Record<string, string> & {
|
||||
HELM_REPOSITORY_CACHE?: string;
|
||||
@@ -36,14 +38,13 @@ export class HelmRepoManager extends Singleton {
|
||||
protected initialized: boolean;
|
||||
|
||||
async loadAvailableRepos(): Promise<HelmRepo[]> {
|
||||
const res = await customRequestPromise({
|
||||
uri: "https://github.com/lensapp/artifact-hub-repositories/releases/download/latest/repositories.json",
|
||||
json: true,
|
||||
resolveWithFullResponse: true,
|
||||
timeout: 10000,
|
||||
});
|
||||
const options = {
|
||||
...defaultGotOptions() as OptionsOfJSONResponseBody,
|
||||
timeout: 10000
|
||||
};
|
||||
const r = await got<HelmRepo[]>("https://github.com/lensapp/artifact-hub-repositories/releases/download/latest/repositories.json", options);
|
||||
|
||||
return orderBy<HelmRepo>(res.body, repo => repo.name);
|
||||
return orderBy(r.body, repo => repo.name);
|
||||
}
|
||||
|
||||
async init() {
|
||||
@@ -60,7 +61,7 @@ export class HelmRepoManager extends Singleton {
|
||||
protected async parseHelmEnv() {
|
||||
const helm = await helmCli.binaryPath();
|
||||
const { stdout } = await promiseExec(`"${helm}" env`).catch((error) => {
|
||||
throw(error.stderr);
|
||||
throw (error.stderr);
|
||||
});
|
||||
const lines = stdout.split(/\r?\n/); // split by new line feed
|
||||
const env: HelmEnv = {};
|
||||
@@ -114,50 +115,41 @@ export class HelmRepoManager extends Singleton {
|
||||
|
||||
public async update() {
|
||||
const helm = await helmCli.binaryPath();
|
||||
const { stdout } = await promiseExec(`"${helm}" repo update`).catch((error) => {
|
||||
return { stdout: error.stdout };
|
||||
});
|
||||
const command = `"${helm}" repo update`;
|
||||
|
||||
return stdout;
|
||||
return stdOptimizedPromiseExec(command);
|
||||
}
|
||||
|
||||
public async addRepo({ name, url }: HelmRepo) {
|
||||
logger.info(`[HELM]: adding repo "${name}" from ${url}`);
|
||||
const helm = await helmCli.binaryPath();
|
||||
const { stdout } = await promiseExec(`"${helm}" repo add ${name} ${url}`).catch((error) => {
|
||||
throw(error.stderr);
|
||||
});
|
||||
const command = `"${helm}" repo add ${name} ${url}`;
|
||||
|
||||
return stdout;
|
||||
return stdOptimizedPromiseExec(command);
|
||||
}
|
||||
|
||||
public async addСustomRepo(repoAttributes : HelmRepo) {
|
||||
logger.info(`[HELM]: adding repo "${repoAttributes.name}" from ${repoAttributes.url}`);
|
||||
const helm = await helmCli.binaryPath();
|
||||
const args = filter([
|
||||
repoAttributes.insecureSkipTlsVerify && "--insecure-skip-tls-verify",
|
||||
repoAttributes.username && `--username "${repoAttributes.username}"`,
|
||||
repoAttributes.username && `--username "${repoAttributes.username}"`,
|
||||
repoAttributes.caFile && `--ca-file "${repoAttributes.caFile}"`,
|
||||
repoAttributes.keyFile && `--key-file "${repoAttributes.keyFile}"`,
|
||||
repoAttributes.certFile && `--cert-file "${repoAttributes.certFile}"`,
|
||||
]);
|
||||
const command = `"${helm}" repo add ${repoAttributes.name} ${repoAttributes.url} ${args.join(" ")}`;
|
||||
|
||||
const insecureSkipTlsVerify = repoAttributes.insecureSkipTlsVerify ? " --insecure-skip-tls-verify" : "";
|
||||
const username = repoAttributes.username ? ` --username "${repoAttributes.username}"` : "";
|
||||
const password = repoAttributes.password ? ` --password "${repoAttributes.password}"` : "";
|
||||
const caFile = repoAttributes.caFile ? ` --ca-file "${repoAttributes.caFile}"` : "";
|
||||
const keyFile = repoAttributes.keyFile ? ` --key-file "${repoAttributes.keyFile}"` : "";
|
||||
const certFile = repoAttributes.certFile ? ` --cert-file "${repoAttributes.certFile}"` : "";
|
||||
|
||||
const addRepoCommand = `"${helm}" repo add ${repoAttributes.name} ${repoAttributes.url}${insecureSkipTlsVerify}${username}${password}${caFile}${keyFile}${certFile}`;
|
||||
const { stdout } = await promiseExec(addRepoCommand).catch((error) => {
|
||||
throw(error.stderr);
|
||||
});
|
||||
|
||||
return stdout;
|
||||
return stdOptimizedPromiseExec(command);
|
||||
}
|
||||
|
||||
public async removeRepo({ name, url }: HelmRepo): Promise<string> {
|
||||
logger.info(`[HELM]: removing repo "${name}" from ${url}`);
|
||||
const helm = await helmCli.binaryPath();
|
||||
const { stdout } = await promiseExec(`"${helm}" repo remove ${name}`).catch((error) => {
|
||||
throw(error.stderr);
|
||||
});
|
||||
const command = `"${helm}" repo remove ${name}`;
|
||||
|
||||
return stdout;
|
||||
return stdOptimizedPromiseExec(command);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+27
-32
@@ -1,15 +1,21 @@
|
||||
import { app, remote } from "electron";
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import { promiseExec } from "./promise-exec";
|
||||
import logger from "./logger";
|
||||
import { ensureDir, pathExists } from "fs-extra";
|
||||
import got from "got";
|
||||
import path from "path";
|
||||
import * as lockFile from "proper-lockfile";
|
||||
import { helmCli } from "./helm/helm-cli";
|
||||
import stream from "stream";
|
||||
import { promisify } from "util";
|
||||
|
||||
import { defaultGotOptions, GotStreamFunctionOptions } from "../common/got-opts";
|
||||
import { userStore } from "../common/user-store";
|
||||
import { customRequest } from "../common/request";
|
||||
import { getBundledKubectlVersion } from "../common/utils/app-version";
|
||||
import { isDevelopment, isWindows, isTestEnv } from "../common/vars";
|
||||
import { isDevelopment, isTestEnv, isWindows } from "../common/vars";
|
||||
import { helmCli } from "./helm/helm-cli";
|
||||
import logger from "./logger";
|
||||
import { promiseExec } from "./promise-exec";
|
||||
|
||||
const pipeline = promisify(stream.pipeline);
|
||||
|
||||
const bundledVersion = getBundledKubectlVersion();
|
||||
const kubectlMap: Map<string, string> = new Map([
|
||||
@@ -273,33 +279,22 @@ export class Kubectl {
|
||||
|
||||
logger.info(`Downloading kubectl ${this.kubectlVersion} from ${this.url} to ${this.path}`);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const stream = customRequest({
|
||||
url: this.url,
|
||||
gzip: true,
|
||||
});
|
||||
const file = fs.createWriteStream(this.path);
|
||||
logger.info(`Downloading kubectl ${this.kubectlVersion} from ${this.url} to ${this.path}`);
|
||||
const options: GotStreamFunctionOptions = {
|
||||
...defaultGotOptions(),
|
||||
decompress: true,
|
||||
isStream: true,
|
||||
};
|
||||
|
||||
stream.on("complete", () => {
|
||||
logger.debug("kubectl binary download finished");
|
||||
file.end();
|
||||
});
|
||||
stream.on("error", (error) => {
|
||||
logger.error(error);
|
||||
fs.unlink(this.path, () => {
|
||||
// do nothing
|
||||
});
|
||||
reject(error);
|
||||
});
|
||||
file.on("close", () => {
|
||||
logger.debug("kubectl binary download closed");
|
||||
fs.chmod(this.path, 0o755, (err) => {
|
||||
if (err) reject(err);
|
||||
});
|
||||
resolve();
|
||||
});
|
||||
stream.pipe(file);
|
||||
});
|
||||
try {
|
||||
// TODO: improve the UI for this to use some sort of loading bar TUI
|
||||
await pipeline(
|
||||
got.stream(this.url, options),
|
||||
fs.createWriteStream(this.path)
|
||||
);
|
||||
} catch (err) {
|
||||
logger.error("Failed to download kubectl:", err);
|
||||
}
|
||||
}
|
||||
|
||||
protected async writeInitScripts() {
|
||||
|
||||
+51
-63
@@ -1,17 +1,22 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import request from "request";
|
||||
import { ensureDir, pathExists } from "fs-extra";
|
||||
import fse from "fs-extra";
|
||||
import * as tar from "tar";
|
||||
import { isWindows } from "../common/vars";
|
||||
import winston from "winston";
|
||||
import { GotStreamFunctionOptions } from "../common/got-opts";
|
||||
import got from "got";
|
||||
import stream from "stream";
|
||||
import { promisify } from "util";
|
||||
|
||||
const pipeline = promisify(stream.pipeline);
|
||||
|
||||
export type LensBinaryOpts = {
|
||||
version: string;
|
||||
baseDir: string;
|
||||
originalBinaryName: string;
|
||||
newBinaryName?: string;
|
||||
requestOpts?: request.Options;
|
||||
requestOpts?: GotStreamFunctionOptions;
|
||||
};
|
||||
|
||||
export class LensBinary {
|
||||
@@ -26,7 +31,7 @@ export class LensBinary {
|
||||
protected platformName: string;
|
||||
protected arch: string;
|
||||
protected originalBinaryName: string;
|
||||
protected requestOpts: request.Options;
|
||||
protected requestOpts: GotStreamFunctionOptions;
|
||||
protected logger: Console | winston.Logger;
|
||||
|
||||
constructor(opts: LensBinaryOpts) {
|
||||
@@ -63,7 +68,7 @@ export class LensBinary {
|
||||
}
|
||||
}
|
||||
|
||||
public setLogger(logger: Console | winston.Logger) {
|
||||
public setLogger(logger: Console | winston.Logger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
@@ -110,88 +115,71 @@ export class LensBinary {
|
||||
}
|
||||
|
||||
protected async checkBinary() {
|
||||
const exists = await pathExists(this.getBinaryPath());
|
||||
|
||||
return exists;
|
||||
return fse.pathExists(this.getBinaryPath());
|
||||
}
|
||||
|
||||
public async ensureBinary() {
|
||||
const isValid = await this.checkBinary();
|
||||
try {
|
||||
if (await this.checkBinary()) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.downloadBinary();
|
||||
|
||||
if (this.tarPath) {
|
||||
await this.untarBinary();
|
||||
}
|
||||
|
||||
if (this.originalBinaryName !== this.binaryName) {
|
||||
await this.renameBinary();
|
||||
}
|
||||
|
||||
if (!isValid) {
|
||||
await this.downloadBinary().catch((error) => {
|
||||
this.logger.error(error);
|
||||
});
|
||||
if (this.tarPath) await this.untarBinary();
|
||||
if (this.originalBinaryName != this.binaryName) await this.renameBinary();
|
||||
this.logger.info(`${this.originalBinaryName} has been downloaded to ${this.getBinaryPath()}`);
|
||||
} catch (err) {
|
||||
this.logger.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
protected async untarBinary() {
|
||||
return new Promise<void>(resolve => {
|
||||
this.logger.debug(`Extracting ${this.originalBinaryName} binary`);
|
||||
tar.x({
|
||||
this.logger.debug(`Extracting ${this.originalBinaryName} binary`);
|
||||
|
||||
try {
|
||||
await tar.x({
|
||||
file: this.tarPath,
|
||||
cwd: this.dirname
|
||||
}).then((() => {
|
||||
resolve();
|
||||
}));
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
this.logger.error(`failed to extract ${this.originalBinaryName}: `, err);
|
||||
}
|
||||
}
|
||||
|
||||
protected async renameBinary() {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
this.logger.debug(`Renaming ${this.originalBinaryName} binary to ${this.binaryName}`);
|
||||
fs.rename(this.getOriginalBinaryPath(), this.getBinaryPath(), (err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
this.logger.debug(`Renaming ${this.originalBinaryName} binary to ${this.binaryName}`);
|
||||
|
||||
return fse.promises.rename(this.getOriginalBinaryPath(), this.getBinaryPath());
|
||||
}
|
||||
|
||||
protected async downloadBinary() {
|
||||
const binaryPath = this.tarPath || this.getBinaryPath();
|
||||
|
||||
await ensureDir(this.getBinaryDir(), 0o755);
|
||||
await fse.ensureDir(this.getBinaryDir(), 0o755);
|
||||
|
||||
const file = fs.createWriteStream(binaryPath);
|
||||
const url = this.getUrl();
|
||||
|
||||
this.logger.info(`Downloading ${this.originalBinaryName} ${this.binaryVersion} from ${url} to ${binaryPath}`);
|
||||
const requestOpts: request.UriOptions & request.CoreOptions = {
|
||||
uri: url,
|
||||
gzip: true,
|
||||
const requestOpts: GotStreamFunctionOptions = {
|
||||
decompress: true,
|
||||
isStream: true,
|
||||
...this.requestOpts
|
||||
};
|
||||
const stream = request(requestOpts);
|
||||
|
||||
stream.on("complete", () => {
|
||||
this.logger.info(`Download of ${this.originalBinaryName} finished`);
|
||||
file.end();
|
||||
});
|
||||
this.logger.info(`Downloading ${this.originalBinaryName} ${this.binaryVersion} from ${url} to ${binaryPath}`);
|
||||
|
||||
stream.on("error", (error) => {
|
||||
this.logger.error(error);
|
||||
fs.unlink(binaryPath, () => {
|
||||
// do nothing
|
||||
});
|
||||
throw(error);
|
||||
});
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
file.on("close", () => {
|
||||
this.logger.debug(`${this.originalBinaryName} binary download closed`);
|
||||
if (!this.tarPath) fs.chmod(binaryPath, 0o755, (err) => {
|
||||
if (err) reject(err);
|
||||
});
|
||||
resolve();
|
||||
});
|
||||
stream.pipe(file);
|
||||
});
|
||||
try {
|
||||
await pipeline(
|
||||
got.stream(url, requestOpts),
|
||||
fs.createWriteStream(binaryPath),
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.error("Failed to download kubectl:", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { CoreV1Api } from "@kubernetes/client-node";
|
||||
|
||||
export type PrometheusClusterQuery = {
|
||||
export interface PrometheusClusterQuery {
|
||||
memoryUsage: string;
|
||||
memoryRequests: string;
|
||||
memoryLimits: string;
|
||||
@@ -11,18 +11,18 @@ export type PrometheusClusterQuery = {
|
||||
cpuCapacity: string;
|
||||
podUsage: string;
|
||||
podCapacity: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type PrometheusNodeQuery = {
|
||||
export interface PrometheusNodeQuery {
|
||||
memoryUsage: string;
|
||||
memoryCapacity: string;
|
||||
cpuUsage: string;
|
||||
cpuCapacity: string;
|
||||
fsSize: string;
|
||||
fsUsage: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type PrometheusPodQuery = {
|
||||
export interface PrometheusPodQuery {
|
||||
memoryUsage: string;
|
||||
memoryRequests: string;
|
||||
memoryLimits: string;
|
||||
@@ -32,25 +32,26 @@ export type PrometheusPodQuery = {
|
||||
fsUsage: string;
|
||||
networkReceive: string;
|
||||
networkTransmit: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type PrometheusPvcQuery = {
|
||||
export interface PrometheusPvcQuery {
|
||||
diskUsage: string;
|
||||
diskCapacity: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type PrometheusIngressQuery = {
|
||||
export interface PrometheusIngressQuery {
|
||||
bytesSentSuccess: string;
|
||||
bytesSentFailure: string;
|
||||
requestDurationSeconds: string;
|
||||
responseDurationSeconds: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type PrometheusQueryOpts = {
|
||||
[key: string]: string | any;
|
||||
};
|
||||
|
||||
export type PrometheusQuery = PrometheusNodeQuery | PrometheusClusterQuery | PrometheusPodQuery | PrometheusPvcQuery | PrometheusIngressQuery;
|
||||
export type PrometheusQueryKey = keyof PrometheusNodeQuery | keyof PrometheusClusterQuery | keyof PrometheusPodQuery | keyof PrometheusPvcQuery | keyof PrometheusIngressQuery;
|
||||
|
||||
export type PrometheusService = {
|
||||
id: string;
|
||||
|
||||
@@ -2,3 +2,13 @@ import * as util from "util";
|
||||
import { exec } from "child_process";
|
||||
|
||||
export const promiseExec = util.promisify(exec);
|
||||
|
||||
export async function stdOptimizedPromiseExec(url: string): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await promiseExec(url);
|
||||
|
||||
return stdout;
|
||||
} catch ({ stderr }) {
|
||||
throw stderr;
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ class HelmApiRoute extends LensApi {
|
||||
const { cluster, params, payload, response } = request;
|
||||
|
||||
try {
|
||||
const result = await helmService.updateRelease(cluster, params.release, params.namespace, payload );
|
||||
const result = await helmService.updateRelease(cluster, params.release, params.namespace, payload);
|
||||
|
||||
this.respondJson(response, result);
|
||||
} catch (error) {
|
||||
@@ -81,7 +81,7 @@ class HelmApiRoute extends LensApi {
|
||||
const result = await helmService.listReleases(cluster, params.namespace);
|
||||
|
||||
this.respondJson(response, result);
|
||||
} catch(error) {
|
||||
} catch (error) {
|
||||
logger.debug(error);
|
||||
this.respondText(response, error, 422);
|
||||
}
|
||||
|
||||
@@ -4,10 +4,15 @@ import { LensApi } from "../lens-api";
|
||||
import { Cluster, ClusterMetadataKey } from "../cluster";
|
||||
import { ClusterPrometheusMetadata } from "../../common/cluster-store";
|
||||
import logger from "../logger";
|
||||
import { PrometheusQueryKey } from "../prometheus/provider-registry";
|
||||
|
||||
export type IMetricsQuery = string | string[] | {
|
||||
export interface MetricsQuery {
|
||||
[metricName: string]: string;
|
||||
};
|
||||
}
|
||||
|
||||
function delay(ms: number) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
// This is used for backoff retry tracking.
|
||||
const MAX_ATTEMPTS = 5;
|
||||
@@ -29,7 +34,7 @@ async function loadMetrics(promQueries: string[], cluster: Cluster, prometheusPa
|
||||
throw new Error("Metrics not available");
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, (attempt + 1) * 1000)); // add delay before repeating request
|
||||
await delay((attempt + 1) * 1000); // add delay before repeating request
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,9 +45,14 @@ async function loadMetrics(promQueries: string[], cluster: Cluster, prometheusPa
|
||||
return Promise.all(queries.map(loadMetric));
|
||||
}
|
||||
|
||||
export interface MetricsResult {
|
||||
status?: string;
|
||||
data?: any;
|
||||
}
|
||||
|
||||
class MetricsRoute extends LensApi {
|
||||
async routeMetrics({ response, cluster, payload, query }: LensApiRequest) {
|
||||
const queryParams: IMetricsQuery = Object.fromEntries(query.entries());
|
||||
const queryParams: MetricsQuery = Object.fromEntries(query.entries());
|
||||
const prometheusMetadata: ClusterPrometheusMetadata = {};
|
||||
|
||||
try {
|
||||
@@ -72,7 +82,7 @@ class MetricsRoute extends LensApi {
|
||||
this.respondJson(response, data);
|
||||
} else {
|
||||
const queries = Object.entries(payload).map(([queryName, queryOpts]) => (
|
||||
(prometheusProvider.getQueries(queryOpts) as Record<string, string>)[queryName]
|
||||
(prometheusProvider.getQueries(queryOpts) as Record<PrometheusQueryKey, string>)[queryName as PrometheusQueryKey]
|
||||
));
|
||||
const result = await loadMetrics(queries, cluster, prometheusPath, queryParams);
|
||||
const data = Object.fromEntries(Object.keys(payload).map((metricName, i) => [metricName, result[i]]));
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import moment from "moment";
|
||||
import { apiBase } from "../index";
|
||||
import type { IMetricsQuery } from "../../../main/routes/metrics-route";
|
||||
import type { MetricsQuery } from "../../../main/routes/metrics-route";
|
||||
|
||||
export interface IMetrics {
|
||||
status: string;
|
||||
@@ -34,7 +34,7 @@ export interface IMetricsReqParams {
|
||||
}
|
||||
|
||||
export const metricsApi = {
|
||||
async getMetrics<T = IMetricsQuery>(query: T, reqParams: IMetricsReqParams = {}): Promise<T extends object ? { [K in keyof T]: IMetrics } : IMetrics> {
|
||||
async getMetrics<T = MetricsQuery>(query: T, reqParams: IMetricsReqParams = {}): Promise<T extends object ? { [K in keyof T]: IMetrics } : IMetrics> {
|
||||
const { range = 3600, step = 60, namespace } = reqParams;
|
||||
let { start, end } = reqParams;
|
||||
|
||||
|
||||
Reference in new issue
Block a user