-
Notifications
You must be signed in to change notification settings - Fork 413
Cluster fixes #789
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
Open
jdmarshall
wants to merge
6
commits into
prometheus:main
Choose a base branch
from
jdmarshall:clusterFixes
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Cluster fixes #789
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8a6941a
Rework cluster and worker lifecycle logic to be more similar.
jdmarshall 0bd94ae
Fixing missing unref for BroadcastChannel.
jdmarshall 3c366f7
Export stats from the primary thread.
jdmarshall c0b8140
Rework state tracking to support bot #155 and #788
jdmarshall efa7691
fix(cluster): skip responses after IPC disconnect
alencristen 3bc15bb
Simplify process.send sanity checks.
jdmarshall 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 |
|---|---|---|
|
|
@@ -22,6 +22,7 @@ | |
| * cluster master. | ||
| */ | ||
|
|
||
| const { debuglog } = require('node:util'); | ||
| const Registry = require('./registry'); | ||
| // We need to lazy-load the 'cluster' module as some application servers - | ||
| // namely Passenger - crash when it is imported. | ||
|
|
@@ -31,17 +32,25 @@ let cluster = () => { | |
| return data; | ||
| }; | ||
|
|
||
| const debug = debuglog('prom:metrics:cluster'); | ||
| const ANNOUNCEMENT = '@prometheus/client:announcement'; | ||
| const GET_METRICS_REQ = '@prometheus/client:getMetricsReq'; | ||
| const GET_METRICS_RES = '@prometheus/client:getMetricsRes'; | ||
|
|
||
| let registries = [Registry.globalRegistry]; | ||
| let requestCtr = 0; // Concurrency control | ||
| let listenersAdded = false; | ||
| const requests = new Map(); // Pending requests for workers' local metrics. | ||
| const workers = new Map(); | ||
|
|
||
| class AggregatorRegistry extends Registry { | ||
| /** | ||
| * Create a Registry. | ||
| * @param regContentType | ||
| */ | ||
| constructor(regContentType = Registry.PROMETHEUS_CONTENT_TYPE) { | ||
| super(regContentType); | ||
|
|
||
| addListeners(); | ||
| } | ||
|
|
||
|
|
@@ -53,9 +62,9 @@ class AggregatorRegistry extends Registry { | |
| */ | ||
| clusterMetrics() { | ||
| const requestId = requestCtr++; | ||
| const workers = Object.values(cluster().workers) | ||
| .filter(worker => worker.isConnected()) | ||
| .sort((left, right) => left.id - right.id); | ||
| const orderedWorkers = [...workers.values()].sort( | ||
| (left, right) => left.id - right.id, | ||
| ); | ||
|
|
||
| return new Promise((resolve, reject) => { | ||
| let settled = false; | ||
|
|
@@ -78,37 +87,44 @@ class AggregatorRegistry extends Registry { | |
| responseHandlers, | ||
| done, | ||
| errorTimeout: setTimeout(() => { | ||
| const err = new Error('Operation timed out.'); | ||
| const err = new Error( | ||
| `Operation timed out. ${request.responseHandlers.size} outstanding responses.`, | ||
| ); | ||
| request.done(err); | ||
| }, 5000), | ||
| }, 5_000), | ||
| }; | ||
| requests.set(requestId, request); | ||
|
|
||
| const message = { | ||
| type: GET_METRICS_REQ, | ||
| requestId, | ||
| }; | ||
|
|
||
| if (workers.length === 0) { | ||
| // No workers were up | ||
| process.nextTick(() => done(undefined, '')); | ||
| return; | ||
| } | ||
|
|
||
| const responsePromises = workers.map( | ||
| const workerMetrics = orderedWorkers.map( | ||
| worker => | ||
| new Promise((resolveResponse, rejectResponse) => { | ||
| responseHandlers.set(worker.id, { | ||
| resolve: resolveResponse, | ||
| reject: rejectResponse, | ||
| }); | ||
| worker.send(message); | ||
|
|
||
| worker.send({ | ||
| type: GET_METRICS_REQ, | ||
| requestId, | ||
| }); | ||
| }), | ||
| ); | ||
|
|
||
| Promise.all(responsePromises) | ||
| .then(metrics => Registry.aggregate(metrics.flat()).metrics()) | ||
| .then(result => done(undefined, result), done); | ||
| const myMetrics = Promise.all( | ||
| registries.map(r => r.getMetricsAsJSON()), | ||
| ).then(metrics => { | ||
| return { metrics }; | ||
| }); | ||
|
|
||
| const allMetrics = [myMetrics, ...workerMetrics]; | ||
| if (allMetrics.length === 0) { | ||
| debug('No workers found for requestId', requestId); | ||
| process.nextTick(() => done(undefined, '')); | ||
| } else { | ||
| Promise.all(allMetrics) | ||
| .then(responses => responses.flatMap(response => response.metrics)) | ||
| .then(metrics => Registry.aggregate(metrics).metrics()) | ||
| .then(result => done(undefined, result), done); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
|
|
@@ -158,53 +174,108 @@ class AggregatorRegistry extends Registry { | |
| * @returns {void} | ||
| */ | ||
| function addListeners() { | ||
| if (listenersAdded) return; | ||
| if (listenersAdded) { | ||
| return; | ||
| } | ||
|
|
||
| listenersAdded = true; | ||
|
|
||
| if (cluster().isPrimary) { | ||
| // Listen for worker responses to requests for local metrics | ||
| cluster().on('message', (worker, message) => { | ||
| if (message.type === GET_METRICS_RES) { | ||
| const request = requests.get(message.requestId); | ||
| cluster().on('message', primaryListener); | ||
| cluster().on('disconnect', deadWorker => { | ||
| debug('worker disconnected', deadWorker.id); | ||
| workers.delete(deadWorker.id); | ||
| }); | ||
|
|
||
| if (request === undefined) { | ||
| return; | ||
| } | ||
| announce(); | ||
| } else { | ||
| process.on('message', workerListener); | ||
| process.send({ type: ANNOUNCEMENT }); | ||
| } | ||
| } | ||
|
|
||
| const response = request.responseHandlers.get(worker.id); | ||
| if (response === undefined) { | ||
| return; | ||
| } | ||
| request.responseHandlers.delete(worker.id); | ||
| /** | ||
| * Watch for metrics events and aggregator announcements | ||
| * | ||
| * Whereas clusters are a top-level activity, multiple modules may start their | ||
| * own workers and require telemetry collection. | ||
| * @param message {MessageEvent} | ||
| */ | ||
| async function workerListener(message) { | ||
| if (message.type === ANNOUNCEMENT) { | ||
| process.send({ type: ANNOUNCEMENT }); | ||
| } else if (message.type === GET_METRICS_REQ) { | ||
| const metrics = await Promise.all( | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What happens if await throws an exception, this is outside the |
||
| registries.map(r => r.getMetricsAsJSON()), | ||
| ); | ||
|
|
||
| if (message.error) { | ||
| response.reject(new Error(message.error)); | ||
| } else { | ||
| response.resolve(message.metrics); | ||
| } | ||
| } | ||
| }); | ||
| } else { | ||
| // Respond to master's requests for worker's local metrics. | ||
| process.on('message', message => { | ||
| if (message.type === GET_METRICS_REQ) { | ||
| Promise.all(registries.map(r => r.getMetricsAsJSON())) | ||
| .then(metrics => { | ||
| process.send({ | ||
| type: GET_METRICS_RES, | ||
| requestId: message.requestId, | ||
| metrics, | ||
| }); | ||
| }) | ||
| .catch(error => { | ||
| process.send({ | ||
| type: GET_METRICS_RES, | ||
| requestId: message.requestId, | ||
| error: error.message, | ||
| }); | ||
| }); | ||
| try { | ||
| process.send({ | ||
| type: GET_METRICS_RES, | ||
| requestId: message.requestId, | ||
| metrics, | ||
| }); | ||
| } catch (error) { | ||
| debug('Error sending to primary', error); | ||
| if (!process.connected) { | ||
| debug('Connection to primary lost.'); | ||
| } else { | ||
| process.send({ | ||
| type: GET_METRICS_RES, | ||
| requestId: message.requestId, | ||
| error: error.message, | ||
| }); | ||
| } | ||
| }); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Add workers to the aggregation list when they are announced. | ||
| * | ||
| * Whereas clusters are a top-level activity, multiple modules may start their | ||
| * own workers and require telemetry collection. | ||
| * @param event {MessageEvent} | ||
| */ | ||
|
|
||
| async function primaryListener(worker, event) { | ||
| if (event.type === ANNOUNCEMENT) { | ||
| if (workers.has(worker.id)) { | ||
| debug('duplicate worker announcement', worker.id); | ||
| return; | ||
| } | ||
|
|
||
| workers.set(worker.id, worker); | ||
| } else if (event.type === GET_METRICS_RES) { | ||
| const request = requests.get(event.requestId); | ||
|
|
||
| if (request === undefined) { | ||
| debug('unexpected results from worker', worker.id); | ||
| return; | ||
| } | ||
|
|
||
| const response = request.responseHandlers.get(worker.id); | ||
| if (response === undefined) { | ||
| return; | ||
| } | ||
| request.responseHandlers.delete(worker.id); | ||
|
|
||
| if (event.error) { | ||
| response.reject(new Error(event.error)); | ||
| } else { | ||
| response.resolve({ | ||
| threadId: worker.id, | ||
| metrics: event.metrics, | ||
| }); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| function announce() { | ||
| for (const worker of Object.values(cluster().workers)) { | ||
| if (worker.isConnected()) { | ||
| worker.send({ type: ANNOUNCEMENT }); | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The non-primary branch calls process.send unconditionally. With cluster.isPrimary === false but no IPC channel (NODE_UNIQUE_ID leaked into a grandchild — the case some process managers hit), this throws where main constructs fine:
PR: THREW: TypeError: process.send is not a function
main: OK: constructed without throwing
main never called send at construction time, so this is a new failure mode. Guard with typeof process.send === 'function' && process.connected.