chore: switch to react-router v7

This commit is contained in:
Aarnav Tale
2024-12-31 10:30:14 +05:30
parent 39504e2487
commit aa9872a45b
101 changed files with 3825 additions and 6796 deletions
+60 -67
View File
@@ -1,17 +1,17 @@
import { access, constants } from 'node:fs/promises'
import { setTimeout } from 'node:timers/promises'
import { access, constants } from 'node:fs/promises';
import { setTimeout } from 'node:timers/promises';
import { Client } from 'undici'
import { Client } from 'undici';
import { HeadscaleError, pull } from '~/utils/headscale'
import log from '~/utils/log'
import { HeadscaleError, pull } from '~/utils/headscale';
import log from '~/utils/log';
import { createIntegration } from './integration'
import { createIntegration } from './integration';
interface Context {
client: Client | undefined
container: string | undefined
maxAttempts: number
client: Client | undefined;
container: string | undefined;
maxAttempts: number;
}
export default createIntegration<Context>({
@@ -24,133 +24,126 @@ export default createIntegration<Context>({
isAvailable: async (context) => {
// Check for the HEADSCALE_CONTAINER environment variable first
// to avoid unnecessary fetching of the Docker socket
log.debug('INTG', 'Checking Docker integration availability')
context.container = process.env.HEADSCALE_CONTAINER
?.trim()
.toLowerCase()
log.debug('INTG', 'Checking Docker integration availability');
context.container = process.env.HEADSCALE_CONTAINER?.trim().toLowerCase();
if (!context.container || context.container.length === 0) {
log.error('INTG', 'Missing HEADSCALE_CONTAINER variable')
return false
log.error('INTG', 'Missing HEADSCALE_CONTAINER variable');
return false;
}
log.info('INTG', 'Using container: %s', context.container)
const path = process.env.DOCKER_SOCK ?? 'unix:///var/run/docker.sock'
let url: URL | undefined
log.info('INTG', 'Using container: %s', context.container);
const path = process.env.DOCKER_SOCK ?? 'unix:///var/run/docker.sock';
let url: URL | undefined;
try {
url = new URL(path)
url = new URL(path);
} catch {
log.error('INTG', 'Invalid Docker socket path: %s', path)
return false
log.error('INTG', 'Invalid Docker socket path: %s', path);
return false;
}
if (url.protocol !== 'tcp:' && url.protocol !== 'unix:') {
log.error('INTG', 'Invalid Docker socket protocol: %s',
url.protocol,
)
return false
log.error('INTG', 'Invalid Docker socket protocol: %s', url.protocol);
return false;
}
// The API is available as an HTTP endpoint and this
// will simplify the fetching logic in undici
if (url.protocol === 'tcp:') {
// Apparently setting url.protocol doesn't work anymore?
const fetchU = url.href.replace(url.protocol, 'http:')
const fetchU = url.href.replace(url.protocol, 'http:');
try {
log.info('INTG', 'Checking API: %s', fetchU)
await fetch(new URL('/v1.30/version', fetchU).href)
log.info('INTG', 'Checking API: %s', fetchU);
await fetch(new URL('/v1.30/version', fetchU).href);
} catch (error) {
log.debug('INTG', 'Failed to connect to Docker API', error)
log.error('INTG', 'Failed to connect to Docker API')
return false
log.debug('INTG', 'Failed to connect to Docker API', error);
log.error('INTG', 'Failed to connect to Docker API');
return false;
}
context.client = new Client(fetchU)
context.client = new Client(fetchU);
}
// Check if the socket is accessible
if (url.protocol === 'unix:') {
try {
log.info('INTG', 'Checking socket: %s',
url.pathname,
)
await access(url.pathname, constants.R_OK)
log.info('INTG', 'Checking socket: %s', url.pathname);
await access(url.pathname, constants.R_OK);
} catch (error) {
log.debug('INTG', 'Failed to access Docker socket: %s', error)
log.error('INTG', 'Failed to access Docker socket: %s',
path,
)
return false
log.debug('INTG', 'Failed to access Docker socket: %s', error);
log.error('INTG', 'Failed to access Docker socket: %s', path);
return false;
}
context.client = new Client('http://localhost', {
socketPath: url.pathname,
})
});
}
return context.client !== undefined
return context.client !== undefined;
},
onConfigChange: async (context) => {
if (!context.client || !context.container) {
return
return;
}
log.info('INTG', 'Restarting Headscale via Docker')
log.info('INTG', 'Restarting Headscale via Docker');
let attempts = 0
let attempts = 0;
while (attempts <= context.maxAttempts) {
log.debug(
'INTG', 'Restarting container: %s (attempt %d)',
'INTG',
'Restarting container: %s (attempt %d)',
context.container,
attempts,
)
);
const response = await context.client.request({
method: 'POST',
path: `/v1.30/containers/${context.container}/restart`,
})
});
if (response.statusCode !== 204) {
if (attempts < context.maxAttempts) {
attempts++
await setTimeout(1000)
continue
attempts++;
await setTimeout(1000);
continue;
}
const stringCode = response.statusCode.toString()
const body = await response.body.text()
throw new Error(`API request failed: ${stringCode} ${body}`)
const stringCode = response.statusCode.toString();
const body = await response.body.text();
throw new Error(`API request failed: ${stringCode} ${body}`);
}
break
break;
}
attempts = 0
attempts = 0;
while (attempts <= context.maxAttempts) {
try {
log.debug('INTG', 'Checking Headscale status (attempt %d)', attempts)
await pull('v1', '')
return
log.debug('INTG', 'Checking Headscale status (attempt %d)', attempts);
await pull('v1', '');
return;
} catch (error) {
if (error instanceof HeadscaleError && error.status === 401) {
break
break;
}
if (error instanceof HeadscaleError && error.status === 404) {
break
break;
}
if (attempts < context.maxAttempts) {
attempts++
await setTimeout(1000)
continue
attempts++;
await setTimeout(1000);
continue;
}
throw new Error(`Missed restart deadline for ${context.container}`)
throw new Error(`Missed restart deadline for ${context.container}`);
}
}
},
})
});
+27 -34
View File
@@ -1,75 +1,68 @@
import log from '~/utils/log'
import log from '~/utils/log';
import dockerIntegration from './docker'
import { IntegrationFactory } from './integration'
import kubernetesIntegration from './kubernetes'
import procIntegration from './proc'
import dockerIntegration from './docker';
import { IntegrationFactory } from './integration';
import kubernetesIntegration from './kubernetes';
import procIntegration from './proc';
export * from './integration'
export * from './integration';
export async function loadIntegration() {
let integration = process.env.HEADSCALE_INTEGRATION
?.trim()
.toLowerCase()
let integration = process.env.HEADSCALE_INTEGRATION?.trim().toLowerCase();
// Old HEADSCALE_CONTAINER variable upgrade path
// This ensures that when people upgrade from older versions of Headplane
// they don't explicitly need to define the new HEADSCALE_INTEGRATION
// variable that is needed to configure docker
if (!integration && process.env.HEADSCALE_CONTAINER) {
integration = 'docker'
integration = 'docker';
}
if (!integration) {
log.info('INTG', 'No integration set with HEADSCALE_INTEGRATION')
return
log.info('INTG', 'No integration set with HEADSCALE_INTEGRATION');
return;
}
let integrationFactory: IntegrationFactory | undefined
let integrationFactory: IntegrationFactory | undefined;
switch (integration.toLowerCase().trim()) {
case 'docker': {
integrationFactory = dockerIntegration
break
integrationFactory = dockerIntegration;
break;
}
case 'proc':
case 'native':
case 'linux': {
integrationFactory = procIntegration
break
integrationFactory = procIntegration;
break;
}
case 'kubernetes':
case 'k8s': {
integrationFactory = kubernetesIntegration
break
integrationFactory = kubernetesIntegration;
break;
}
default: {
log.error('INTG', 'Unknown integration: %s', integration)
throw new Error(`Unknown integration: ${integration}`)
log.error('INTG', 'Unknown integration: %s', integration);
throw new Error(`Unknown integration: ${integration}`);
}
}
log.info('INTG', 'Loading integration: %s', integration)
log.info('INTG', 'Loading integration: %s', integration);
try {
const res = await integrationFactory.isAvailable(
integrationFactory.context,
)
);
if (!res) {
log.error('INTG', 'Integration %s is not available',
integration,
)
return
log.error('INTG', 'Integration %s is not available', integration);
return;
}
} catch (error) {
log.error('INTG', 'Failed to load integration %s: %s',
integration,
error,
)
return
log.error('INTG', 'Failed to load integration %s: %s', integration, error);
return;
}
log.info('INTG', 'Loaded integration: %s', integration)
return integrationFactory
log.info('INTG', 'Loaded integration: %s', integration);
return integrationFactory;
}
+6 -8
View File
@@ -1,13 +1,11 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export interface IntegrationFactory<T = any> {
name: string
context: T
isAvailable: (context: T) => Promise<boolean> | boolean
onConfigChange?: (context: T) => Promise<void> | void
name: string;
context: T;
isAvailable: (context: T) => Promise<boolean> | boolean;
onConfigChange?: (context: T) => Promise<void> | void;
}
export function createIntegration<T>(
options: IntegrationFactory<T>,
) {
return options
export function createIntegration<T>(options: IntegrationFactory<T>) {
return options;
}
+99 -92
View File
@@ -1,16 +1,16 @@
import { readdir, readFile } from 'node:fs/promises'
import { platform } from 'node:os'
import { join, resolve } from 'node:path'
import { kill } from 'node:process'
import { readdir, readFile } from 'node:fs/promises';
import { platform } from 'node:os';
import { join, resolve } from 'node:path';
import { kill } from 'node:process';
import { Config, CoreV1Api, KubeConfig } from '@kubernetes/client-node'
import { Config, CoreV1Api, KubeConfig } from '@kubernetes/client-node';
import log from '~/utils/log'
import log from '~/utils/log';
import { createIntegration } from './integration'
import { createIntegration } from './integration';
interface Context {
pid: number | undefined
pid: number | undefined;
}
export default createIntegration<Context>({
@@ -20,185 +20,192 @@ export default createIntegration<Context>({
},
isAvailable: async (context) => {
if (platform() !== 'linux') {
log.error('INTG', 'Kubernetes is only available on Linux')
return false
log.error('INTG', 'Kubernetes is only available on Linux');
return false;
}
const svcRoot = Config.SERVICEACCOUNT_ROOT
const svcRoot = Config.SERVICEACCOUNT_ROOT;
try {
log.debug('INTG', 'Checking Kubernetes service account at %s', svcRoot)
const files = await readdir(svcRoot)
log.debug('INTG', 'Checking Kubernetes service account at %s', svcRoot);
const files = await readdir(svcRoot);
if (files.length === 0) {
log.error('INTG', 'Kubernetes service account not found')
return false
log.error('INTG', 'Kubernetes service account not found');
return false;
}
const mappedFiles = new Set(files.map(file => join(svcRoot, file)))
const mappedFiles = new Set(files.map((file) => join(svcRoot, file)));
const expectedFiles = [
Config.SERVICEACCOUNT_CA_PATH,
Config.SERVICEACCOUNT_TOKEN_PATH,
Config.SERVICEACCOUNT_NAMESPACE_PATH,
]
];
log.debug('INTG', 'Looking for %s', expectedFiles.join(', '))
if (!expectedFiles.every(file => mappedFiles.has(file))) {
log.error('INTG', 'Malformed Kubernetes service account')
return false
log.debug('INTG', 'Looking for %s', expectedFiles.join(', '));
if (!expectedFiles.every((file) => mappedFiles.has(file))) {
log.error('INTG', 'Malformed Kubernetes service account');
return false;
}
} catch (error) {
log.error('INTG', 'Failed to access %s: %s', svcRoot, error)
return false
log.error('INTG', 'Failed to access %s: %s', svcRoot, error);
return false;
}
log.debug('INTG', 'Reading Kubernetes service account at %s', svcRoot)
log.debug('INTG', 'Reading Kubernetes service account at %s', svcRoot);
const namespace = await readFile(
Config.SERVICEACCOUNT_NAMESPACE_PATH,
'utf8',
)
);
// Some very ugly nesting but it's necessary
if (process.env.HEADSCALE_INTEGRATION_UNSTRICT === 'true') {
log.warn('INTG', 'Skipping strict Pod status check')
log.warn('INTG', 'Skipping strict Pod status check');
} else {
const pod = process.env.POD_NAME
const pod = process.env.POD_NAME;
if (!pod) {
log.error('INTG', 'Missing POD_NAME variable')
return false
log.error('INTG', 'Missing POD_NAME variable');
return false;
}
if (pod.trim().length === 0) {
log.error('INTG', 'Pod name is empty')
return false
log.error('INTG', 'Pod name is empty');
return false;
}
log.debug('INTG', 'Checking Kubernetes pod %s in namespace %s',
log.debug(
'INTG',
'Checking Kubernetes pod %s in namespace %s',
pod,
namespace,
)
);
try {
log.debug('INTG', 'Attempgin to get cluster KubeConfig')
const kc = new KubeConfig()
kc.loadFromCluster()
log.debug('INTG', 'Attempgin to get cluster KubeConfig');
const kc = new KubeConfig();
kc.loadFromCluster();
const cluster = kc.getCurrentCluster()
const cluster = kc.getCurrentCluster();
if (!cluster) {
log.error('INTG', 'Malformed kubeconfig')
return false
log.error('INTG', 'Malformed kubeconfig');
return false;
}
log.info('INTG', 'Service account connected to %s (%s)',
log.info(
'INTG',
'Service account connected to %s (%s)',
cluster.name,
cluster.server,
)
);
const kCoreV1Api = kc.makeApiClient(CoreV1Api)
const kCoreV1Api = kc.makeApiClient(CoreV1Api);
log.info('INTG', 'Checking pod %s in namespace %s (%s)',
log.info(
'INTG',
'Checking pod %s in namespace %s (%s)',
pod,
namespace,
kCoreV1Api.basePath,
)
);
log.debug('INTG', 'Reading pod info for %s', pod)
log.debug('INTG', 'Reading pod info for %s', pod);
const { response, body } = await kCoreV1Api.readNamespacedPod(
pod,
namespace,
)
);
if (response.statusCode !== 200) {
log.error('INTG', 'Failed to read pod info: http %d',
response.statusCode,
)
return false
}
log.debug('INTG', 'Got pod info: %o', body.spec)
const shared = body.spec?.shareProcessNamespace
if (shared === undefined) {
log.error(
'INTG',
'Pod does not have spec.shareProcessNamespace set',
)
return false
'Failed to read pod info: http %d',
response.statusCode,
);
return false;
}
log.debug('INTG', 'Got pod info: %o', body.spec);
const shared = body.spec?.shareProcessNamespace;
if (shared === undefined) {
log.error('INTG', 'Pod does not have spec.shareProcessNamespace set');
return false;
}
if (!shared) {
log.error(
'INTG',
'Pod has set but disabled spec.shareProcessNamespace',
)
return false
);
return false;
}
log.info('INTG', 'Pod %s enabled shared processes', pod)
log.info('INTG', 'Pod %s enabled shared processes', pod);
} catch (error) {
log.error('INTG', 'Failed to read pod info: %s', error)
return false
log.error('INTG', 'Failed to read pod info: %s', error);
return false;
}
}
log.debug('INTG', 'Looking for namespaced process in /proc')
const dir = resolve('/proc')
log.debug('INTG', 'Looking for namespaced process in /proc');
const dir = resolve('/proc');
try {
const subdirs = await readdir(dir)
const subdirs = await readdir(dir);
const promises = subdirs.map(async (dir) => {
const pid = Number.parseInt(dir, 10)
const pid = Number.parseInt(dir, 10);
if (Number.isNaN(pid)) {
return
return;
}
const path = join('/proc', dir, 'cmdline')
const path = join('/proc', dir, 'cmdline');
try {
log.debug('INTG', 'Reading %s', path)
const data = await readFile(path, 'utf8')
log.debug('INTG', 'Reading %s', path);
const data = await readFile(path, 'utf8');
if (data.includes('headscale')) {
return pid
return pid;
}
} catch (error) {
log.debug('INTG', 'Failed to read %s: %s', path, error)
log.debug('INTG', 'Failed to read %s: %s', path, error);
}
})
});
const results = await Promise.allSettled(promises)
const pids = []
const results = await Promise.allSettled(promises);
const pids = [];
for (const result of results) {
if (result.status === 'fulfilled' && result.value) {
pids.push(result.value)
pids.push(result.value);
}
}
log.debug('INTG', 'Found Headscale processes: %o', pids)
log.debug('INTG', 'Found Headscale processes: %o', pids);
if (pids.length > 1) {
log.error('INTG', 'Found %d Headscale processes: %s',
log.error(
'INTG',
'Found %d Headscale processes: %s',
pids.length,
pids.join(', '),
)
return false
);
return false;
}
if (pids.length === 0) {
log.error('INTG', 'Could not find Headscale process')
return false
log.error('INTG', 'Could not find Headscale process');
return false;
}
context.pid = pids[0]
log.info('INTG', 'Found Headscale process with PID: %d', context.pid)
return true
context.pid = pids[0];
log.info('INTG', 'Found Headscale process with PID: %d', context.pid);
return true;
} catch {
log.error('INTG', 'Failed to read /proc')
return false
log.error('INTG', 'Failed to read /proc');
return false;
}
},
onConfigChange: (context) => {
if (!context.pid) {
return
return;
}
log.info('INTG', 'Sending SIGTERM to Headscale')
kill(context.pid, 'SIGTERM')
log.info('INTG', 'Sending SIGTERM to Headscale');
kill(context.pid, 'SIGTERM');
},
})
});
+38 -36
View File
@@ -1,14 +1,14 @@
import { readdir, readFile } from 'node:fs/promises'
import { platform } from 'node:os'
import { join, resolve } from 'node:path'
import { kill } from 'node:process'
import { readdir, readFile } from 'node:fs/promises';
import { platform } from 'node:os';
import { join, resolve } from 'node:path';
import { kill } from 'node:process';
import log from '~/utils/log'
import log from '~/utils/log';
import { createIntegration } from './integration'
import { createIntegration } from './integration';
interface Context {
pid: number | undefined
pid: number | undefined;
}
export default createIntegration<Context>({
@@ -18,62 +18,64 @@ export default createIntegration<Context>({
},
isAvailable: async (context) => {
if (platform() !== 'linux') {
log.error('INTG', '/proc is only available on Linux')
return false
log.error('INTG', '/proc is only available on Linux');
return false;
}
log.debug('INTG', 'Checking /proc for Headscale process')
const dir = resolve('/proc')
log.debug('INTG', 'Checking /proc for Headscale process');
const dir = resolve('/proc');
try {
const subdirs = await readdir(dir)
const subdirs = await readdir(dir);
const promises = subdirs.map(async (dir) => {
const pid = Number.parseInt(dir, 10)
const pid = Number.parseInt(dir, 10);
if (Number.isNaN(pid)) {
return
return;
}
const path = join('/proc', dir, 'cmdline')
const path = join('/proc', dir, 'cmdline');
try {
log.debug('INTG', 'Reading %s', path)
const data = await readFile(path, 'utf8')
log.debug('INTG', 'Reading %s', path);
const data = await readFile(path, 'utf8');
if (data.includes('headscale')) {
return pid
return pid;
}
} catch (error) {
log.error('INTG', 'Failed to read %s: %s', path, error)
log.error('INTG', 'Failed to read %s: %s', path, error);
}
})
});
const results = await Promise.allSettled(promises)
const pids = []
const results = await Promise.allSettled(promises);
const pids = [];
for (const result of results) {
if (result.status === 'fulfilled' && result.value) {
pids.push(result.value)
pids.push(result.value);
}
}
log.debug('INTG', 'Found Headscale processes: %o', pids)
log.debug('INTG', 'Found Headscale processes: %o', pids);
if (pids.length > 1) {
log.error('INTG', 'Found %d Headscale processes: %s',
log.error(
'INTG',
'Found %d Headscale processes: %s',
pids.length,
pids.join(', '),
)
return false
);
return false;
}
if (pids.length === 0) {
log.error('INTG', 'Could not find Headscale process')
return false
log.error('INTG', 'Could not find Headscale process');
return false;
}
context.pid = pids[0]
log.info('INTG', 'Found Headscale process with PID: %d', context.pid)
return true
context.pid = pids[0];
log.info('INTG', 'Found Headscale process with PID: %d', context.pid);
return true;
} catch {
log.error('INTG', 'Failed to read /proc')
return false
log.error('INTG', 'Failed to read /proc');
return false;
}
}
})
},
});