Enforce semicolons in eslint

Signed-off-by: Panu Horsmalahti <phorsmalahti@mirantis.com>
This commit is contained in:
Panu Horsmalahti committed 2020-11-19 16:35:04 +02:00
1 parent 0f3f5611ba
commit 1477bb8274
531 files changed
+3979 -3975

No files matched your search

+2 -2
View File
@@ -24,7 +24,7 @@ export class ApiManager {
}
protected resolveApi(api: string | KubeApi): KubeApi {
if (typeof api === "string") return this.getApi(api)
if (typeof api === "string") return this.getApi(api);
return api;
}
@@ -41,7 +41,7 @@ export class ApiManager {
registerStore(store: KubeObjectStore, apis: KubeApi[] = [store.api]) {
apis.forEach(api => {
this.stores.set(api, store);
})
});
}
getStore(api: string | KubeApi): KubeObjectStore {
+1 -1
View File
@@ -8,7 +8,7 @@ export class ClusterApi extends KubeApi<Cluster> {
async getMetrics(nodeNames: string[], params?: IMetricsReqParams): Promise<IClusterMetrics> {
const nodes = nodeNames.join("|");
const opts = { category: "cluster", nodes: nodes }
const opts = { category: "cluster", nodes: nodes };
return metricsApi.getMetrics({
memoryUsage: opts,
+6 -6
View File
@@ -70,25 +70,25 @@ export class CustomResourceDefinition extends KubeObject {
group: this.getGroup(),
name: this.getPluralName(),
}
})
});
}
getResourceApiBase() {
const { group } = this.spec;
return `/apis/${group}/${this.getVersion()}/${this.getPluralName()}`
return `/apis/${group}/${this.getVersion()}/${this.getPluralName()}`;
}
getPluralName() {
return this.getNames().plural
return this.getNames().plural;
}
getResourceKind() {
return this.spec.names.kind
return this.spec.names.kind;
}
getResourceTitle() {
const name = this.getPluralName();
return name[0].toUpperCase() + name.substr(1)
return name[0].toUpperCase() + name.substr(1);
}
getGroup() {
@@ -141,7 +141,7 @@ export class CustomResourceDefinition extends KubeObject {
...condition,
isReady: status === "True",
tooltip: `${message || reason} (${lastTransitionTime})`
}
};
});
}
}
+5 -5
View File
@@ -65,17 +65,17 @@ export class CronJob extends KubeObject {
}
getSuspendFlag() {
return this.spec.suspend.toString()
return this.spec.suspend.toString();
}
getLastScheduleTime() {
if (!this.status.lastScheduleTime) return "-"
const diff = moment().diff(this.status.lastScheduleTime)
return formatDuration(diff, true)
if (!this.status.lastScheduleTime) return "-";
const diff = moment().diff(this.status.lastScheduleTime);
return formatDuration(diff, true);
}
getSchedule() {
return this.spec.schedule
return this.spec.schedule;
}
isNeverRun() {
+3 -3
View File
@@ -64,9 +64,9 @@ export class DaemonSet extends WorkloadKubeObject {
}
getImages() {
const containers: IPodContainer[] = get(this, "spec.template.spec.containers", [])
const initContainers: IPodContainer[] = get(this, "spec.template.spec.initContainers", [])
return [...containers, ...initContainers].map(container => container.image)
const containers: IPodContainer[] = get(this, "spec.template.spec.containers", []);
const initContainers: IPodContainer[] = get(this, "spec.template.spec.initContainers", []);
return [...containers, ...initContainers].map(container => container.image);
}
}
+9 -9
View File
@@ -6,13 +6,13 @@ import { KubeApi } from "../kube-api";
export class DeploymentApi extends KubeApi<Deployment> {
protected getScaleApiUrl(params: { namespace: string; name: string }) {
return this.getUrl(params) + "/scale"
return this.getUrl(params) + "/scale";
}
getReplicas(params: { namespace: string; name: string }): Promise<number> {
return this.request
.get(this.getScaleApiUrl(params))
.then(({ status }: any) => status?.replicas)
.then(({ status }: any) => status?.replicas);
}
scale(params: { namespace: string; name: string }, replicas: number) {
@@ -23,7 +23,7 @@ export class DeploymentApi extends KubeApi<Deployment> {
replicas: replicas
}
}
})
});
}
restart(params: { namespace: string; name: string }) {
@@ -42,7 +42,7 @@ export class DeploymentApi extends KubeApi<Deployment> {
headers: {
'content-type': 'application/strategic-merge-patch+json'
}
})
});
}
}
@@ -170,16 +170,16 @@ export class Deployment extends WorkloadKubeObject {
}
getConditions(activeOnly = false) {
const { conditions } = this.status
if (!conditions) return []
const { conditions } = this.status;
if (!conditions) return [];
if (activeOnly) {
return conditions.filter(c => c.status === "True")
return conditions.filter(c => c.status === "True");
}
return conditions
return conditions;
}
getConditionsText(activeOnly = true) {
return this.getConditions(activeOnly).map(({ type }) => type).join(" ")
return this.getConditions(activeOnly).map(({ type }) => type).join(" ");
}
getReplicas() {
+13 -13
View File
@@ -42,22 +42,22 @@ export class EndpointAddress implements IEndpointAddress {
};
constructor(data: IEndpointAddress) {
Object.assign(this, data)
Object.assign(this, data);
}
getId() {
return this.ip
return this.ip;
}
getName() {
return this.hostname
return this.hostname;
}
getTargetRef(): ITargetRef {
if (this.targetRef) {
return Object.assign(this.targetRef, {apiVersion: "v1"})
return Object.assign(this.targetRef, {apiVersion: "v1"});
} else {
return null
return null;
}
}
}
@@ -68,7 +68,7 @@ export class EndpointSubset implements IEndpointSubset {
ports: IEndpointPort[];
constructor(data: IEndpointSubset) {
Object.assign(this, data)
Object.assign(this, data);
}
getAddresses(): EndpointAddress[] {
@@ -83,16 +83,16 @@ export class EndpointSubset implements IEndpointSubset {
toString(): string {
if(!this.addresses) {
return ""
return "";
}
return this.addresses.map(address => {
if (!this.ports) {
return address.ip
return address.ip;
}
return this.ports.map(port => {
return `${address.ip}:${port.port}`
}).join(", ")
}).join(", ")
return `${address.ip}:${port.port}`;
}).join(", ");
}).join(", ");
}
}
@@ -111,9 +111,9 @@ export class Endpoint extends KubeObject {
toString(): string {
if(this.subsets) {
return this.getEndpointSubsets().map(es => es.toString()).join(", ")
return this.getEndpointSubsets().map(es => es.toString()).join(", ");
} else {
return "<none>"
return "<none>";
}
}
+7 -7
View File
@@ -38,21 +38,21 @@ export class KubeEvent extends KubeObject {
}
getSource() {
const { component, host } = this.source
return `${component} ${host || ""}`
const { component, host } = this.source;
return `${component} ${host || ""}`;
}
getFirstSeenTime() {
const diff = moment().diff(this.firstTimestamp)
return formatDuration(diff, true)
const diff = moment().diff(this.firstTimestamp);
return formatDuration(diff, true);
}
getLastSeenTime() {
const diff = moment().diff(this.lastTimestamp)
return formatDuration(diff, true)
const diff = moment().diff(this.lastTimestamp);
return formatDuration(diff, true);
}
}
export const eventApi = new KubeApi({
objectConstructor: KubeEvent,
})
});
@@ -41,7 +41,7 @@ export const helmChartsApi = {
return {
readme,
versions,
}
};
});
},
@@ -82,7 +82,7 @@ export const helmReleasesApi = {
return {
...details,
resources
}
};
});
},
@@ -156,12 +156,12 @@ export class HelmRelease implements ItemObject {
}
getChart(withVersion = false) {
let chart = this.chart
let chart = this.chart;
if(!withVersion && this.getVersion() != "" ) {
const search = new RegExp(`-${this.getVersion()}`)
const search = new RegExp(`-${this.getVersion()}`);
chart = chart.replace(search, "");
}
return chart
return chart;
}
getRevision() {
@@ -173,12 +173,12 @@ export class HelmRelease implements ItemObject {
}
getVersion() {
const versions = this.chart.match(/(v?\d+)[^-].*$/)
const versions = this.chart.match(/(v?\d+)[^-].*$/);
if (versions) {
return versions[0]
return versions[0];
}
else {
return ""
return "";
}
}
+3 -3
View File
@@ -86,7 +86,7 @@ export class HorizontalPodAutoscaler extends KubeObject {
...condition,
isReady: status === "True",
tooltip: `${message || reason} (${lastTransitionTime})`
}
};
});
}
@@ -102,7 +102,7 @@ export class HorizontalPodAutoscaler extends KubeObject {
const { type, resource, pods, object, external } = metric;
switch (type) {
case HpaMetricType.Resource:
return resource.name
return resource.name;
case HpaMetricType.Pods:
return pods.metricName;
case HpaMetricType.Object:
@@ -128,7 +128,7 @@ export class HorizontalPodAutoscaler extends KubeObject {
}
if (target) {
targetValue = target.targetAverageUtilization || target.targetAverageValue || target.targetValue;
if (target.targetAverageUtilization) targetValue += "%"
if (target.targetAverageUtilization) targetValue += "%";
}
return `${currentValue} / ${targetValue}`;
}
+32 -32
View File
@@ -1,35 +1,35 @@
// Kubernetes apis
// Docs: https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/
export * from "./cluster.api"
export * from "./cluster-role.api"
export * from "./cluster-role-binding.api"
export * from "./configmap.api"
export * from "./crd.api"
export * from "./cron-job.api"
export * from "./daemon-set.api"
export * from "./deployment.api"
export * from "./endpoint.api"
export * from "./events.api"
export * from "./hpa.api"
export * from "./ingress.api"
export * from "./job.api"
export * from "./namespaces.api"
export * from "./network-policy.api"
export * from "./nodes.api"
export * from "./persistent-volume.api"
export * from "./persistent-volume-claims.api"
export * from "./pods.api"
export * from "./poddisruptionbudget.api"
export * from "./pod-metrics.api"
export * from "./podsecuritypolicy.api"
export * from "./replica-set.api"
export * from "./resource-quota.api"
export * from "./role.api"
export * from "./role-binding.api"
export * from "./secret.api"
export * from "./selfsubjectrulesreviews.api"
export * from "./service.api"
export * from "./service-accounts.api"
export * from "./stateful-set.api"
export * from "./storage-class.api"
export * from "./cluster.api";
export * from "./cluster-role.api";
export * from "./cluster-role-binding.api";
export * from "./configmap.api";
export * from "./crd.api";
export * from "./cron-job.api";
export * from "./daemon-set.api";
export * from "./deployment.api";
export * from "./endpoint.api";
export * from "./events.api";
export * from "./hpa.api";
export * from "./ingress.api";
export * from "./job.api";
export * from "./namespaces.api";
export * from "./network-policy.api";
export * from "./nodes.api";
export * from "./persistent-volume.api";
export * from "./persistent-volume-claims.api";
export * from "./pods.api";
export * from "./poddisruptionbudget.api";
export * from "./pod-metrics.api";
export * from "./podsecuritypolicy.api";
export * from "./replica-set.api";
export * from "./resource-quota.api";
export * from "./role.api";
export * from "./role-binding.api";
export * from "./secret.api";
export * from "./selfsubjectrulesreviews.api";
export * from "./service.api";
export * from "./service-accounts.api";
export * from "./stateful-set.api";
export * from "./storage-class.api";
+22 -22
View File
@@ -5,7 +5,7 @@ import { KubeApi } from "../kube-api";
export class IngressApi extends KubeApi<Ingress> {
getMetrics(ingress: string, namespace: string): Promise<IIngressMetrics> {
const opts = { category: "ingress", ingress }
const opts = { category: "ingress", ingress };
return metricsApi.getMetrics({
bytesSentSuccess: opts,
bytesSentFailure: opts,
@@ -63,51 +63,51 @@ export class Ingress extends KubeObject {
}
getRoutes() {
const { spec: { tls, rules } } = this
if (!rules) return []
const { spec: { tls, rules } } = this;
if (!rules) return [];
let protocol = "http"
const routes: string[] = []
let protocol = "http";
const routes: string[] = [];
if (tls && tls.length > 0) {
protocol += "s"
protocol += "s";
}
rules.map(rule => {
const host = rule.host ? rule.host : "*"
const host = rule.host ? rule.host : "*";
if (rule.http && rule.http.paths) {
rule.http.paths.forEach(path => {
routes.push(protocol + "://" + host + (path.path || "/") + " ⇢ " + path.backend.serviceName + ":" + path.backend.servicePort)
})
routes.push(protocol + "://" + host + (path.path || "/") + " ⇢ " + path.backend.serviceName + ":" + path.backend.servicePort);
});
}
})
});
return routes;
}
getHosts() {
const { spec: { rules } } = this
if (!rules) return []
return rules.filter(rule => rule.host).map(rule => rule.host)
const { spec: { rules } } = this;
if (!rules) return [];
return rules.filter(rule => rule.host).map(rule => rule.host);
}
getPorts() {
const ports: number[] = []
const { spec: { tls, rules, backend } } = this
const httpPort = 80
const tlsPort = 443
const ports: number[] = [];
const { spec: { tls, rules, backend } } = this;
const httpPort = 80;
const tlsPort = 443;
if (rules && rules.length > 0) {
if (rules.some(rule => rule.hasOwnProperty("http"))) {
ports.push(httpPort)
ports.push(httpPort);
}
}
else {
if (backend && backend.servicePort) {
ports.push(backend.servicePort)
ports.push(backend.servicePort);
}
}
if (tls && tls.length > 0) {
ports.push(tlsPort)
ports.push(tlsPort);
}
return ports.join(", ")
return ports.join(", ");
}
getLoadBalancers() {
@@ -115,7 +115,7 @@ export class Ingress extends KubeObject {
return (loadBalancer.ingress ?? []).map(address => (
address.hostname || address.ip
))
));
}
}
+4 -4
View File
@@ -91,15 +91,15 @@ export class Job extends WorkloadKubeObject {
}
getImages() {
const containers: IPodContainer[] = get(this, "spec.template.spec.containers", [])
return [...containers].map(container => container.image)
const containers: IPodContainer[] = get(this, "spec.template.spec.containers", []);
return [...containers].map(container => container.image);
}
delete() {
const params: JsonApiParams = {
query: { propagationPolicy: "Background" }
}
return super.delete(params)
};
return super.delete(params);
}
}
+3 -3
View File
@@ -66,7 +66,7 @@ export function normalizeMetrics(metrics: IMetrics, frames = 60): IMetrics {
} as IMetricsResult],
},
status: "",
}
};
}
const { result } = metrics.data;
@@ -78,7 +78,7 @@ export function normalizeMetrics(metrics: IMetrics, frames = 60): IMetrics {
if (!res.values || !res.values.length) return;
while (res.values.length < frames) {
const timestamp = moment.unix(res.values[0][0]).subtract(1, "minute").unix();
res.values.unshift([timestamp, "0"])
res.values.unshift([timestamp, "0"]);
}
});
}
@@ -103,7 +103,7 @@ export function getItemMetrics(metrics: { [key: string]: IMetrics }, itemName: s
const itemMetrics = { ...metrics };
for (const metric in metrics) {
if (!metrics[metric]?.data?.result) {
continue
continue;
}
const results = metrics[metric].data.result;
const result = results.find(res => Object.values(res.metric)[0] == itemName);
@@ -57,7 +57,7 @@ export class NetworkPolicy extends KubeObject {
if (!this.spec.podSelector || !this.spec.podSelector.matchLabels) return [];
return Object
.entries(this.spec.podSelector.matchLabels)
.map(data => data.join(":"))
.map(data => data.join(":"));
}
getTypes(): string[] {
+17 -17
View File
@@ -5,7 +5,7 @@ import { KubeApi } from "../kube-api";
export class NodesApi extends KubeApi<Node> {
getMetrics(): Promise<INodeMetrics> {
const opts = { category: "nodes"}
const opts = { category: "nodes"};
return metricsApi.getMetrics({
memoryUsage: opts,
@@ -86,12 +86,12 @@ export class Node extends KubeObject {
}
getNodeConditionText() {
const { conditions } = this.status
if (!conditions) return ""
const { conditions } = this.status;
if (!conditions) return "";
return conditions.reduce((types, current) => {
if (current.status !== "True") return ""
return types += ` ${current.type}`
}, "")
if (current.status !== "True") return "";
return types += ` ${current.type}`;
}, "");
}
getTaints() {
@@ -101,23 +101,23 @@ export class Node extends KubeObject {
getRoleLabels() {
const roleLabels = Object.keys(this.metadata.labels).filter(key =>
key.includes("node-role.kubernetes.io")
).map(key => key.match(/([^/]+$)/)[0]) // all after last slash
).map(key => key.match(/([^/]+$)/)[0]); // all after last slash
if (this.metadata.labels["kubernetes.io/role"] != undefined) {
roleLabels.push(this.metadata.labels["kubernetes.io/role"])
roleLabels.push(this.metadata.labels["kubernetes.io/role"]);
}
return roleLabels.join(", ")
return roleLabels.join(", ");
}
getCpuCapacity() {
if (!this.status.capacity || !this.status.capacity.cpu) return 0
return cpuUnitsToNumber(this.status.capacity.cpu)
if (!this.status.capacity || !this.status.capacity.cpu) return 0;
return cpuUnitsToNumber(this.status.capacity.cpu);
}
getMemoryCapacity() {
if (!this.status.capacity || !this.status.capacity.memory) return 0
return unitsToBytes(this.status.capacity.memory)
if (!this.status.capacity || !this.status.capacity.memory) return 0;
return unitsToBytes(this.status.capacity.memory);
}
getConditions() {
@@ -144,16 +144,16 @@ export class Node extends KubeObject {
}
getOperatingSystem(): string {
const label = this.getLabels().find(label => label.startsWith("kubernetes.io/os="))
const label = this.getLabels().find(label => label.startsWith("kubernetes.io/os="));
if (label) {
return label.split("=", 2)[1]
return label.split("=", 2)[1];
}
return "linux"
return "linux";
}
isUnschedulable() {
return this.spec.unschedulable
return this.spec.unschedulable;
}
}
@@ -51,13 +51,13 @@ export class PersistentVolumeClaim extends KubeObject {
}
getPods(allPods: Pod[]): Pod[] {
const pods = allPods.filter(pod => pod.getNs() === this.getNs())
const pods = allPods.filter(pod => pod.getNs() === this.getNs());
return pods.filter(pod => {
return pod.getVolumes().filter(volume =>
volume.persistentVolumeClaim &&
volume.persistentVolumeClaim.claimName === this.getName()
).length > 0
})
).length > 0;
});
}
getStorage(): string {
@@ -78,7 +78,7 @@ export class PersistentVolumeClaim extends KubeObject {
getStatus(): string {
if (this.status) return this.status.phase;
return "-"
return "-";
}
}
@@ -48,7 +48,7 @@ export class PersistentVolume extends KubeObject {
getCapacity(inBytes = false) {
const capacity = this.spec.capacity;
if (capacity) {
if (inBytes) return unitsToBytes(capacity.storage)
if (inBytes) return unitsToBytes(capacity.storage);
return capacity.storage;
}
return 0;
+19 -19
View File
@@ -11,7 +11,7 @@ export class PodsApi extends KubeApi<Pod> {
getMetrics(pods: Pod[], namespace: string, selector = "pod, namespace"): Promise<IPodMetrics> {
const podSelector = pods.map(pod => pod.getName()).join("|");
const opts = { category: "pods", pods: podSelector, namespace, selector }
const opts = { category: "pods", pods: podSelector, namespace, selector };
return metricsApi.getMetrics({
cpuUsage: opts,
@@ -246,11 +246,11 @@ export class Pod extends WorkloadKubeObject {
}
getRunningContainers() {
const statuses = this.getContainerStatuses()
const statuses = this.getContainerStatuses();
return this.getAllContainers().filter(container => {
return statuses.find(status => status.name === container.name && !!status.state["running"])
return statuses.find(status => status.name === container.name && !!status.state["running"]);
}
)
);
}
getContainerStatuses(includeInitContainers = true) {
@@ -323,7 +323,7 @@ export class Pod extends WorkloadKubeObject {
const { reason } = state.terminated;
message = reason ? reason : "Terminated";
}
})
});
}
if (message) return message;
return this.getStatusPhase();
@@ -348,32 +348,32 @@ export class Pod extends WorkloadKubeObject {
}
getNodeSelectors(): string[] {
const { nodeSelector } = this.spec
if (!nodeSelector) return []
return Object.entries(nodeSelector).map(values => values.join(": "))
const { nodeSelector } = this.spec;
if (!nodeSelector) return [];
return Object.entries(nodeSelector).map(values => values.join(": "));
}
getTolerations() {
return this.spec.tolerations || []
return this.spec.tolerations || [];
}
getAffinity(): IAffinity {
return this.spec.affinity
return this.spec.affinity;
}
hasIssues() {
const notReady = !!this.getConditions().find(condition => {
return condition.type == "Ready" && condition.status !== "True"
return condition.type == "Ready" && condition.status !== "True";
});
const crashLoop = !!this.getContainerStatuses().find(condition => {
const waiting = condition.state.waiting
return (waiting && waiting.reason == "CrashLoopBackOff")
})
const waiting = condition.state.waiting;
return (waiting && waiting.reason == "CrashLoopBackOff");
});
return (
notReady ||
crashLoop ||
this.getStatusPhase() !== "Running"
)
);
}
getLivenessProbe(container: IPodContainer) {
@@ -418,14 +418,14 @@ export class Pod extends WorkloadKubeObject {
}
getNodeName() {
return this.spec?.nodeName
return this.spec?.nodeName;
}
getSelectedNodeOs() {
if (!this.spec.nodeSelector) return
if (!this.spec.nodeSelector["kubernetes.io/os"] && !this.spec.nodeSelector["beta.kubernetes.io/os"]) return
if (!this.spec.nodeSelector) return;
if (!this.spec.nodeSelector["kubernetes.io/os"] && !this.spec.nodeSelector["beta.kubernetes.io/os"]) return;
return this.spec.nodeSelector["kubernetes.io/os"] || this.spec.nodeSelector["beta.kubernetes.io/os"]
return this.spec.nodeSelector["kubernetes.io/os"] || this.spec.nodeSelector["beta.kubernetes.io/os"];
}
}
@@ -47,8 +47,8 @@ export class ReplicaSet extends WorkloadKubeObject {
}
getImages() {
const containers: IPodContainer[] = get(this, "spec.template.spec.containers", [])
return [...containers].map(container => container.image)
const containers: IPodContainer[] = get(this, "spec.template.spec.containers", []);
return [...containers].map(container => container.image);
}
}
@@ -1,4 +1,4 @@
import jsYaml from "js-yaml"
import jsYaml from "js-yaml";
import { KubeObject } from "../kube-object";
import { KubeJsonApiData } from "../kube-json-api";
import { apiBase } from "../index";
@@ -21,7 +21,7 @@ export const resourceApplierApi = {
if (api) {
return new api.objectConstructor(obj);
} else {
return new KubeObject(obj)
return new KubeObject(obj);
}
});
return items.length === 1 ? items[0] : items;
@@ -37,7 +37,7 @@ export class ResourceQuota extends KubeObject {
constructor(data: KubeJsonApiData) {
super(data);
this.spec = this.spec || {} as any
this.spec = this.spec || {} as any;
}
spec: {
@@ -27,7 +27,7 @@ export class RoleBinding extends KubeObject {
}
getSubjectNames(): string {
return this.getSubjects().map(subject => subject.name).join(", ")
return this.getSubjects().map(subject => subject.name).join(", ");
}
}
@@ -58,7 +58,7 @@ export class SelfSubjectRulesReview extends KubeObject {
const separator = apiGroup == "" ? "" : ".";
return resource + separator + apiGroup;
})
}
};
}
}
+2 -2
View File
@@ -17,7 +17,7 @@ export class ServicePort implements IServicePort {
nodePort?: number;
constructor(data: IServicePort) {
Object.assign(this, data)
Object.assign(this, data);
}
toString() {
@@ -62,7 +62,7 @@ export class Service extends KubeObject {
getExternalIps() {
const lb = this.getLoadBalancer();
if (lb && lb.ingress) {
return lb.ingress.map(val => val.ip || val.hostname)
return lb.ingress.map(val => val.ip || val.hostname);
}
return this.spec.externalIPs || [];
}
@@ -73,8 +73,8 @@ export class StatefulSet extends WorkloadKubeObject {
}
getImages() {
const containers: IPodContainer[] = get(this, "spec.template.spec.containers", [])
return [...containers].map(container => container.image)
const containers: IPodContainer[] = get(this, "spec.template.spec.containers", []);
return [...containers].map(container => container.image);
}
}
@@ -21,15 +21,15 @@ export class StorageClass extends KubeObject {
return (
annotations["storageclass.kubernetes.io/is-default-class"] === "true" ||
annotations["storageclass.beta.kubernetes.io/is-default-class"] === "true"
)
);
}
getVolumeBindingMode() {
return this.volumeBindingMode || "-"
return this.volumeBindingMode || "-";
}
getReclaimPolicy() {
return this.reclaimPolicy || "-"
return this.reclaimPolicy || "-";
}
}
+6 -6
View File
@@ -110,23 +110,23 @@ export class JsonApi<D = JsonApiData, P extends JsonApiParams = JsonApiParams> {
} else {
const error = new JsonApiErrorParsed(data, this.parseError(data, res));
this.onError.emit(error, res);
this.writeLog({ ...log, error })
this.writeLog({ ...log, error });
throw error;
}
})
});
}
protected parseError(error: JsonApiError | string, res: Response): string[] {
if (typeof error === "string") {
return [error]
return [error];
}
else if (Array.isArray(error.errors)) {
return error.errors.map(error => error.title)
return error.errors.map(error => error.title);
}
else if (error.message) {
return [error.message]
return [error.message];
}
return [res.statusText || "Error!"]
return [res.statusText || "Error!"];
}
protected writeLog(log: JsonApiLog) {
+10 -10
View File
@@ -51,7 +51,7 @@ export function parseKubeApi(path: string): IKubeApiParsed {
} else {
switch (left.length) {
case 4:
[apiGroup, apiVersion, resource, name] = left
[apiGroup, apiVersion, resource, name] = left;
break;
case 2:
resource = left.pop();
@@ -79,11 +79,11 @@ export function parseKubeApi(path: string): IKubeApiParsed {
*/
if (left[0].includes('.') || left[1].match(/^v[0-9]/)) {
[apiGroup, apiVersion] = left;
resource = left.slice(2).join("/")
resource = left.slice(2).join("/");
} else {
apiGroup = "";
apiVersion = left[0];
[resource, name] = left.slice(1)
[resource, name] = left.slice(1);
}
break;
}
@@ -93,7 +93,7 @@ export function parseKubeApi(path: string): IKubeApiParsed {
const apiBase = [apiPrefix, apiGroup, apiVersion, resource].filter(v => v).join("/");
if (!apiBase) {
throw new Error(`invalid apiPath: ${path}`)
throw new Error(`invalid apiPath: ${path}`);
}
return {
@@ -108,11 +108,11 @@ export function createKubeApiURL(ref: IKubeApiLinkRef): string {
const { apiPrefix = "/apis", resource, apiVersion, name } = ref;
let { namespace } = ref;
if (namespace) {
namespace = `namespaces/${namespace}`
namespace = `namespaces/${namespace}`;
}
return [apiPrefix, apiVersion, namespace, resource, name]
.filter(v => v)
.join("/")
.join("/");
}
export function lookupApiLink(ref: IKubeObjectRef, parentObject: KubeObject): string {
@@ -124,9 +124,9 @@ export function lookupApiLink(ref: IKubeObjectRef, parentObject: KubeObject): st
if (!kind) return "";
// search in registered apis by 'kind' & 'apiVersion'
const api = apiManager.getApi(api => api.kind === kind && api.apiVersionWithGroup == apiVersion)
const api = apiManager.getApi(api => api.kind === kind && api.apiVersionWithGroup == apiVersion);
if (api) {
return api.getUrl({ namespace, name })
return api.getUrl({ namespace, name });
}
// lookup api by generated resource link
@@ -142,10 +142,10 @@ export function lookupApiLink(ref: IKubeObjectRef, parentObject: KubeObject): st
// resolve by kind only (hpa's might use refs to older versions of resources for example)
const apiByKind = apiManager.getApi(api => api.kind === kind);
if (apiByKind) {
return apiByKind.getUrl({ name, namespace })
return apiByKind.getUrl({ name, namespace });
}
// otherwise generate link with default prefix
// resource still might exists in k8s, but api is not registered in the app
return createKubeApiURL({ apiVersion, name, namespace, resource })
return createKubeApiURL({ apiVersion, name, namespace, resource });
}
+12 -12
View File
@@ -1,6 +1,6 @@
// Base class for building all kubernetes apis
import merge from "lodash/merge"
import merge from "lodash/merge";
import { stringify } from "querystring";
import { IKubeObjectConstructor, KubeObject } from "./kube-object";
import { KubeJsonApi, KubeJsonApiData, KubeJsonApiDataList } from "./kube-json-api";
@@ -51,7 +51,7 @@ export function forCluster<T extends KubeObject>(cluster: IKubeApiCluster, kubeC
return new KubeApi({
objectConstructor: kubeClass,
request: request
})
});
}
export class KubeApi<T extends KubeObject = any> {
@@ -83,7 +83,7 @@ export class KubeApi<T extends KubeObject = any> {
isNamespaced = options.objectConstructor?.namespaced
} = options || {};
if (!options.apiBase) {
options.apiBase = objectConstructor.apiBase
options.apiBase = objectConstructor.apiBase;
}
const { apiBase, apiPrefix, apiGroup, apiVersion, apiVersionWithGroup, resource } = KubeApi.parseApi(options.apiBase);
@@ -105,7 +105,7 @@ export class KubeApi<T extends KubeObject = any> {
get apiVersionWithGroup() {
return [this.apiGroup, this.apiVersionPreferred ?? this.apiVersion]
.filter(Boolean)
.join("/")
.join("/");
}
protected async checkPreferredVersion() {
@@ -116,7 +116,7 @@ export class KubeApi<T extends KubeObject = any> {
});
if (this.apiVersionPreferred) {
Object.defineProperty(this, "apiBase", { value: this.getUrl() })
Object.defineProperty(this, "apiBase", { value: this.getUrl() });
apiManager.registerApi(this.apiBase, this);
}
}
@@ -147,10 +147,10 @@ export class KubeApi<T extends KubeObject = any> {
protected normalizeQuery(query: Partial<IKubeApiQueryParams> = {}) {
if (query.labelSelector) {
query.labelSelector = [query.labelSelector].flat().join(",")
query.labelSelector = [query.labelSelector].flat().join(",");
}
if (query.fieldSelector) {
query.fieldSelector = [query.fieldSelector].flat().join(",")
query.fieldSelector = [query.fieldSelector].flat().join(",");
}
return query;
}
@@ -170,7 +170,7 @@ export class KubeApi<T extends KubeObject = any> {
kind: this.kind,
apiVersion: apiVersion,
...item,
}))
}));
}
// custom apis might return array for list response, e.g. users, groups, etc.
@@ -218,13 +218,13 @@ export class KubeApi<T extends KubeObject = any> {
const apiUrl = this.getUrl({ namespace, name });
return this.request
.put(apiUrl, { data })
.then(this.parseResponse)
.then(this.parseResponse);
}
async delete({ name = "", namespace = "default" }) {
await this.checkPreferredVersion();
const apiUrl = this.getUrl({ namespace, name });
return this.request.del(apiUrl)
return this.request.del(apiUrl);
}
getWatchUrl(namespace = "", query: IKubeApiQueryParams = {}) {
@@ -232,7 +232,7 @@ export class KubeApi<T extends KubeObject = any> {
watch: 1,
resourceVersion: this.getResourceVersion(namespace),
...query,
})
});
}
watch(): () => void {
@@ -240,4 +240,4 @@ export class KubeApi<T extends KubeObject = any> {
}
}
export * from "./kube-api-parse"
export * from "./kube-api-parse";
@@ -1 +1 @@
export { kubeObjectDetailRegistry } from "../../extensions/registries/kube-object-detail-registry"
export { kubeObjectDetailRegistry } from "../../extensions/registries/kube-object-detail-registry";
+5 -5
View File
@@ -65,7 +65,7 @@ export class KubeObject implements ItemObject {
static stringifyLabels(labels: { [name: string]: string }): string[] {
if (!labels) return [];
return Object.entries(labels).map(([name, value]) => `${name}=${value}`)
return Object.entries(labels).map(([name, value]) => `${name}=${value}`);
}
constructor(data: KubeJsonApiData) {
@@ -78,7 +78,7 @@ export class KubeObject implements ItemObject {
status?: any; // todo: type-safety support
get selfLink() {
return this.metadata.selfLink
return this.metadata.selfLink;
}
getId() {
@@ -131,18 +131,18 @@ export class KubeObject implements ItemObject {
return refs.map(ownerRef => ({
...ownerRef,
namespace: this.getNs(),
}))
}));
}
getSearchFields() {
const { getName, getId, getNs, getAnnotations, getLabels } = this
const { getName, getId, getNs, getAnnotations, getLabels } = this;
return [
getName(),
getNs(),
getId(),
...getLabels(),
...getAnnotations(true),
]
];
}
toPlainObject(): object {
+7 -7
View File
@@ -1,7 +1,7 @@
// Kubernetes watch-api consumer
import { computed, observable, reaction } from "mobx";
import { stringify } from "querystring"
import { stringify } from "querystring";
import { autobind, EventEmitter } from "../utils";
import { KubeJsonApiData } from "./kube-json-api";
import type { KubeObjectStore } from "../kube-object.store";
@@ -61,13 +61,13 @@ export class KubeWatchApi {
}
protected getQuery(): Partial<IKubeWatchRouteQuery> {
const { isAdmin, allowedNamespaces } = getHostedCluster()
const { isAdmin, allowedNamespaces } = getHostedCluster();
return {
api: this.activeApis.map(api => {
if (isAdmin) return api.getWatchUrl();
return allowedNamespaces.map(namespace => api.getWatchUrl(namespace))
return allowedNamespaces.map(namespace => api.getWatchUrl(namespace));
}).flat()
}
};
}
// todo: maybe switch to websocket to avoid often reconnects
@@ -119,11 +119,11 @@ export class KubeWatchApi {
await api.refreshResourceVersion({ namespace });
this.reconnect();
} catch (error) {
console.error("failed to refresh resource version", error)
console.error("failed to refresh resource version", error);
if (this.subscribers.size > 0) {
setTimeout(() => {
this.onRouteEvent(event)
}, 1000)
this.onRouteEvent(event);
}, 1000);
}
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { stringify } from "querystring";
import { autobind, base64, EventEmitter } from "../utils";
import { WebSocketApi } from "./websocket-api";
import isEqual from "lodash/isEqual"
import isEqual from "lodash/isEqual";
import { isDevelopment } from "../../common/vars";
export enum TerminalChannels {
@@ -51,7 +51,7 @@ export class TerminalApi extends WebSocketApi {
const wss = `ws${protocol === "https:" ? "s" : ""}://`;
const query: TerminalApiQuery = { id };
if (port) {
port = `:${port}`
port = `:${port}`;
}
if (node) {
query.node = node;
+1 -1
View File
@@ -146,7 +146,7 @@ export class WebSocketApi {
}
protected _onError(evt: Event) {
this.writeLog('%cERROR', 'color:red;font-weight:bold;', evt)
this.writeLog('%cERROR', 'color:red;font-weight:bold;', evt);
}
protected _onClose(evt: CloseEvent) {
+5 -5
View File
@@ -65,16 +65,16 @@ export class WorkloadKubeObject extends KubeObject {
}
getTolerations(): IToleration[] {
return get(this, "spec.template.spec.tolerations", [])
return get(this, "spec.template.spec.tolerations", []);
}
getAffinity(): IAffinity {
return get(this, "spec.template.spec.affinity")
return get(this, "spec.template.spec.affinity");
}
getAffinityNumber() {
const affinity = this.getAffinity()
if (!affinity) return 0
return Object.keys(affinity).length
const affinity = this.getAffinity();
if (!affinity) return 0;
return Object.keys(affinity).length;
}
}