Applied prettier to code

This commit is contained in:
djeinstine 2024-11-09 19:30:09 +00:00
parent cb2c7b9147
commit bbb1ef5a55
3 changed files with 163 additions and 169 deletions

View File

@ -7,36 +7,31 @@ import { KubeConfig } from "@kubernetes/client-node";
import checkAndCopyConfig, { CONF_DIR, substituteEnvironmentVars } from "utils/config/config"; import checkAndCopyConfig, { CONF_DIR, substituteEnvironmentVars } from "utils/config/config";
const extractKubeData = (config) => { const extractKubeData = (config) => {
//kubeconfig //kubeconfig
const kc = new KubeConfig(); const kc = new KubeConfig();
kc.loadFromCluster() kc.loadFromCluster();
//route //route
let route="ingress"; let route = "ingress";
if (config?.route=="gateway"){ if (config?.route == "gateway") {
route="gateway"; route = "gateway";
} }
//traefik //traefik
let traefik=true; let traefik = true;
if (config?.traefik=="disable"){ if (config?.traefik == "disable") {
traefik=false; traefik = false;
} }
//traefik //traefik
let metrics=true; let metrics = true;
if (config?.metrics=="disable"){ if (config?.metrics == "disable") {
metrics=false; metrics = false;
} }
//return //return
return {"config":kc, return { config: kc, route: route, traefik: traefik, metrics: metrics };
"route":route, };
"traefik":traefik,
"metrics":metrics
};
}
export default function getKubeArguments() { export default function getKubeArguments() {
checkAndCopyConfig("kubernetes.yaml"); checkAndCopyConfig("kubernetes.yaml");
@ -56,7 +51,7 @@ export default function getKubeArguments() {
break; break;
case "disabled": case "disabled":
default: default:
kubeData=null; kubeData = null;
} }
return kubeData; return kubeData;

View File

@ -8,7 +8,7 @@ import { ApiextensionsV1Api } from "@kubernetes/client-node";
import createLogger from "utils/logger"; import createLogger from "utils/logger";
import checkAndCopyConfig, { CONF_DIR, getSettings, substituteEnvironmentVars } from "utils/config/config"; import checkAndCopyConfig, { CONF_DIR, getSettings, substituteEnvironmentVars } from "utils/config/config";
import getDockerArguments from "utils/config/docker"; import getDockerArguments from "utils/config/docker";
import {getUrlSchema,getRouteList} from "utils/kubernetes/kubernetes-routes"; import { getUrlSchema, getRouteList } from "utils/kubernetes/kubernetes-routes";
import * as shvl from "utils/config/shvl"; import * as shvl from "utils/config/shvl";
const logger = createLogger("service-helpers"); const logger = createLogger("service-helpers");
@ -165,62 +165,63 @@ export async function servicesFromKubernetes() {
return []; return [];
} }
const services = await Promise.all(routeList const services = await Promise.all(
.filter( routeList
(route) => .filter(
route.metadata.annotations && (route) =>
route.metadata.annotations[`${ANNOTATION_BASE}/enabled`] === "true" && route.metadata.annotations &&
(!route.metadata.annotations[`${ANNOTATION_BASE}/instance`] || route.metadata.annotations[`${ANNOTATION_BASE}/enabled`] === "true" &&
route.metadata.annotations[`${ANNOTATION_BASE}/instance`] === instanceName || (!route.metadata.annotations[`${ANNOTATION_BASE}/instance`] ||
`${ANNOTATION_BASE}/instance.${instanceName}` in route.metadata.annotations), route.metadata.annotations[`${ANNOTATION_BASE}/instance`] === instanceName ||
) `${ANNOTATION_BASE}/instance.${instanceName}` in route.metadata.annotations),
.map( async (route) => { )
let constructedService = { .map(async (route) => {
app: route.metadata.annotations[`${ANNOTATION_BASE}/app`] || route.metadata.name, let constructedService = {
namespace: route.metadata.namespace, app: route.metadata.annotations[`${ANNOTATION_BASE}/app`] || route.metadata.name,
href: route.metadata.annotations[`${ANNOTATION_BASE}/href`] || await getUrlSchema(route), namespace: route.metadata.namespace,
name: route.metadata.annotations[`${ANNOTATION_BASE}/name`] || route.metadata.name, href: route.metadata.annotations[`${ANNOTATION_BASE}/href`] || (await getUrlSchema(route)),
group: route.metadata.annotations[`${ANNOTATION_BASE}/group`] || "Kubernetes", name: route.metadata.annotations[`${ANNOTATION_BASE}/name`] || route.metadata.name,
weight: route.metadata.annotations[`${ANNOTATION_BASE}/weight`] || "0", group: route.metadata.annotations[`${ANNOTATION_BASE}/group`] || "Kubernetes",
icon: route.metadata.annotations[`${ANNOTATION_BASE}/icon`] || "", weight: route.metadata.annotations[`${ANNOTATION_BASE}/weight`] || "0",
description: route.metadata.annotations[`${ANNOTATION_BASE}/description`] || "", icon: route.metadata.annotations[`${ANNOTATION_BASE}/icon`] || "",
external: false, description: route.metadata.annotations[`${ANNOTATION_BASE}/description`] || "",
type: "service", external: false,
}; type: "service",
if (route.metadata.annotations[`${ANNOTATION_BASE}/external`]) { };
constructedService.external = if (route.metadata.annotations[`${ANNOTATION_BASE}/external`]) {
String(route.metadata.annotations[`${ANNOTATION_BASE}/external`]).toLowerCase() === "true"; constructedService.external =
} String(route.metadata.annotations[`${ANNOTATION_BASE}/external`]).toLowerCase() === "true";
if (route.metadata.annotations[`${ANNOTATION_BASE}/pod-selector`] !== undefined) {
constructedService.podSelector = route.metadata.annotations[`${ANNOTATION_BASE}/pod-selector`];
}
if (route.metadata.annotations[`${ANNOTATION_BASE}/ping`]) {
constructedService.ping = route.metadata.annotations[`${ANNOTATION_BASE}/ping`];
}
if (route.metadata.annotations[`${ANNOTATION_BASE}/siteMonitor`]) {
constructedService.siteMonitor = route.metadata.annotations[`${ANNOTATION_BASE}/siteMonitor`];
}
if (route.metadata.annotations[`${ANNOTATION_BASE}/statusStyle`]) {
constructedService.statusStyle = route.metadata.annotations[`${ANNOTATION_BASE}/statusStyle`];
}
Object.keys(route.metadata.annotations).forEach((annotation) => {
if (annotation.startsWith(ANNOTATION_WIDGET_BASE)) {
shvl.set(
constructedService,
annotation.replace(`${ANNOTATION_BASE}/`, ""),
route.metadata.annotations[annotation],
);
} }
}); if (route.metadata.annotations[`${ANNOTATION_BASE}/pod-selector`] !== undefined) {
constructedService.podSelector = route.metadata.annotations[`${ANNOTATION_BASE}/pod-selector`];
}
if (route.metadata.annotations[`${ANNOTATION_BASE}/ping`]) {
constructedService.ping = route.metadata.annotations[`${ANNOTATION_BASE}/ping`];
}
if (route.metadata.annotations[`${ANNOTATION_BASE}/siteMonitor`]) {
constructedService.siteMonitor = route.metadata.annotations[`${ANNOTATION_BASE}/siteMonitor`];
}
if (route.metadata.annotations[`${ANNOTATION_BASE}/statusStyle`]) {
constructedService.statusStyle = route.metadata.annotations[`${ANNOTATION_BASE}/statusStyle`];
}
Object.keys(route.metadata.annotations).forEach((annotation) => {
if (annotation.startsWith(ANNOTATION_WIDGET_BASE)) {
shvl.set(
constructedService,
annotation.replace(`${ANNOTATION_BASE}/`, ""),
route.metadata.annotations[annotation],
);
}
});
try { try {
constructedService = JSON.parse(substituteEnvironmentVars(JSON.stringify(constructedService))); constructedService = JSON.parse(substituteEnvironmentVars(JSON.stringify(constructedService)));
} catch (e) { } catch (e) {
logger.error("Error attempting k8s environment variable substitution."); logger.error("Error attempting k8s environment variable substitution.");
logger.debug(e); logger.debug(e);
} }
return constructedService; return constructedService;
}) }),
); );
const mappedServiceGroups = []; const mappedServiceGroups = [];

View File

@ -1,5 +1,3 @@
import { CustomObjectsApi, NetworkingV1Api, CoreV1Api, ApiextensionsV1Api } from "@kubernetes/client-node"; import { CustomObjectsApi, NetworkingV1Api, CoreV1Api, ApiextensionsV1Api } from "@kubernetes/client-node";
import getKubeArguments from "utils/config/kubernetes"; import getKubeArguments from "utils/config/kubernetes";
import createLogger from "utils/logger"; import createLogger from "utils/logger";
@ -9,8 +7,8 @@ const logger = createLogger("service-helpers");
const kubeArguments = getKubeArguments(); const kubeArguments = getKubeArguments();
const kc = kubeArguments.config; const kc = kubeArguments.config;
const apiGroup = 'gateway.networking.k8s.io'; const apiGroup = "gateway.networking.k8s.io";
const version = 'v1'; const version = "v1";
let crd; let crd;
let core; let core;
@ -18,7 +16,6 @@ let networking;
let routingType; let routingType;
let traefik; let traefik;
export async function checkCRD(kc, name) { export async function checkCRD(kc, name) {
const apiExtensions = kc.makeApiClient(ApiextensionsV1Api); const apiExtensions = kc.makeApiClient(ApiextensionsV1Api);
const exist = await apiExtensions const exist = await apiExtensions
@ -40,124 +37,127 @@ export async function checkCRD(kc, name) {
} }
const getSchemaFromGateway = async (gatewayRef) => { const getSchemaFromGateway = async (gatewayRef) => {
try { try {
const gateway = await crd.getNamespacedCustomObject(apiGroup, version, gatewayRef.namespace,"gateways",gatewayRef.name); const gateway = await crd.getNamespacedCustomObject(
const listener = gateway.body.spec.listeners.filter((listener)=>listener.name==gatewayRef.sectionName)[0]; apiGroup,
return listener.protocol.toLowerCase(); version,
} catch (err) { gatewayRef.namespace,
console.error(err); "gateways",
} gatewayRef.name,
);
const listener = gateway.body.spec.listeners.filter((listener) => listener.name == gatewayRef.sectionName)[0];
return listener.protocol.toLowerCase();
} catch (err) {
console.error(err);
}
}; };
async function getUrlFromHttpRoute(ingress) { async function getUrlFromHttpRoute(ingress) {
const urlHost = ingress.spec.hostnames[0]; const urlHost = ingress.spec.hostnames[0];
const urlPath = ingress.spec.rules[0].matches[0].path.value; const urlPath = ingress.spec.rules[0].matches[0].path.value;
const urlSchema = await getSchemaFromGateway(ingress.spec.parentRefs[0]) ? "https" : "http"; const urlSchema = (await getSchemaFromGateway(ingress.spec.parentRefs[0])) ? "https" : "http";
// const urlSchema = "https" // const urlSchema = "https"
return `${urlSchema}://${urlHost}${urlPath}`; return `${urlSchema}://${urlHost}${urlPath}`;
} }
function getUrlFromIngress(ingress) { function getUrlFromIngress(ingress) {
const urlHost = ingress.spec.rules[0].host; const urlHost = ingress.spec.rules[0].host;
const urlPath = ingress.spec.rules[0].http.paths[0].path; const urlPath = ingress.spec.rules[0].http.paths[0].path;
const urlSchema = ingress.spec.tls ? "https" : "http"; const urlSchema = ingress.spec.tls ? "https" : "http";
return `${urlSchema}://${urlHost}${urlPath}`; return `${urlSchema}://${urlHost}${urlPath}`;
} }
async function getHttpRouteList(){ async function getHttpRouteList() {
const httpRouteList = new Array(); const httpRouteList = new Array();
const namespaces = await core.listNamespace() const namespaces = await core
.then((response) => response.body.items.map(ns => ns.metadata.name)) .listNamespace()
.then((response) => response.body.items.map((ns) => ns.metadata.name))
.catch((error) => { .catch((error) => {
logger.error("Error getting namespaces: %d %s %s", error.statusCode, error.body, error.response); logger.error("Error getting namespaces: %d %s %s", error.statusCode, error.body, error.response);
logger.debug(error); logger.debug(error);
return null; return null;
}) });
if (namespaces){ if (namespaces) {
// Iterate over each namespace // Iterate over each namespace
for (const namespace of namespaces) { for (const namespace of namespaces) {
try { try {
// Fetch the httproute from one namespaces // Fetch the httproute from one namespaces
const httpRoute = await crd.listNamespacedCustomObject(apiGroup,version,namespace,'httproutes'); const httpRoute = await crd.listNamespacedCustomObject(apiGroup, version, namespace, "httproutes");
if (httpRoute.body.items.length !== 0){ if (httpRoute.body.items.length !== 0) {
httpRouteList.push(httpRoute.body.items[0]); httpRouteList.push(httpRoute.body.items[0]);
}
} catch (err) {
console.error(`Error fetching httproutes objects in namespace "${namespace}":`, err.body || err.message);
}
} }
} catch (err) {
console.error(`Error fetching httproutes objects in namespace "${namespace}":`, err.body || err.message);
}
} }
return httpRouteList; }
return httpRouteList;
} }
async function getIngressList(){ async function getIngressList() {
const ingressList = await networking const ingressList = await networking
.listIngressForAllNamespaces(null, null, null, null) .listIngressForAllNamespaces(null, null, null, null)
.then((response) => response.body) .then((response) => response.body)
.catch((error) => { .catch((error) => {
logger.error("Error getting ingresses: %d %s %s", error.statusCode, error.body, error.response); logger.error("Error getting ingresses: %d %s %s", error.statusCode, error.body, error.response);
logger.debug(error); logger.debug(error);
return null; return null;
}); });
if (traefik){ if (traefik) {
const traefikContainoExists = await checkCRD(kc, "ingressroutes.traefik.containo.us"); const traefikContainoExists = await checkCRD(kc, "ingressroutes.traefik.containo.us");
const traefikExists = await checkCRD(kc, "ingressroutes.traefik.io"); const traefikExists = await checkCRD(kc, "ingressroutes.traefik.io");
const traefikIngressListContaino = await crd const traefikIngressListContaino = await crd
.listClusterCustomObject("traefik.containo.us", "v1alpha1", "ingressroutes") .listClusterCustomObject("traefik.containo.us", "v1alpha1", "ingressroutes")
.then((response) => response.body) .then((response) => response.body)
.catch(async (error) => { .catch(async (error) => {
if (traefikContainoExists) { if (traefikContainoExists) {
logger.error( logger.error(
"Error getting traefik ingresses from traefik.containo.us: %d %s %s", "Error getting traefik ingresses from traefik.containo.us: %d %s %s",
error.statusCode, error.statusCode,
error.body, error.body,
error.response, error.response,
); );
logger.debug(error); logger.debug(error);
} }
return []; return [];
}); });
const traefikIngressListIo = await crd const traefikIngressListIo = await crd
.listClusterCustomObject("traefik.io", "v1alpha1", "ingressroutes") .listClusterCustomObject("traefik.io", "v1alpha1", "ingressroutes")
.then((response) => response.body) .then((response) => response.body)
.catch(async (error) => { .catch(async (error) => {
if (traefikExists) { if (traefikExists) {
logger.error( logger.error(
"Error getting traefik ingresses from traefik.io: %d %s %s", "Error getting traefik ingresses from traefik.io: %d %s %s",
error.statusCode, error.statusCode,
error.body, error.body,
error.response, error.response,
); );
logger.debug(error); logger.debug(error);
} }
return []; return [];
}); });
const traefikIngressList = [...(traefikIngressListContaino?.items ?? []), ...(traefikIngressListIo?.items ?? [])]; const traefikIngressList = [...(traefikIngressListContaino?.items ?? []), ...(traefikIngressListIo?.items ?? [])];
if (traefikIngressList.length > 0) { if (traefikIngressList.length > 0) {
const traefikServices = traefikIngressList.filter( const traefikServices = traefikIngressList.filter(
(ingress) => ingress.metadata.annotations && ingress.metadata.annotations[`${ANNOTATION_BASE}/href`], (ingress) => ingress.metadata.annotations && ingress.metadata.annotations[`${ANNOTATION_BASE}/href`],
); );
ingressList.items.push(...traefikServices); ingressList.items.push(...traefikServices);
} }
} }
return ingressList.items; return ingressList.items;
} }
export async function getRouteList(){ export async function getRouteList() {
let routeList = new Array(); let routeList = new Array();
if (!kc) { if (!kc) {
@ -171,7 +171,6 @@ export async function getRouteList(){
routingType = kubeArguments.route; routingType = kubeArguments.route;
traefik = kubeArguments.traefik; traefik = kubeArguments.traefik;
switch (routingType) { switch (routingType) {
case "ingress": case "ingress":
routeList = await getIngressList(); routeList = await getIngressList();
@ -187,18 +186,17 @@ export async function getRouteList(){
} }
export async function getUrlSchema(route) { export async function getUrlSchema(route) {
let urlSchema; let urlSchema;
switch (routingType) { switch (routingType) {
case "ingress": case "ingress":
urlSchema = getUrlFromIngress(route); urlSchema = getUrlFromIngress(route);
break; break;
case "gateway": case "gateway":
urlSchema = await getUrlFromHttpRoute(route); urlSchema = await getUrlFromHttpRoute(route);
break; break;
default: default:
urlSchema = getUrlFromIngress(route); urlSchema = getUrlFromIngress(route);
}
return urlSchema;
} }
return urlSchema;
}