Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions apps/agent/src/http/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import type { DaemonServerDetails, SystemInfo } from "@bytepanel/protocol";
import type { Config } from "../config";
import { COMMIT, VERSION } from "../config";
import type { Docker } from "../docker";
import { errorMessage, logger } from "../log";
import { errorMessage, logger, redactUrl, debugEnabled } from "../log";
import type { Backups } from "../server/backups";
import { FilesystemError } from "../server/filesystem";
import type { ServerManager } from "../server/manager";
Expand Down Expand Up @@ -280,8 +280,7 @@ export const createFetchHandler = (deps: Deps) => {
throw new HttpError(404, "route not found");
};

return async (req: Request, bun: BunServer<SocketData>): Promise<Response | undefined> => {
const url = new URL(req.url);
const handle = async (req: Request, url: URL, bun: BunServer<SocketData>): Promise<Response | undefined> => {
if (LONG_RUNNING.test(url.pathname)) {
bun.timeout(req, 0);
}
Expand Down Expand Up @@ -369,4 +368,17 @@ export const createFetchHandler = (deps: Deps) => {
return json({ error: errorMessage(error) }, status, cors(req));
}
};

return async (req: Request, bun: BunServer<SocketData>): Promise<Response | undefined> => {
const url = new URL(req.url);
if (!debugEnabled()) {
return handle(req, url, bun);
}
const started = performance.now();
const res = await handle(req, url, bun);
const ip = bun.requestIP(req)?.address ?? "unknown";
const ms = Math.round(performance.now() - started);
log.debug(`${req.method} ${redactUrl(url)} -> ${res?.status ?? 101} (${ms}ms) from ${ip}`);
return res;
};
};
13 changes: 10 additions & 3 deletions apps/agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Docker } from "./docker";
import { createFetchHandler } from "./http/router";
import type { SocketData } from "./http/websocket";
import { websocketHandlers } from "./http/websocket";
import { logger } from "./log";
import { logger, debugEnabled, enableDebug } from "./log";
import { ActivityBuffer, PanelClient } from "./panel";
import { Backups } from "./server/backups";
import { ServerManager } from "./server/manager";
Expand Down Expand Up @@ -38,10 +38,17 @@ const configure = async (args: string[]) => {
console.log(`Configuration for node ${saved.uuid} written to ${values.config}`);
};

const run = async () => {
const run = async (args: string[]) => {
const { values } = parseArgs({ args, options: { debug: { type: "boolean" } } });
if (values.debug) {
enableDebug();
}
const config = await loadConfig();
await ensureDirectories(config);
log.info(`BytePanel daemon v${VERSION} starting for node ${config.uuid}`);
if (debugEnabled()) {
log.warn("debug mode on: logging every API call (headers, bodies and tokens are never logged)");
}

const docker = new Docker(config.docker.socket);
const dockerVersion = await docker.version();
Expand Down Expand Up @@ -108,7 +115,7 @@ try {
break;
}
case "run": {
await run();
await run(rest);
break;
}
default: {
Expand Down
27 changes: 24 additions & 3 deletions apps/agent/src/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,18 @@ type Level = "debug" | "info" | "warn" | "error";

const LEVELS: Record<Level, number> = { debug: 10, error: 40, info: 20, warn: 30 };

const threshold =
LEVELS[(process.env.BYTEPANEL_LOG_LEVEL as Level | undefined) ?? "info"] ??
LEVELS.info;
const truthy = (value: string | undefined) => value === "1" || value?.toLowerCase() === "true";

let debug = truthy(process.env.BYTEPANEL_DEBUG);

let threshold = debug ? LEVELS.debug : (LEVELS[(process.env.BYTEPANEL_LOG_LEVEL as Level | undefined) ?? "info"] ?? LEVELS.info);

export const enableDebug = () => {
debug = true;
threshold = LEVELS.debug;
};

export const debugEnabled = () => debug;

const write = (level: Level, scope: string, message: string, extra?: unknown) => {
if (LEVELS[level] < threshold) {
Expand All @@ -28,3 +37,15 @@ export const logger = (scope: string) => ({

export const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : String(error);

const SENSITIVE_PARAM = /token|secret|password|key|signature|auth/iu;

export const redactUrl = (url: URL): string => {
if (url.search === "") {
return url.pathname;
}
const params = [...url.searchParams].map(([name, value]) =>
`${name}=${SENSITIVE_PARAM.test(name) ? "[redacted]" : value}`,
);
return `${url.pathname}?${params.join("&")}`;
};
14 changes: 11 additions & 3 deletions apps/agent/src/panel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type {
SftpAuthResponse,
} from "@bytepanel/protocol";
import type { Config } from "./config";
import { logger } from "./log";
import { logger, redactUrl, errorMessage } from "./log";

const log = logger("panel");

Expand All @@ -41,6 +41,9 @@ export class PanelClient {
const url = new URL(path, this.config.remote);
let lastError: unknown;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
const started = performance.now();
const tag = () =>
`${method} ${redactUrl(url)}${attempt > 1 ? ` (attempt ${attempt}/${attempts})` : ""}`;
try {
const res = await fetch(url, {
body: body === undefined ? undefined : JSON.stringify(body),
Expand All @@ -53,6 +56,7 @@ export class PanelClient {
method,
signal: AbortSignal.timeout(30_000),
});
log.debug(`${tag()} -> ${res.status} (${Math.round(performance.now() - started)}ms)`);
if (res.status === 204) {
return null;
}
Expand All @@ -70,8 +74,12 @@ export class PanelClient {
return text.length > 0 ? JSON.parse(text) : null;
}
} catch (error) {
if (error instanceof PanelError && error.status < 500) {
throw error;
if (error instanceof PanelError) {
if (error.status < 500) {
throw error;
}
} else {
log.debug(`${tag()} failed: ${errorMessage(error)}`);
}
lastError = error;
}
Expand Down