Skip to content
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

feat(instrumentation-runtime-node): add prom-client-metrics #2136

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions plugins/node/instrumentation-runtime-node/README.md
Expand Up @@ -26,7 +26,7 @@ const prometheusExporter = new PrometheusExporter({
const sdk = new NodeSDK({
metricReader: prometheusExporter,
instrumentations: [new RuntimeNodeInstrumentation({
eventLoopUtilizationMeasurementInterval: 5000,
monitoringPrecision: 5000,
})],
});

Expand All @@ -44,7 +44,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 @@ -56,7 +56,7 @@ nodejs_performance_event_loop_utilization 0.010140079547955264

| 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 | `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. |

## Supported Node.js versions

Expand Down
2 changes: 1 addition & 1 deletion plugins/node/instrumentation-runtime-node/package.json
@@ -1,6 +1,6 @@
{
"name": "@opentelemetry/instrumentation-runtime-node",
"version": "0.3.0",
"version": "0.4.0",
"description": "OpenTelemetry Node.js Performance measurement API automatic instrumentation package",
"main": "build/src/index.js",
"types": "build/src/index.d.ts",
Expand Down
77 changes: 32 additions & 45 deletions plugins/node/instrumentation-runtime-node/src/instrumentation.ts
Expand Up @@ -13,83 +13,70 @@
* 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';

import { VERSION } from './version';
import { RuntimeNodeInstrumentationConfig } from './types';
import { MetricCollector } from './types/metricCollector';
import { EventLoopUtilizationCollector } from './metrics/eventLoopUtilizationCollector';
import { EventLoopLagCollector } from './metrics/eventLoopLagCollector';
import { GCCollector } from './metrics/gcCollector';
import { HeapSizeAndUsedCollector } from './metrics/heapSizeAndUsedCollector';
import { HeapSpacesSizeAndUsedCollector } from './metrics/heapSpacesSizeAndUsedCollector';

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

const namePrefix = 'nodejs';

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

constructor(config: RuntimeNodeInstrumentationConfig = {}) {
super(
'@opentelemetry/instrumentation-runtime-node',
VERSION,
Object.assign({}, DEFAULT_CONFIG, config)
);
}

private _addELU() {
this._ELUs.unshift(eventLoopUtilization());
if (this._ELUs.length > ELUS_LENGTH) {
this._ELUs.pop();
this._collectors = [
new EventLoopUtilizationCollector(this._config, namePrefix),
new EventLoopLagCollector(this._config, namePrefix),
new GCCollector(this._config, namePrefix),
new HeapSizeAndUsedCollector(this._config, namePrefix),
new HeapSpacesSizeAndUsedCollector(this._config, namePrefix),
];
if (this._config.enabled) {
for (const collector of this._collectors) {
collector.enable();
}
}
}

private _clearELU() {
if (!this._ELUs) {
this._ELUs = [];
}
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._config as RuntimeNodeInstrumentationConfig)
.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();
}
}
}
@@ -0,0 +1,73 @@
/*
* 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 { clearInterval } from 'node:timers';
import { RuntimeNodeInstrumentationConfig } from '../types';

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

protected namePrefix: string;
private _interval: NodeJS.Timeout | undefined;
protected _scrapeQueue: T[] = [];

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

public disable(): void {
this._clearQueue();
clearInterval(this._interval);
this._interval = undefined;

this.internalDisable();
}

public enable(): void {
this._clearQueue();
clearInterval(this._interval);
this._interval = setInterval(
() => this._addTask(),
this._config.monitoringPrecision
);

// unref so that it does not keep the process running if disable() is never called
this._interval?.unref();

this.internalEnable();
}

private _clearQueue() {
this._scrapeQueue.length = 0;
}

private _addTask() {
const taskResult = this.scrape();
if (taskResult) {
this._scrapeQueue.push(taskResult);
}
}

public abstract updateMetricInstruments(meter: Meter): void;
protected abstract internalEnable(): void;
protected abstract internalDisable(): void;
protected abstract scrape(): T;
}