-
Notifications
You must be signed in to change notification settings - Fork 1
feat(metrics): expose worker metrics over HTTP #547
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,97 +1,180 @@ | ||
| import * as client from 'prom-client'; | ||
| import os from 'os'; | ||
| import { nanoid } from 'nanoid'; | ||
| import * as http from 'http'; | ||
| import createLogger from './logger'; | ||
|
|
||
| const register = new client.Registry(); | ||
| const logger = createLogger(); | ||
|
|
||
| const DEFAULT_PUSH_INTERVAL_MS = 10_000; | ||
| const ID_SIZE = 5; | ||
| const METRICS_JOB_NAME = 'workers'; | ||
| const DEFAULT_METRICS_HOST = '0.0.0.0'; | ||
| const DEFAULT_METRICS_PATH = '/metrics'; | ||
| const MIN_PORT = 1; | ||
| const MAX_PORT = 65535; | ||
| const HTTP_OK = 200; | ||
| const HTTP_NOT_FOUND = 404; | ||
| const HTTP_INTERNAL_SERVER_ERROR = 500; | ||
|
|
||
| let pushInterval: NodeJS.Timeout | null = null; | ||
| let metricsServer: http.Server | null = null; | ||
| let currentWorkerName = ''; | ||
|
|
||
| client.collectDefaultMetrics({ register }); | ||
|
|
||
| export { register, client }; | ||
|
|
||
| /** | ||
| * Parse push interval from environment. | ||
| * Parse metrics endpoint port from environment. | ||
| */ | ||
| function getPushIntervalMs(): number { | ||
| const rawInterval = process.env.PROMETHEUS_PUSHGATEWAY_INTERVAL; | ||
| const parsedInterval = rawInterval === undefined | ||
| ? DEFAULT_PUSH_INTERVAL_MS | ||
| : Number(rawInterval); | ||
|
|
||
| const interval = Number.isFinite(parsedInterval) && parsedInterval > 0 | ||
| ? parsedInterval | ||
| : DEFAULT_PUSH_INTERVAL_MS; | ||
|
|
||
| if (rawInterval !== undefined && interval !== parsedInterval) { | ||
| logger.warn(`[metrics] invalid PROMETHEUS_PUSHGATEWAY_INTERVAL="${rawInterval}", fallback to ${DEFAULT_PUSH_INTERVAL_MS}ms`); | ||
| function getMetricsPort(): number | null { | ||
| const rawPort = process.env.PROMETHEUS_METRICS_PORT; | ||
|
|
||
| if (!rawPort) { | ||
| return null; | ||
| } | ||
|
|
||
| const port = Number(rawPort); | ||
|
|
||
| if (!Number.isInteger(port) || port < MIN_PORT || port > MAX_PORT) { | ||
| logger.warn(`[metrics] invalid PROMETHEUS_METRICS_PORT="${rawPort}"; expected an integer between ${MIN_PORT} and ${MAX_PORT}`); | ||
|
|
||
| return null; | ||
| } | ||
|
|
||
| return port; | ||
| } | ||
|
|
||
| /** | ||
| * Read metrics endpoint path from environment. | ||
| */ | ||
| function getMetricsPath(): string { | ||
| const rawPath = process.env.PROMETHEUS_METRICS_PATH; | ||
|
|
||
| if (!rawPath) { | ||
| return DEFAULT_METRICS_PATH; | ||
| } | ||
|
|
||
| const path = rawPath.trim(); | ||
|
|
||
| if (!path) { | ||
| logger.warn(`[metrics] invalid PROMETHEUS_METRICS_PATH="${rawPath}", fallback to ${DEFAULT_METRICS_PATH}`); | ||
|
|
||
| return DEFAULT_METRICS_PATH; | ||
| } | ||
|
|
||
| if (!path.startsWith('/')) { | ||
| const normalizedPath = `/${path}`; | ||
|
|
||
| logger.warn(`[metrics] normalized PROMETHEUS_METRICS_PATH from "${rawPath}" to "${normalizedPath}"`); | ||
|
|
||
| return normalizedPath; | ||
| } | ||
|
|
||
| return interval; | ||
| return path; | ||
| } | ||
|
|
||
| /** | ||
| * Stop periodic push to pushgateway. | ||
| * Stop HTTP metrics endpoint. | ||
| */ | ||
| export function stopMetricsPushing(): void { | ||
| if (!pushInterval) { | ||
| export function stopMetricsServer(): void { | ||
| if (!metricsServer) { | ||
| return; | ||
| } | ||
|
|
||
| clearInterval(pushInterval); | ||
| pushInterval = null; | ||
| logger.info(`[metrics] stopped pushing metrics for worker=${currentWorkerName}`); | ||
| currentWorkerName = ''; | ||
| const serverToStop = metricsServer; | ||
| const stoppedWorkerName = currentWorkerName; | ||
|
|
||
| if (!serverToStop.listening) { | ||
| logger.info(`[metrics] endpoint already stopped for worker=${stoppedWorkerName}`); | ||
|
|
||
| if (metricsServer === serverToStop) { | ||
| metricsServer = null; | ||
| currentWorkerName = ''; | ||
| } | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| serverToStop.close((error) => { | ||
| if (error) { | ||
| logger.error(`[metrics] failed to stop endpoint for worker=${stoppedWorkerName}: ${error.message}`); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| if (metricsServer === serverToStop) { | ||
| metricsServer = null; | ||
| currentWorkerName = ''; | ||
| } | ||
|
|
||
| logger.info(`[metrics] stopped endpoint for worker=${stoppedWorkerName}`); | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Start periodic push to pushgateway. | ||
| * Start HTTP metrics endpoint for scraper-based monitoring. | ||
| * | ||
| * @param workerName - name of the worker for grouping. | ||
| * @param workerName - name of the worker for default metric labels. | ||
| */ | ||
| export function startMetricsPushing(workerName: string): () => void { | ||
| const url = process.env.PROMETHEUS_PUSHGATEWAY_URL; | ||
| export function startMetricsServer(workerName: string): () => void { | ||
| const port = getMetricsPort(); | ||
|
|
||
| if (!url) { | ||
| return stopMetricsPushing; | ||
| if (!port) { | ||
| return stopMetricsServer; | ||
| } | ||
|
|
||
| if (pushInterval) { | ||
| logger.warn(`[metrics] pushing is already started for worker=${currentWorkerName}, skip duplicate start for worker=${workerName}`); | ||
| if (metricsServer) { | ||
| logger.warn(`[metrics] endpoint is already started for worker=${currentWorkerName}, skip duplicate start for worker=${workerName}`); | ||
|
|
||
| return stopMetricsPushing; | ||
| return stopMetricsServer; | ||
| } | ||
|
|
||
| const interval = getPushIntervalMs(); | ||
| const hostname = os.hostname(); | ||
| const id = nanoid(ID_SIZE); | ||
| const gateway = new client.Pushgateway(url, undefined, register); | ||
| const host = process.env.PROMETHEUS_METRICS_HOST || DEFAULT_METRICS_HOST; | ||
| const path = getMetricsPath(); | ||
|
|
||
| register.setDefaultLabels({ worker: workerName }); | ||
|
|
||
| const server = http.createServer(async (request, response) => { | ||
| const requestPath = request.url?.split('?')[0]; | ||
|
|
||
| if (requestPath === '/-/healthy') { | ||
| response.writeHead(HTTP_OK, { 'Content-Type': 'text/plain' }); | ||
| response.end('ok'); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| if (request.method !== 'GET' || requestPath !== path) { | ||
| response.writeHead(HTTP_NOT_FOUND, { 'Content-Type': 'text/plain' }); | ||
| response.end('not found'); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| try { | ||
| response.writeHead(HTTP_OK, { 'Content-Type': register.contentType }); | ||
| response.end(await register.metrics()); | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : String(error); | ||
|
|
||
| logger.error(`[metrics] failed to render metrics: ${message}`); | ||
| response.writeHead(HTTP_INTERNAL_SERVER_ERROR, { 'Content-Type': 'text/plain' }); | ||
| response.end('metrics error'); | ||
| } | ||
| }); | ||
|
|
||
| server.on('error', (error) => { | ||
| logger.error(`[metrics] endpoint error for worker=${workerName}: ${error.message}`); | ||
|
|
||
| if (metricsServer === server) { | ||
| metricsServer = null; | ||
| currentWorkerName = ''; | ||
| } | ||
| }); | ||
|
|
||
| metricsServer = server; | ||
| currentWorkerName = workerName; | ||
|
|
||
| logger.info(`Start pushing metrics to ${url} every ${interval}ms (host: ${hostname}, id: ${id}, worker: ${workerName})`); | ||
|
|
||
| pushInterval = setInterval(() => { | ||
| gateway.pushAdd({ | ||
| jobName: METRICS_JOB_NAME, | ||
| groupings: { | ||
| worker: workerName, | ||
| host: hostname, | ||
| id, | ||
| }, | ||
| }, (err) => { | ||
| if (err) { | ||
| logger.error(`Metrics push error: ${err.message || err}`); | ||
| } | ||
| }); | ||
| }, interval); | ||
|
|
||
| return stopMetricsPushing; | ||
| server.listen(port, host, () => { | ||
| logger.info(`[metrics] endpoint started for worker=${workerName} at http://${host}:${port}${path}`); | ||
| }); | ||
|
Kuchizu marked this conversation as resolved.
|
||
|
|
||
| return stopMetricsServer; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.