diff --git a/package-lock.json b/package-lock.json index 4ac44d4efe..dba5b500b2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38197,7 +38197,7 @@ "@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", @@ -38205,7 +38205,7 @@ "typescript": "4.4.4" }, "engines": { - "node": ">=14.10.0" + "node": ">=17.4.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" @@ -38218,10 +38218,11 @@ "dev": true }, "plugins/node/instrumentation-runtime-node/node_modules/@types/node": { - "version": "20.11.20", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.20.tgz", - "integrity": "sha512-7/rR21OS+fq8IyHTgtLkDK949uzsa6n8BkziAKtPVpugIkO6D+/ooXMvzXxDnZrmtXVfjb1bKQafYpb8s89LOg==", + "version": "18.18.14", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.18.14.tgz", + "integrity": "sha512-iSOeNeXYNYNLLOMDSVPvIFojclvMZ/HDY2dU17kUlcsOsSQETbWIslJbYLZgA+ox8g2XQwSHKTkght1a5X26lQ==", "dev": true, + "license": "MIT", "dependencies": { "undici-types": "~5.26.4" } @@ -52929,7 +52930,7 @@ "@opentelemetry/instrumentation": "^0.53.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", @@ -52944,9 +52945,9 @@ "dev": true }, "@types/node": { - "version": "20.11.20", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.20.tgz", - "integrity": "sha512-7/rR21OS+fq8IyHTgtLkDK949uzsa6n8BkziAKtPVpugIkO6D+/ooXMvzXxDnZrmtXVfjb1bKQafYpb8s89LOg==", + "version": "18.18.14", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.18.14.tgz", + "integrity": "sha512-iSOeNeXYNYNLLOMDSVPvIFojclvMZ/HDY2dU17kUlcsOsSQETbWIslJbYLZgA+ox8g2XQwSHKTkght1a5X26lQ==", "dev": true, "requires": { "undici-types": "~5.26.4" diff --git a/plugins/node/instrumentation-runtime-node/README.md b/plugins/node/instrumentation-runtime-node/README.md index d3f1160db9..e1dd4844c9 100644 --- a/plugins/node/instrumentation-runtime-node/README.md +++ b/plugins/node/instrumentation-runtime-node/README.md @@ -32,7 +32,7 @@ const prometheusExporter = new PrometheusExporter({ const sdk = new NodeSDK({ metricReader: prometheusExporter, instrumentations: [new RuntimeNodeInstrumentation({ - eventLoopUtilizationMeasurementInterval: 5000, + monitoringPrecision: 5000, })], }); @@ -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 @@ -62,7 +62,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. | ## Useful links diff --git a/plugins/node/instrumentation-runtime-node/package.json b/plugins/node/instrumentation-runtime-node/package.json index 703628d776..55f1553a53 100644 --- a/plugins/node/instrumentation-runtime-node/package.json +++ b/plugins/node/instrumentation-runtime-node/package.json @@ -20,7 +20,7 @@ "author": "OpenTelemetry Authors", "license": "Apache-2.0", "engines": { - "node": ">=14.10.0" + "node": ">=17.4.0" }, "keywords": [ "perf_hooks", @@ -45,7 +45,7 @@ "@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", diff --git a/plugins/node/instrumentation-runtime-node/src/consts/attributes.ts b/plugins/node/instrumentation-runtime-node/src/consts/attributes.ts new file mode 100644 index 0000000000..b399ce99a6 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/src/consts/attributes.ts @@ -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 V8_HEAP_SIZE_NAME_ATTRIBUTE = 'heap.space.name'; diff --git a/plugins/node/instrumentation-runtime-node/src/global.d.ts b/plugins/node/instrumentation-runtime-node/src/global.d.ts new file mode 100644 index 0000000000..a3affb3ff2 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/src/global.d.ts @@ -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; + } +} diff --git a/plugins/node/instrumentation-runtime-node/src/instrumentation.ts b/plugins/node/instrumentation-runtime-node/src/instrumentation.ts index 3e80ae4280..c5e58f9c69 100644 --- a/plugins/node/instrumentation-runtime-node/src/instrumentation.ts +++ b/plugins/node/instrumentation-runtime-node/src/instrumentation.ts @@ -13,22 +13,24 @@ * 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 { 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'; +import { PACKAGE_VERSION, PACKAGE_NAME } from './version'; -const ELUS_LENGTH = 2; const DEFAULT_CONFIG: RuntimeNodeInstrumentationConfig = { - eventLoopUtilizationMeasurementInterval: 5000, + monitoringPrecision: 10, }; export class RuntimeNodeInstrumentation extends InstrumentationBase { - private _ELUs: EventLoopUtilization[] = []; - private _interval: NodeJS.Timeout | undefined; + private readonly _collectors: MetricCollector[] = []; constructor(config: RuntimeNodeInstrumentationConfig = {}) { super( @@ -36,37 +38,33 @@ export class RuntimeNodeInstrumentation extends InstrumentationBase 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() { @@ -74,21 +72,16 @@ export class RuntimeNodeInstrumentation extends InstrumentationBase 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(); + } } } diff --git a/plugins/node/instrumentation-runtime-node/src/metrics/baseCollector.ts b/plugins/node/instrumentation-runtime-node/src/metrics/baseCollector.ts new file mode 100644 index 0000000000..60147d3b75 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/src/metrics/baseCollector.ts @@ -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; +} diff --git a/plugins/node/instrumentation-runtime-node/src/metrics/eventLoopDelayCollector.ts b/plugins/node/instrumentation-runtime-node/src/metrics/eventLoopDelayCollector.ts new file mode 100644 index 0000000000..cd9a6d31b2 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/src/metrics/eventLoopDelayCollector.ts @@ -0,0 +1,178 @@ +/* + * 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 { RuntimeNodeInstrumentationConfig } from '../types'; +import { Meter } from '@opentelemetry/api'; +import * as perf_hooks from 'node:perf_hooks'; +import { IntervalHistogram } from 'node:perf_hooks'; +import { BaseCollector } from './baseCollector'; + +enum NodeJsEventLoopDelay { + min = 'eventloop.delay.min', + max = 'eventloop.delay.max', + mean = 'eventloop.delay.mean', + stddev = 'eventloop.delay.stddev', + p50 = 'eventloop.delay.p50', + p90 = 'eventloop.delay.p90', + p99 = 'eventloop.delay.p99', +} + +export const metricNames: Record< + NodeJsEventLoopDelay, + { description: string } +> = { + [NodeJsEventLoopDelay.min]: { + description: 'Event loop minimum delay.', + }, + [NodeJsEventLoopDelay.max]: { + description: 'Event loop maximum delay.', + }, + [NodeJsEventLoopDelay.mean]: { + description: 'Event loop mean delay.', + }, + [NodeJsEventLoopDelay.stddev]: { + description: 'Event loop standard deviation delay.', + }, + [NodeJsEventLoopDelay.p50]: { + description: 'Event loop 50 percentile delay.', + }, + [NodeJsEventLoopDelay.p90]: { + description: 'Event loop 90 percentile delay.', + }, + [NodeJsEventLoopDelay.p99]: { + description: 'Event loop 99 percentile delay.', + }, +}; + +export interface EventLoopLagInformation { + min: number; + max: number; + mean: number; + stddev: number; + p50: number; + p90: number; + p99: number; +} + +export class EventLoopDelayCollector extends BaseCollector { + private _histogram: IntervalHistogram; + + constructor( + config: RuntimeNodeInstrumentationConfig = {}, + namePrefix: string + ) { + super(config, namePrefix); + this._histogram = perf_hooks.monitorEventLoopDelay({ + resolution: config.monitoringPrecision, + }); + } + + updateMetricInstruments(meter: Meter): void { + const delayMin = meter.createObservableGauge( + `${this.namePrefix}.${NodeJsEventLoopDelay.min}`, + { + description: metricNames[NodeJsEventLoopDelay.min].description, + unit: 's', + } + ); + const delayMax = meter.createObservableGauge( + `${this.namePrefix}.${NodeJsEventLoopDelay.max}`, + { + description: metricNames[NodeJsEventLoopDelay.max].description, + unit: 's', + } + ); + const delayMean = meter.createObservableGauge( + `${this.namePrefix}.${NodeJsEventLoopDelay.mean}`, + { + description: metricNames[NodeJsEventLoopDelay.mean].description, + unit: 's', + } + ); + const delayStddev = meter.createObservableGauge( + `${this.namePrefix}.${NodeJsEventLoopDelay.stddev}`, + { + description: metricNames[NodeJsEventLoopDelay.stddev].description, + unit: 's', + } + ); + const delayp50 = meter.createObservableGauge( + `${this.namePrefix}.${NodeJsEventLoopDelay.p50}`, + { + description: metricNames[NodeJsEventLoopDelay.p50].description, + unit: 's', + } + ); + const delayp90 = meter.createObservableGauge( + `${this.namePrefix}.${NodeJsEventLoopDelay.p90}`, + { + description: metricNames[NodeJsEventLoopDelay.p90].description, + unit: 's', + } + ); + const delayp99 = meter.createObservableGauge( + `${this.namePrefix}.${NodeJsEventLoopDelay.p99}`, + { + description: metricNames[NodeJsEventLoopDelay.p99].description, + unit: 's', + } + ); + + meter.addBatchObservableCallback( + async observableResult => { + if (!this._config.enabled) return; + + const data = this.scrape(); + if (data === undefined) return; + if (this._histogram.count < 5) return; // Don't return histogram data if we have less than 5 samples + + observableResult.observe(delayMin, data.min); + observableResult.observe(delayMax, data.max); + observableResult.observe(delayMean, data.mean); + observableResult.observe(delayStddev, data.stddev); + observableResult.observe(delayp50, data.p50); + observableResult.observe(delayp90, data.p90); + observableResult.observe(delayp99, data.p99); + + this._histogram.reset(); + }, + [delayMin, delayMax, delayMean, delayStddev, delayp50, delayp90, delayp99] + ); + } + + internalEnable(): void { + this._histogram.enable(); + } + + internalDisable(): void { + this._histogram.disable(); + } + + private scrape(): EventLoopLagInformation { + return { + min: this.checkNan(this._histogram.min / 1e9), + max: this.checkNan(this._histogram.max / 1e9), + mean: this.checkNan(this._histogram.mean / 1e9), + stddev: this.checkNan(this._histogram.stddev / 1e9), + p50: this.checkNan(this._histogram.percentile(50) / 1e9), + p90: this.checkNan(this._histogram.percentile(90) / 1e9), + p99: this.checkNan(this._histogram.percentile(99) / 1e9), + }; + } + + private checkNan(value: number) { + return isNaN(value) ? 0 : value; + } +} diff --git a/plugins/node/instrumentation-runtime-node/src/metrics/eventLoopTimeCollector.ts b/plugins/node/instrumentation-runtime-node/src/metrics/eventLoopTimeCollector.ts new file mode 100644 index 0000000000..f31bd6280c --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/src/metrics/eventLoopTimeCollector.ts @@ -0,0 +1,68 @@ +/* + * 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 { EventLoopUtilization, performance } from 'node:perf_hooks'; +import { RuntimeNodeInstrumentationConfig } from '../types'; +import { Meter } from '@opentelemetry/api'; +import { BaseCollector } from './baseCollector'; + +const { eventLoopUtilization: eventLoopUtilizationCollector } = performance; + +export const NODEJS_EVENT_LOOP_TIME = 'eventloop.time'; + +export class EventLoopTimeCollector extends BaseCollector { + constructor( + config: RuntimeNodeInstrumentationConfig = {}, + namePrefix: string + ) { + super(config, namePrefix); + } + + public updateMetricInstruments(meter: Meter): void { + const timeCounter = meter.createObservableCounter( + `${this.namePrefix}.${NODEJS_EVENT_LOOP_TIME}`, + { + description: + 'Cumulative duration of time the event loop has been in each state.', + unit: 's', + } + ); + + meter.addBatchObservableCallback( + async observableResult => { + if (!this._config.enabled) return; + + const data = this.scrape(); + if (data === undefined) return; + + observableResult.observe(timeCounter, data.active / 1000, { + [`${this.namePrefix}.eventloop.state`]: 'active', + }); + observableResult.observe(timeCounter, data.idle / 1000, { + [`${this.namePrefix}.eventloop.state`]: 'idle', + }); + }, + [timeCounter] + ); + } + + protected internalDisable(): void {} + + protected internalEnable(): void {} + + private scrape(): EventLoopUtilization { + return eventLoopUtilizationCollector(); + } +} diff --git a/plugins/node/instrumentation-runtime-node/src/metrics/eventLoopUtilizationCollector.ts b/plugins/node/instrumentation-runtime-node/src/metrics/eventLoopUtilizationCollector.ts new file mode 100644 index 0000000000..4ee7b337f6 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/src/metrics/eventLoopUtilizationCollector.ts @@ -0,0 +1,56 @@ +/* + * 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 { EventLoopUtilization, performance } from 'node:perf_hooks'; +import { RuntimeNodeInstrumentationConfig } from '../types'; +import { Meter } from '@opentelemetry/api'; +import { BaseCollector } from './baseCollector'; + +const { eventLoopUtilization: eventLoopUtilizationCollector } = performance; + +export const NODEJS_EVENT_LOOP_UTILIZATION = 'eventloop.utilization'; + +export class EventLoopUtilizationCollector extends BaseCollector { + private _lastValue?: EventLoopUtilization; + + constructor( + config: RuntimeNodeInstrumentationConfig = {}, + namePrefix: string + ) { + super(config, namePrefix); + } + + public updateMetricInstruments(meter: Meter): void { + meter + .createObservableGauge( + `${this.namePrefix}.${NODEJS_EVENT_LOOP_UTILIZATION}`, + { + description: 'Event loop utilization', + unit: 's', + } + ) + .addCallback(async observableResult => { + if (!this._config.enabled) return; + + const elu = eventLoopUtilizationCollector(this._lastValue); + observableResult.observe(elu.utilization); + this._lastValue = elu; + }); + } + + protected internalDisable(): void {} + + protected internalEnable(): void {} +} diff --git a/plugins/node/instrumentation-runtime-node/src/metrics/gcCollector.ts b/plugins/node/instrumentation-runtime-node/src/metrics/gcCollector.ts new file mode 100644 index 0000000000..60e38b20ac --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/src/metrics/gcCollector.ts @@ -0,0 +1,80 @@ +/* + * 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 { RuntimeNodeInstrumentationConfig } from '../types'; +import { Meter } from '@opentelemetry/api'; +import { Histogram, ValueType } from '@opentelemetry/api'; +import { BaseCollector } from './baseCollector'; +import * as perf_hooks from 'node:perf_hooks'; +import { PerformanceObserver } from 'node:perf_hooks'; + +const NODEJS_GC_DURATION_SECONDS = 'gc.duration'; +const DEFAULT_GC_DURATION_BUCKETS = [0.01, 0.1, 1, 10]; + +const kinds: string[] = []; +kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR] = 'major'; +kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR] = 'minor'; +kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL] = 'incremental'; +kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB] = 'weakcb'; + +export class GCCollector extends BaseCollector { + private _gcDurationByKindHistogram?: Histogram; + private _observer: PerformanceObserver; + + constructor( + config: RuntimeNodeInstrumentationConfig = {}, + namePrefix: string + ) { + super(config, namePrefix); + this._observer = new perf_hooks.PerformanceObserver(list => { + if (!this._config.enabled) return; + + const entry = list.getEntries()[0]; + // Node < 16 uses entry.kind + // Node >= 16 uses entry.detail.kind + // See: https://nodejs.org/docs/latest-v16.x/api/deprecations.html#deprecations_dep0152_extension_performanceentry_properties + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const kind = entry.detail ? kinds[entry.detail.kind] : kinds[entry.kind]; + this._gcDurationByKindHistogram?.record( + entry.duration / 1000, + Object.assign({ [`${this.namePrefix}.gc.type`]: kind }) + ); + }); + } + + updateMetricInstruments(meter: Meter): void { + this._gcDurationByKindHistogram = meter.createHistogram( + `${this.namePrefix}.${NODEJS_GC_DURATION_SECONDS}`, + { + description: + 'Garbage collection duration by kind, one of major, minor, incremental or weakcb.', + unit: 's', + valueType: ValueType.DOUBLE, + advice: { + explicitBucketBoundaries: DEFAULT_GC_DURATION_BUCKETS, + }, + } + ); + } + + internalEnable(): void { + this._observer.observe({ entryTypes: ['gc'] }); + } + + internalDisable(): void { + this._observer.disconnect(); + } +} diff --git a/plugins/node/instrumentation-runtime-node/src/metrics/heapSpacesSizeAndUsedCollector.ts b/plugins/node/instrumentation-runtime-node/src/metrics/heapSpacesSizeAndUsedCollector.ts new file mode 100644 index 0000000000..e81c63a34f --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/src/metrics/heapSpacesSizeAndUsedCollector.ts @@ -0,0 +1,130 @@ +/* + * 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 { RuntimeNodeInstrumentationConfig } from '../types'; +import { Meter } from '@opentelemetry/api'; +import { BaseCollector } from './baseCollector'; +import * as v8 from 'node:v8'; +import { HeapSpaceInfo } from 'v8'; +import { V8_HEAP_SIZE_NAME_ATTRIBUTE } from '../consts/attributes'; + +export enum V8HeapSpaceMetrics { + heapLimit = 'memory.heap.limit', + used = 'memory.heap.used', + available = 'memory.heap.space.available_size', + physical = 'memory.heap.space.physical_size', +} + +export const metricNames: Record = + { + [V8HeapSpaceMetrics.heapLimit]: { + description: 'Total heap memory size pre-allocated.', + }, + [V8HeapSpaceMetrics.used]: { + description: 'Heap Memory size allocated.', + }, + [V8HeapSpaceMetrics.available]: { + description: 'Heap space available size.', + }, + [V8HeapSpaceMetrics.physical]: { + description: 'Committed size of a heap space.', + }, + }; + +export class HeapSpacesSizeAndUsedCollector extends BaseCollector { + constructor( + config: RuntimeNodeInstrumentationConfig = {}, + namePrefix: string + ) { + super(config, namePrefix); + } + + updateMetricInstruments(meter: Meter): void { + const heapLimit = meter.createObservableGauge( + `${this.namePrefix}.${V8HeapSpaceMetrics.heapLimit}`, + { + description: metricNames[V8HeapSpaceMetrics.heapLimit].description, + unit: 'By', + } + ); + const heapSpaceUsed = meter.createObservableGauge( + `${this.namePrefix}.${V8HeapSpaceMetrics.used}`, + { + description: metricNames[V8HeapSpaceMetrics.used].description, + unit: 'By', + } + ); + const heapSpaceAvailable = meter.createObservableGauge( + `${this.namePrefix}.${V8HeapSpaceMetrics.available}`, + { + description: metricNames[V8HeapSpaceMetrics.available].description, + unit: 'By', + } + ); + const heapSpacePhysical = meter.createObservableGauge( + `${this.namePrefix}.${V8HeapSpaceMetrics.physical}`, + { + description: metricNames[V8HeapSpaceMetrics.physical].description, + unit: 'By', + } + ); + const heapSpaceNameAttributeName = `${this.namePrefix}.${V8_HEAP_SIZE_NAME_ATTRIBUTE}`; + + meter.addBatchObservableCallback( + observableResult => { + if (!this._config.enabled) return; + + const data = this.scrape(); + if (data === undefined) return; + for (const space of data) { + const spaceName = space.space_name; + + observableResult.observe(heapLimit, space.space_size, { + [heapSpaceNameAttributeName]: spaceName, + }); + + observableResult.observe(heapSpaceUsed, space.space_used_size, { + [heapSpaceNameAttributeName]: spaceName, + }); + + observableResult.observe( + heapSpaceAvailable, + space.space_available_size, + { + [heapSpaceNameAttributeName]: spaceName, + } + ); + + observableResult.observe( + heapSpacePhysical, + space.physical_space_size, + { + [heapSpaceNameAttributeName]: spaceName, + } + ); + } + }, + [heapLimit, heapSpaceUsed, heapSpaceAvailable, heapSpacePhysical] + ); + } + + internalEnable(): void {} + + internalDisable(): void {} + + private scrape(): HeapSpaceInfo[] { + return v8.getHeapSpaceStatistics(); + } +} diff --git a/plugins/node/instrumentation-runtime-node/src/types.ts b/plugins/node/instrumentation-runtime-node/src/types.ts index af0c5b12ef..68227c98f2 100644 --- a/plugins/node/instrumentation-runtime-node/src/types.ts +++ b/plugins/node/instrumentation-runtime-node/src/types.ts @@ -17,11 +17,5 @@ import type { InstrumentationConfig } from '@opentelemetry/instrumentation'; export interface RuntimeNodeInstrumentationConfig extends InstrumentationConfig { - /** - * 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. - * @default 5000 - */ - eventLoopUtilizationMeasurementInterval?: number; + monitoringPrecision?: number; } diff --git a/plugins/node/instrumentation-runtime-node/src/types/ConventionalNamePrefix.ts b/plugins/node/instrumentation-runtime-node/src/types/ConventionalNamePrefix.ts new file mode 100644 index 0000000000..6b17a6e00d --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/src/types/ConventionalNamePrefix.ts @@ -0,0 +1,19 @@ +/* + * 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 enum ConventionalNamePrefix { + NodeJs = 'nodejs', + V8js = 'v8js', +} diff --git a/plugins/node/instrumentation-runtime-node/src/types/heapSizes.ts b/plugins/node/instrumentation-runtime-node/src/types/heapSizes.ts new file mode 100644 index 0000000000..59cd766294 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/src/types/heapSizes.ts @@ -0,0 +1,19 @@ +/* + * 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 enum HeapSizes { + Total = 'total', + Used = 'used', +} diff --git a/plugins/node/instrumentation-runtime-node/src/types/metricCollector.ts b/plugins/node/instrumentation-runtime-node/src/types/metricCollector.ts new file mode 100644 index 0000000000..bfb7eda171 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/src/types/metricCollector.ts @@ -0,0 +1,24 @@ +/* + * 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 { Meter } from '@opentelemetry/api'; + +export interface MetricCollector { + updateMetricInstruments(meter: Meter): void; + + enable(): void; + + disable(): void; +} diff --git a/plugins/node/instrumentation-runtime-node/test/event_loop_delay.test.ts b/plugins/node/instrumentation-runtime-node/test/event_loop_delay.test.ts new file mode 100644 index 0000000000..9571ff23c6 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/test/event_loop_delay.test.ts @@ -0,0 +1,77 @@ +/* + * 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 { MeterProvider, DataPointType } from '@opentelemetry/sdk-metrics'; + +import { RuntimeNodeInstrumentation } from '../src'; +import * as assert from 'assert'; +import { TestMetricReader } from './testMetricsReader'; +import { metricNames } from '../src/metrics/eventLoopDelayCollector'; +import { ConventionalNamePrefix } from '../src/types/ConventionalNamePrefix'; + +describe(`${ConventionalNamePrefix.NodeJs}.eventloop`, function () { + let metricReader: TestMetricReader; + let meterProvider: MeterProvider; + + beforeEach(() => { + metricReader = new TestMetricReader(); + meterProvider = new MeterProvider(); + meterProvider.addMetricReader(metricReader); + }); + + for (const metricName in metricNames) { + it(`should write ${ConventionalNamePrefix.NodeJs}.${metricName} after monitoringPrecision`, async function () { + // arrange + const instrumentation = new RuntimeNodeInstrumentation({ + monitoringPrecision: 10, + }); + instrumentation.setMeterProvider(meterProvider); + + // act + await new Promise(resolve => setTimeout(resolve, 100)); + const { resourceMetrics, errors } = await metricReader.collect(); + + // assert + assert.deepEqual( + errors, + [], + 'expected no errors from the callback during collection' + ); + const scopeMetrics = resourceMetrics.scopeMetrics; + const metric = scopeMetrics[0].metrics.find( + x => + x.descriptor.name === `${ConventionalNamePrefix.NodeJs}.${metricName}` + ); + + assert.notEqual( + metric, + undefined, + `${ConventionalNamePrefix.NodeJs}.${metricName} not found` + ); + + assert.strictEqual( + metric!.dataPointType, + DataPointType.GAUGE, + 'expected gauge' + ); + + assert.strictEqual( + metric!.descriptor.name, + `${ConventionalNamePrefix.NodeJs}.${metricName}`, + 'descriptor.name' + ); + }); + } +}); diff --git a/plugins/node/instrumentation-runtime-node/test/event_loop_time.test.ts b/plugins/node/instrumentation-runtime-node/test/event_loop_time.test.ts new file mode 100644 index 0000000000..ce18f432c6 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/test/event_loop_time.test.ts @@ -0,0 +1,97 @@ +/* + * 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 { MeterProvider } from '@opentelemetry/sdk-metrics'; + +import { RuntimeNodeInstrumentation } from '../src'; +import * as assert from 'assert'; +import { TestMetricReader } from './testMetricsReader'; +import { ConventionalNamePrefix } from '../src/types/ConventionalNamePrefix'; +import { NODEJS_EVENT_LOOP_TIME } from '../src/metrics/eventLoopTimeCollector'; + +const MEASUREMENT_INTERVAL = 10; + +describe(`${ConventionalNamePrefix.NodeJs}.${NODEJS_EVENT_LOOP_TIME}`, function () { + let metricReader: TestMetricReader; + let meterProvider: MeterProvider; + + beforeEach(() => { + metricReader = new TestMetricReader(); + meterProvider = new MeterProvider(); + meterProvider.addMetricReader(metricReader); + }); + + it('should not export before being enabled', async function () { + // arrange + const instrumentation = new RuntimeNodeInstrumentation({ + monitoringPrecision: MEASUREMENT_INTERVAL, + enabled: false, + }); + instrumentation.setMeterProvider(meterProvider); + + // act + await new Promise(resolve => setTimeout(resolve, MEASUREMENT_INTERVAL * 5)); + const { resourceMetrics, errors } = await metricReader.collect(); + + // assert + assert.deepEqual(errors, []); + const scopeMetrics = resourceMetrics.scopeMetrics; + assert.strictEqual(scopeMetrics.length, 0); + }); + + it(`should write ${ConventionalNamePrefix.NodeJs}.${NODEJS_EVENT_LOOP_TIME}`, async function () { + // arrange + const instrumentation = new RuntimeNodeInstrumentation({ + monitoringPrecision: MEASUREMENT_INTERVAL, + }); + instrumentation.setMeterProvider(meterProvider); + + // act + await new Promise(resolve => setTimeout(resolve, MEASUREMENT_INTERVAL * 5)); + const { resourceMetrics, errors } = await metricReader.collect(); + + // assert + assert.deepEqual( + errors, + [], + 'expected no errors from the callback during collection' + ); + const scopeMetrics = resourceMetrics.scopeMetrics; + const timeMetric = scopeMetrics[0].metrics.find( + x => + x.descriptor.name === + `${ConventionalNamePrefix.NodeJs}.${NODEJS_EVENT_LOOP_TIME}` + ); + + assert.notEqual(timeMetric, undefined, 'metric not found'); + + assert.strictEqual( + timeMetric!.descriptor.name, + `${ConventionalNamePrefix.NodeJs}.${NODEJS_EVENT_LOOP_TIME}`, + 'descriptor.name' + ); + + assert.strictEqual( + timeMetric!.descriptor.description, + 'Cumulative duration of time the event loop has been in each state.' + ); + + assert.strictEqual( + timeMetric!.descriptor.unit, + 's', + 'expected default unit' + ); + }); +}); diff --git a/plugins/node/instrumentation-runtime-node/test/event_loop_utilization.test.ts b/plugins/node/instrumentation-runtime-node/test/event_loop_utilization.test.ts index ccc3a04ff7..cb9c7a04c2 100644 --- a/plugins/node/instrumentation-runtime-node/test/event_loop_utilization.test.ts +++ b/plugins/node/instrumentation-runtime-node/test/event_loop_utilization.test.ts @@ -13,28 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { - MeterProvider, - DataPointType, - MetricReader, -} from '@opentelemetry/sdk-metrics'; +import { MeterProvider } from '@opentelemetry/sdk-metrics'; import { RuntimeNodeInstrumentation } from '../src'; import * as assert from 'assert'; +import { TestMetricReader } from './testMetricsReader'; +import { ConventionalNamePrefix } from '../src/types/ConventionalNamePrefix'; +import { NODEJS_EVENT_LOOP_UTILIZATION } from '../src/metrics/eventLoopUtilizationCollector'; const MEASUREMENT_INTERVAL = 10; -class TestMetricReader extends MetricReader { - constructor() { - super(); - } - - protected async onForceFlush(): Promise {} - - protected async onShutdown(): Promise {} -} - -describe('nodejs.event_loop.utilization', function () { +describe(`${ConventionalNamePrefix.NodeJs}.${NODEJS_EVENT_LOOP_UTILIZATION}`, function () { let metricReader: TestMetricReader; let meterProvider: MeterProvider; @@ -47,7 +36,7 @@ describe('nodejs.event_loop.utilization', function () { it('should not export before being enabled', async function () { // arrange const instrumentation = new RuntimeNodeInstrumentation({ - eventLoopUtilizationMeasurementInterval: MEASUREMENT_INTERVAL, + monitoringPrecision: MEASUREMENT_INTERVAL, enabled: false, }); instrumentation.setMeterProvider(meterProvider); @@ -62,32 +51,10 @@ describe('nodejs.event_loop.utilization', function () { assert.strictEqual(scopeMetrics.length, 0); }); - it('should not record result when collecting immediately with custom config', async function () { - const instrumentation = new RuntimeNodeInstrumentation({ - eventLoopUtilizationMeasurementInterval: MEASUREMENT_INTERVAL, - }); - instrumentation.setMeterProvider(meterProvider); - - assert.deepEqual( - (await metricReader.collect()).resourceMetrics.scopeMetrics, - [] - ); - }); - - it('should not record result when collecting immediately with default config', async function () { - const instrumentation = new RuntimeNodeInstrumentation(); - instrumentation.setMeterProvider(meterProvider); - - assert.deepEqual( - (await metricReader.collect()).resourceMetrics.scopeMetrics, - [] - ); - }); - - it('should write event loop utilization metrics after eventLoopUtilizationMeasurementInterval', async function () { + it(`should write ${ConventionalNamePrefix.NodeJs}.${NODEJS_EVENT_LOOP_UTILIZATION}`, async function () { // arrange const instrumentation = new RuntimeNodeInstrumentation({ - eventLoopUtilizationMeasurementInterval: MEASUREMENT_INTERVAL, + monitoringPrecision: MEASUREMENT_INTERVAL, }); instrumentation.setMeterProvider(meterProvider); @@ -102,43 +69,35 @@ describe('nodejs.event_loop.utilization', function () { 'expected no errors from the callback during collection' ); const scopeMetrics = resourceMetrics.scopeMetrics; - assert.strictEqual( - scopeMetrics.length, - 1, - 'expected one scope (one meter created by instrumentation)' - ); - const metrics = scopeMetrics[0].metrics; - assert.strictEqual( - metrics.length, - 1, - 'expected one metric (one metric created by instrumentation)' - ); - assert.strictEqual( - metrics[0].dataPointType, - DataPointType.GAUGE, - 'expected gauge' + const utilizationMetric = scopeMetrics[0].metrics.find( + x => + x.descriptor.name === + `${ConventionalNamePrefix.NodeJs}.${NODEJS_EVENT_LOOP_UTILIZATION}` ); + + assert.notEqual(utilizationMetric, undefined, 'metric not found'); + assert.strictEqual( - metrics[0].descriptor.name, - 'nodejs.event_loop.utilization', + utilizationMetric!.descriptor.name, + `${ConventionalNamePrefix.NodeJs}.${NODEJS_EVENT_LOOP_UTILIZATION}`, 'descriptor.name' ); + assert.strictEqual( - metrics[0].descriptor.description, + utilizationMetric!.descriptor.description, 'Event loop utilization' ); + assert.strictEqual( - metrics[0].descriptor.unit, - '1', + utilizationMetric!.descriptor.unit, + 's', 'expected default unit' ); + assert.strictEqual( - metrics[0].dataPoints.length, + utilizationMetric!.dataPoints.length, 1, 'expected one data point' ); - const val = metrics[0].dataPoints[0].value; - assert.strictEqual(val > 0, true, `val (${val}) > 0`); - assert.strictEqual(val <= 1, true, `val (${val}) <= 1`); }); }); diff --git a/plugins/node/instrumentation-runtime-node/test/heap_space_and_used.test.ts b/plugins/node/instrumentation-runtime-node/test/heap_space_and_used.test.ts new file mode 100644 index 0000000000..a81b594949 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/test/heap_space_and_used.test.ts @@ -0,0 +1,133 @@ +/* + * 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 { DataPointType, MeterProvider } from '@opentelemetry/sdk-metrics'; + +import { RuntimeNodeInstrumentation } from '../src'; +import * as assert from 'assert'; +import { TestMetricReader } from './testMetricsReader'; +import { metricNames } from '../src/metrics/heapSpacesSizeAndUsedCollector'; +import { ConventionalNamePrefix } from '../src/types/ConventionalNamePrefix'; +import { V8_HEAP_SIZE_NAME_ATTRIBUTE } from '../src/consts/attributes'; +import { GaugeMetricData } from '@opentelemetry/sdk-metrics/build/src/export/MetricData'; + +const MEASUREMENT_INTERVAL = 10; + +describe('nodejs.heap_space', function () { + let metricReader: TestMetricReader; + let meterProvider: MeterProvider; + + beforeEach(() => { + metricReader = new TestMetricReader(); + meterProvider = new MeterProvider(); + meterProvider.addMetricReader(metricReader); + }); + + for (const metricName in metricNames) { + it(`should write ${ConventionalNamePrefix.V8js}.${metricName} after monitoringPrecision`, async function () { + // arrange + const instrumentation = new RuntimeNodeInstrumentation({ + monitoringPrecision: MEASUREMENT_INTERVAL, + }); + instrumentation.setMeterProvider(meterProvider); + + // act + await new Promise(resolve => + setTimeout(resolve, MEASUREMENT_INTERVAL * 5) + ); + const { resourceMetrics, errors } = await metricReader.collect(); + + // assert + assert.deepEqual( + errors, + [], + 'expected no errors from the callback during collection' + ); + const scopeMetrics = resourceMetrics.scopeMetrics; + const metric = scopeMetrics[0].metrics.find( + x => + x.descriptor.name === `${ConventionalNamePrefix.V8js}.${metricName}` + ); + + assert.notEqual( + metric, + undefined, + `${ConventionalNamePrefix.V8js}.${metricName} not found` + ); + + assert.strictEqual( + metric!.dataPointType, + DataPointType.GAUGE, + 'expected gauge' + ); + + assert.strictEqual( + metric!.descriptor.name, + `${ConventionalNamePrefix.V8js}.${metricName}`, + 'descriptor.name' + ); + }); + + for (const space of [ + 'new_space', + 'old_space', + 'code_space', + 'large_object_space', + ]) { + it(`should write ${ConventionalNamePrefix.V8js}.${metricName} ${space} attribute`, async function () { + // arrange + const instrumentation = new RuntimeNodeInstrumentation({ + monitoringPrecision: MEASUREMENT_INTERVAL, + }); + instrumentation.setMeterProvider(meterProvider); + const map = [...Array(10).keys()].map(x => x + 10); + map.indexOf(1); + // act + await new Promise(resolve => + setTimeout(resolve, MEASUREMENT_INTERVAL * 5) + ); + const { resourceMetrics, errors } = await metricReader.collect(); + + // assert + assert.deepEqual( + errors, + [], + 'expected no errors from the callback during collection' + ); + const scopeMetrics = resourceMetrics.scopeMetrics; + let metric: GaugeMetricData | undefined = undefined; + const foundMetric = scopeMetrics[0].metrics.find( + x => + x.descriptor.name === `${ConventionalNamePrefix.V8js}.${metricName}` + ); + if (foundMetric?.dataPointType === DataPointType.GAUGE) { + metric = foundMetric; + } + const spaceAttribute = metric?.dataPoints.find( + x => + x.attributes[ + `${ConventionalNamePrefix.V8js}.${V8_HEAP_SIZE_NAME_ATTRIBUTE}` + ] === space + ); + + assert.notEqual( + spaceAttribute, + undefined, + `${ConventionalNamePrefix.V8js}.${metricName} space: ${space} not found` + ); + }); + } + } +}); diff --git a/plugins/node/instrumentation-runtime-node/test/instrumentation.test.ts b/plugins/node/instrumentation-runtime-node/test/instrumentation.test.ts new file mode 100644 index 0000000000..34de947e15 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/test/instrumentation.test.ts @@ -0,0 +1,85 @@ +/* + * 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 { MeterProvider } from '@opentelemetry/sdk-metrics'; + +import { RuntimeNodeInstrumentation } from '../src'; +import * as assert from 'assert'; +import { TestMetricReader } from './testMetricsReader'; + +const MEASUREMENT_INTERVAL = 10; + +describe('instrumentation', function () { + let metricReader: TestMetricReader; + let meterProvider: MeterProvider; + + beforeEach(() => { + metricReader = new TestMetricReader(); + meterProvider = new MeterProvider(); + meterProvider.addMetricReader(metricReader); + }); + + it('should not export before being enabled', async function () { + // arrange + const instrumentation = new RuntimeNodeInstrumentation({ + monitoringPrecision: MEASUREMENT_INTERVAL, + enabled: false, + }); + instrumentation.setMeterProvider(meterProvider); + + // act + await new Promise(resolve => setTimeout(resolve, MEASUREMENT_INTERVAL * 5)); + const { resourceMetrics, errors } = await metricReader.collect(); + + // assert + assert.deepEqual(errors, []); + const scopeMetrics = resourceMetrics.scopeMetrics; + assert.strictEqual(scopeMetrics.length, 0); + }); + + it('should export after being enabled', async function () { + // arrange + const instrumentation = new RuntimeNodeInstrumentation({ + monitoringPrecision: MEASUREMENT_INTERVAL, + enabled: false, + }); + instrumentation.setMeterProvider(meterProvider); + + // act + await new Promise(resolve => setTimeout(resolve, MEASUREMENT_INTERVAL * 5)); + const firstCollections = await metricReader.collect(); + + // assert + assert.deepEqual(firstCollections.errors, []); + const scopeMetrics = firstCollections.resourceMetrics.scopeMetrics; + assert.strictEqual(scopeMetrics.length, 0); + + instrumentation.enable(); + await new Promise(resolve => setTimeout(resolve, MEASUREMENT_INTERVAL * 5)); + + const secondCollection = await metricReader.collect(); + assert.deepEqual( + secondCollection.errors, + [], + 'expected no errors from the callback during collection' + ); + const secondScopeMetrics = secondCollection.resourceMetrics.scopeMetrics; + assert.strictEqual( + secondScopeMetrics.length, + 1, + 'expected one scope (one meter created by instrumentation)' + ); + }); +}); diff --git a/plugins/node/instrumentation-runtime-node/test/testMetricsReader.ts b/plugins/node/instrumentation-runtime-node/test/testMetricsReader.ts new file mode 100644 index 0000000000..f40d1d7382 --- /dev/null +++ b/plugins/node/instrumentation-runtime-node/test/testMetricsReader.ts @@ -0,0 +1,25 @@ +/* + * 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 { MetricReader } from '@opentelemetry/sdk-metrics'; +export class TestMetricReader extends MetricReader { + constructor() { + super(); + } + + protected async onForceFlush(): Promise {} + + protected async onShutdown(): Promise {} +}