Skip to content

Commit

Permalink
feat(instrumentation-runtime-node)!: add prom-client-metrics (#2136)
Browse files Browse the repository at this point in the history
  • Loading branch information
pikalovArtemN authored Nov 5, 2024
1 parent 6234918 commit 80d0c74
Show file tree
Hide file tree
Showing 21 changed files with 2,291 additions and 134 deletions.
1,151 changes: 1,141 additions & 10 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions plugins/node/instrumentation-runtime-node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const prometheusExporter = new PrometheusExporter({
const sdk = new NodeSDK({
metricReader: prometheusExporter,
instrumentations: [new RuntimeNodeInstrumentation({
eventLoopUtilizationMeasurementInterval: 5000,
monitoringPrecision: 5000,
})],
});

Expand All @@ -50,7 +50,7 @@ Go to [`localhost:9464/metrics`](http://localhost:9464/metrics), and you should
nodejs_performance_event_loop_utilization 0.010140079547955264
```

> Metrics will only be exported after it has collected two ELU readings (at least approximately `RuntimeNodeInstrumentationConfig.eventLoopUtilizationMeasurementInterval` milliseconds after initialization). Otherwise, you may see:
> Metrics will only be exported after it has collected two ELU readings (at least approximately `RuntimeNodeInstrumentationConfig.monitoringPrecision` milliseconds after initialization). Otherwise, you may see:
>
> ```txt
> # no registered metrics
Expand All @@ -61,8 +61,8 @@ nodejs_performance_event_loop_utilization 0.010140079547955264
`RuntimeNodeInstrumentation`'s constructor accepts the following options:
| name | type | unit | default | description |
|---|---|---|---|---|
| [`eventLoopUtilizationMeasurementInterval`](./src/types.ts#L25) | `int` | millisecond | `5000` | The approximate number of milliseconds for which to calculate event loop utilization averages. A larger value will result in more accurate averages at the expense of less granular data. Should be set to below the scrape interval of your metrics collector to avoid duplicated data points. |
|---|---|---|---------|---|
| [`monitoringPrecision`](./src/types.ts#L25) | `int` | millisecond | `10` | The approximate number of milliseconds for which to calculate event loop utilization averages. A larger value will result in more accurate averages at the expense of less granular data. Should be set to below the scrape interval of your metrics collector to avoid duplicated data points. |
## Useful links
Expand Down
5 changes: 3 additions & 2 deletions plugins/node/instrumentation-runtime-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"author": "OpenTelemetry Authors",
"license": "Apache-2.0",
"engines": {
"node": ">=14.10.0"
"node": ">=17.4.0"
},
"keywords": [
"perf_hooks",
Expand All @@ -44,7 +44,8 @@
"@opentelemetry/api": "^1.3.0",
"@opentelemetry/sdk-metrics": "^1.20.0",
"@types/mocha": "^10.0.6",
"@types/node": "^20.11.2",
"@types/node": "18.18.14",
"mocha": "7.2.0",
"nyc": "^15.1.0",
"rimraf": "5.0.10",
"typescript": "4.4.4"
Expand Down
16 changes: 16 additions & 0 deletions plugins/node/instrumentation-runtime-node/src/consts/attributes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const ATTR_V8JS_HEAP_SPACE_NAME = 'heap.space.name';
36 changes: 36 additions & 0 deletions plugins/node/instrumentation-runtime-node/src/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Histogram } from 'perf_hooks';

declare module 'node:perf_hooks' {
interface IntervalHistogram extends Histogram {
/**
* Enables the update interval timer. Returns `true` if the timer was
* started, `false` if it was already started.
* @since v11.10.0
*/
enable(): boolean;

/**
* Disables the update interval timer. Returns `true` if the timer was
* stopped, `false` if it was already stopped.
* @since v11.10.0
*/
disable(): boolean;

count: number;
}
}
85 changes: 39 additions & 46 deletions plugins/node/instrumentation-runtime-node/src/instrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,83 +13,76 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { EventLoopUtilization, performance } from 'node:perf_hooks';
const { eventLoopUtilization } = performance;

import { InstrumentationBase } from '@opentelemetry/instrumentation';

/** @knipignore */
import { PACKAGE_NAME, PACKAGE_VERSION } from './version';
import { RuntimeNodeInstrumentationConfig } from './types';
import { MetricCollector } from './types/metricCollector';
import { EventLoopUtilizationCollector } from './metrics/eventLoopUtilizationCollector';
import { EventLoopDelayCollector } from './metrics/eventLoopDelayCollector';
import { GCCollector } from './metrics/gcCollector';
import { HeapSpacesSizeAndUsedCollector } from './metrics/heapSpacesSizeAndUsedCollector';
import { ConventionalNamePrefix } from './types/ConventionalNamePrefix';
import { EventLoopTimeCollector } from './metrics/eventLoopTimeCollector';
/** @knipignore */
import { PACKAGE_VERSION, PACKAGE_NAME } from './version';

const ELUS_LENGTH = 2;
const DEFAULT_CONFIG: RuntimeNodeInstrumentationConfig = {
eventLoopUtilizationMeasurementInterval: 5000,
monitoringPrecision: 10,
};

export class RuntimeNodeInstrumentation extends InstrumentationBase<RuntimeNodeInstrumentationConfig> {
private _ELUs: EventLoopUtilization[] = [];
private _interval: NodeJS.Timeout | undefined;
private readonly _collectors: MetricCollector[] = [];

constructor(config: RuntimeNodeInstrumentationConfig = {}) {
super(
PACKAGE_NAME,
PACKAGE_VERSION,
Object.assign({}, DEFAULT_CONFIG, config)
);
}

private _addELU() {
this._ELUs.unshift(eventLoopUtilization());
if (this._ELUs.length > ELUS_LENGTH) {
this._ELUs.pop();
}
}

private _clearELU() {
if (!this._ELUs) {
this._ELUs = [];
this._collectors = [
new EventLoopUtilizationCollector(
this._config,
ConventionalNamePrefix.NodeJs
),
new EventLoopTimeCollector(this._config, ConventionalNamePrefix.NodeJs),
new EventLoopDelayCollector(this._config, ConventionalNamePrefix.NodeJs),
new GCCollector(this._config, ConventionalNamePrefix.V8js),
new HeapSpacesSizeAndUsedCollector(
this._config,
ConventionalNamePrefix.V8js
),
];
if (this._config.enabled) {
for (const collector of this._collectors) {
collector.enable();
}
}
this._ELUs.length = 0;
}

// Called when a new `MeterProvider` is set
// the Meter (result of @opentelemetry/api's getMeter) is available as this.meter within this method
override _updateMetricInstruments() {
this.meter
.createObservableGauge('nodejs.event_loop.utilization', {
description: 'Event loop utilization',
unit: '1',
})
.addCallback(async observableResult => {
if (this._ELUs.length !== ELUS_LENGTH) {
return;
}
const elu = eventLoopUtilization(...this._ELUs);
observableResult.observe(elu.utilization);
});
if (!this._collectors) return;
for (const collector of this._collectors) {
collector.updateMetricInstruments(this.meter);
}
}

init() {
// Not instrumenting or patching a Node.js module
}

override enable() {
this._clearELU();
this._addELU();
clearInterval(this._interval);
this._interval = setInterval(
() => this._addELU(),
this.getConfig().eventLoopUtilizationMeasurementInterval
);
if (!this._collectors) return;

// unref so that it does not keep the process running if disable() is never called
this._interval?.unref();
for (const collector of this._collectors) {
collector.enable();
}
}

override disable() {
this._clearELU();
clearInterval(this._interval);
this._interval = undefined;
for (const collector of this._collectors) {
collector.disable();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { MetricCollector } from '../types/metricCollector';
import { Meter } from '@opentelemetry/api';
import { RuntimeNodeInstrumentationConfig } from '../types';

export abstract class BaseCollector implements MetricCollector {
protected _config: RuntimeNodeInstrumentationConfig = {};

protected namePrefix: string;

protected constructor(
config: RuntimeNodeInstrumentationConfig = {},
namePrefix: string
) {
this._config = config;
this.namePrefix = namePrefix;
}

public disable(): void {
this._config.enabled = false;
this.internalDisable();
}

public enable(): void {
this._config.enabled = true;
this.internalEnable();
}

public abstract updateMetricInstruments(meter: Meter): void;

protected abstract internalEnable(): void;

protected abstract internalDisable(): void;
}
Loading

0 comments on commit 80d0c74

Please sign in to comment.