Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6,999 changes: 6,681 additions & 318 deletions package-lock.json

Large diffs are not rendered by default.

156 changes: 110 additions & 46 deletions src/autoCollection/metrics/httpMetricsInstrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,27 @@
// Licensed under the MIT license.
import type * as http from 'http';
import type * as https from 'https';
export type Http = typeof http;
import * as semver from 'semver';
import * as url from 'url';
import {
InstrumentationBase,
InstrumentationConfig,
InstrumentationNodeModuleDefinition,
isWrapped,
safeExecuteInTheMiddle
} from '@opentelemetry/instrumentation';
import { getRequestInfo } from '@opentelemetry/instrumentation-http';
import { Histogram, MeterProvider, ValueType } from '@opentelemetry/api-metrics';

import { APPLICATION_INSIGHTS_SDK_VERSION } from "../../declarations/constants";
import { IHttpMetric, IMetricDependencyDimensions, IMetricRequestDimensions } from './types';
import { HttpMetricsInstrumentationConfig, IHttpStandardMetric, MetricId, StandardMetric } from './types';
import { Logger } from '../../library/logging';
import { SpanKind } from '@opentelemetry/api';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';


export class HttpMetricsInstrumentation extends InstrumentationBase {
export class HttpMetricsInstrumentation extends InstrumentationBase<Http> {

private static _instance: HttpMetricsInstrumentation;
private _nodeVersion: string;
public totalRequestCount: number = 0;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to keep track of these totals? Are you planning to replace performance counters with this instrumentation?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfomance counters are currently calculated using these, is still not very clear how perf counters would be handled in OpenTelemetry so having this functionality in the meantime

public totalFailedRequestCount: number = 0;
Expand All @@ -28,16 +31,27 @@ export class HttpMetricsInstrumentation extends InstrumentationBase {
public intervalDependencyExecutionTime: number = 0;
public intervalRequestExecutionTime: number = 0;

public static getInstance() {
if (!HttpMetricsInstrumentation._instance) {
HttpMetricsInstrumentation._instance = new HttpMetricsInstrumentation();
}
return HttpMetricsInstrumentation._instance;
}
private _httpServerDurationHistogram!: Histogram;
private _httpClientDurationHistogram!: Histogram;

constructor(config: InstrumentationConfig = {}) {
constructor(config: HttpMetricsInstrumentationConfig = {}) {
super('AzureHttpMetricsInstrumentation', APPLICATION_INSIGHTS_SDK_VERSION, config);
this._nodeVersion = process.versions.node;
this._updateMetricInstruments();
}

public setMeterProvider(meterProvider: MeterProvider) {
super.setMeterProvider(meterProvider);
this._updateMetricInstruments();
}

private _updateMetricInstruments() {
this._httpServerDurationHistogram = this.meter.createHistogram(StandardMetric.REQUESTS, { valueType: ValueType.DOUBLE });
this._httpClientDurationHistogram = this.meter.createHistogram(StandardMetric.DEPENDENCIES, { valueType: ValueType.DOUBLE });
}

public _getConfig(): HttpMetricsInstrumentationConfig {
return this._config;
}

/**
Expand All @@ -51,20 +65,31 @@ export class HttpMetricsInstrumentation extends InstrumentationBase {
return [this._getHttpDefinition(), this._getHttpsDefinition()];
}

private _htppRequestDone(metric: IHttpMetric) {
private _httpRequestDone(metric: IHttpStandardMetric) {
// Done could be called multiple times, only process metric once
if (!metric.isProcessed) {
metric.isProcessed = true;
Copy link
Copy Markdown

@lzchen lzchen Aug 12, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Curious as to why and how _httpRequestDone is called multiple times for the same request?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It could be called multiple times for specific cases, like request timeout, abort, etc.

metric.attributes["_MS.IsAutocollected"] = "True";
let durationMs = Date.now() - metric.startTime;
if (metric.isOutgoingRequest) {
let success = false;
const statusCode = parseInt(metric.attributes[SemanticAttributes.HTTP_STATUS_CODE]);
if (statusCode !== NaN) {
success = (0 < statusCode) && (statusCode < 500);
}
if (metric.spanKind == SpanKind.SERVER) {
metric.attributes["_MS.MetricId"] = MetricId.REQUESTS_DURATION;
this._httpServerDurationHistogram.record(durationMs, metric.attributes);
this.intervalRequestExecutionTime += durationMs;
if ((metric.dimensions as IMetricRequestDimensions).requestSuccess === false) {
if (!success) {
this.totalFailedRequestCount++;
}
this.totalRequestCount++;
}
else {
metric.attributes["_MS.MetricId"] = MetricId.DEPENDENCIES_DURATION;
this._httpClientDurationHistogram.record(durationMs, metric.attributes);
this.intervalDependencyExecutionTime += durationMs;
if ((metric.dimensions as IMetricDependencyDimensions).dependencySuccess === false) {
if (!success) {
this.totalFailedDependencyCount++;
}
this.totalDependencyCount++;
Expand Down Expand Up @@ -163,56 +188,71 @@ export class HttpMetricsInstrumentation extends InstrumentationBase {
* 2 span for the same request we need to check that the protocol is correct
* See: https://github.com/nodejs/node/blob/v8.17.0/lib/https.js#L245
*/
const { origin, pathname, method, optionsParsed } = getRequestInfo(options);
const { optionsParsed } = getRequestInfo(options);
if (
component === 'http' &&
semver.lt(process.version, '9.0.0') &&
optionsParsed.protocol === 'https:'
) {
return original.apply(this, [options, ...args]);
}
let dimensions: IMetricDependencyDimensions = {
dependencySuccess: false,
};
let metric: IHttpMetric = {
if (safeExecuteInTheMiddle(
() => instrumentation._getConfig().ignoreOutgoingRequestHook?.(optionsParsed),
(e: unknown) => {
if (e != null) {
instrumentation._diag.error('caught ignoreOutgoingRequestHook error: ', e);
}
},
true
)) {
return original.apply(this, [optionsParsed, ...args]);
}

let metric: IHttpStandardMetric = {
startTime: Date.now(),
isOutgoingRequest: true,
isProcessed: false,
dimensions: dimensions
spanKind: SpanKind.CLIENT,
attributes: {}
};

metric.attributes[SemanticAttributes.HTTP_METHOD] = optionsParsed.method;
metric.attributes[SemanticAttributes.NET_PEER_NAME] = optionsParsed.hostname;

const request: http.ClientRequest = safeExecuteInTheMiddle(
() => original.apply(this, [options, ...args]),
error => {
if (error) {

throw error;
}
}
);
request.prependListener(
'response',
(response: http.IncomingMessage & { aborted?: boolean }) => {
response.on('end', () => {
if (response.aborted && !(response as any).complete) {
(response: http.IncomingMessage & { aborted?: boolean, complete?: boolean }) => {
Logger.getInstance().debug('outgoingRequest on response()');
metric.attributes[SemanticAttributes.NET_PEER_PORT] = String(response.socket.remotePort);
metric.attributes[SemanticAttributes.HTTP_STATUS_CODE] = String(response.statusCode);
metric.attributes[SemanticAttributes.HTTP_FLAVOR] = response.httpVersion;

} else {

}
instrumentation._htppRequestDone(metric);
response.on('end', () => {
Logger.getInstance().debug('outgoingRequest on end()');
instrumentation._httpRequestDone(metric);
});
response.on('error', (error: Error) => {
instrumentation._htppRequestDone(metric);
Logger.getInstance().debug('outgoingRequest on response error()', error);
instrumentation._httpRequestDone(metric);
});
}
);
request.on('close', () => {
Logger.getInstance().debug('outgoingRequest on request close()');
if (!request.aborted) {
instrumentation._htppRequestDone(metric);
instrumentation._httpRequestDone(metric);
}
});
request.on('error', (error: Error) => {
(metric.dimensions as IMetricDependencyDimensions).dependencySuccess = false;
instrumentation._htppRequestDone(metric);
Logger.getInstance().debug('outgoingRequest on request error()');
instrumentation._httpRequestDone(metric);
});
return request;
};
Expand All @@ -238,18 +278,40 @@ export class HttpMetricsInstrumentation extends InstrumentationBase {
if (event !== 'request') {
return original.apply(this, [event, ...args]);
}
let dimensions: IMetricRequestDimensions = {
requestSuccess: false,
};
let metric: IHttpMetric = {
const request = args[0] as http.IncomingMessage;
const response = args[1] as http.ServerResponse;

if (safeExecuteInTheMiddle(
() => instrumentation._getConfig().ignoreIncomingRequestHook?.(request),
(e: unknown) => {
if (e != null) {
instrumentation._diag.error('caught ignoreIncomingRequestHook error: ', e);
}
},
true
)) {
return original.apply(this, [event, ...args]);
}

let metric: IHttpStandardMetric = {
startTime: Date.now(),
isOutgoingRequest: false,
spanKind: SpanKind.SERVER,
isProcessed: false,
dimensions: dimensions
attributes: {}
};

const request = args[0] as http.IncomingMessage;
const response = args[1] as http.ServerResponse;
metric.attributes[SemanticAttributes.HTTP_SCHEME] = component;
metric.attributes[SemanticAttributes.HTTP_METHOD] = request.method || 'GET';
metric.attributes[SemanticAttributes.HTTP_FLAVOR] = request.httpVersion;

const requestUrl = request.url ? url.parse(request.url) : null;
const hostname =
requestUrl?.hostname ||
requestUrl?.host?.replace(/^(.*)(:[0-9]{1,5})/, '$1') ||
'localhost';
metric.attributes[SemanticAttributes.NET_HOST_NAME] = hostname;
metric.attributes[SemanticAttributes.HTTP_TARGET] = requestUrl.pathname || '/';

const originalEnd = response.end;
response.end = function (
this: http.ServerResponse,
Expand All @@ -260,24 +322,26 @@ export class HttpMetricsInstrumentation extends InstrumentationBase {
() => response.end.apply(this, arguments as never),
error => {
if (error) {
instrumentation._htppRequestDone(metric);
instrumentation._httpRequestDone(metric);
throw error;
}
}
);

instrumentation._htppRequestDone(metric);
metric.attributes[SemanticAttributes.HTTP_STATUS_CODE] = String(response.statusCode);
metric.attributes[SemanticAttributes.NET_HOST_PORT] = String(request.socket.localPort);
instrumentation._httpRequestDone(metric);
return returned;
};
return safeExecuteInTheMiddle(
() => original.apply(this, [event, ...args]),
error => {
if (error) {
instrumentation._htppRequestDone(metric);
instrumentation._httpRequestDone(metric);
throw error;
}
}
);
};
}

}
10 changes: 5 additions & 5 deletions src/autoCollection/metrics/nativePerformance.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Meter, ObservableGauge, ObservableResult, Histogram } from "@opentelemetry/api-metrics";
import { GarbageCollectionType, NativeMetricsCounter } from "../../declarations/constants";
import { GarbageCollectionType, NativeMetricsCounter } from "./types";
import { Logger } from "../../library/logging";
import { IBaseConfig, IDisabledExtendedMetrics } from "../../library/configuration/interfaces";

Expand Down Expand Up @@ -83,10 +83,10 @@ export class AutoCollectNativePerformance {
clearInterval(this._handle);
this._handle = undefined;
}
// Remove observable callbacks
this._heapMemoryTotalGauge.removeCallback(this._getHeapTotal);
this._heapMemoryUsageGauge.removeCallback(this._getHeapUsage);
this._memoryUsageNonHeapGauge.removeCallback(this._getNonHeapUsage);
// Remove observable callbacks
this._heapMemoryTotalGauge.removeCallback(this._getHeapTotal);
this._heapMemoryUsageGauge.removeCallback(this._getHeapUsage);
this._memoryUsageNonHeapGauge.removeCallback(this._getNonHeapUsage);
}
}

Expand Down
11 changes: 7 additions & 4 deletions src/autoCollection/metrics/performance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import { Meter, ObservableCallback, ObservableGauge, ObservableResult, ValueType
import { QuickPulseCounter, PerformanceCounter } from "./types";
import { HttpMetricsInstrumentation } from "./httpMetricsInstrumentation";
import { Config } from "../../library";
import { MetricHandler } from "../../library/handlers";


export class AutoCollectPerformance {
private _config: Config;
private _metricHandler: MetricHandler;
private _meter: Meter;
private _enableLiveMetricsCounters: boolean;
private _httpMetrics: HttpMetricsInstrumentation
private _httpMetrics: HttpMetricsInstrumentation;
// Perf counters
private _memoryPrivateBytesGauge: ObservableGauge;
private _memoryPrivateBytesGaugeCallback: ObservableCallback;
Expand Down Expand Up @@ -52,17 +54,18 @@ export class AutoCollectPerformance {
private _lastFailureDependencyRate: { count: number; time: number; executionInterval: number; };
private _lastDependencyDuration: { count: number; time: number; executionInterval: number; };

constructor(meter: Meter, config: Config) {
this._meter = meter;
constructor(config: Config, metricHandler: MetricHandler) {
this._config = config;
this._metricHandler = metricHandler;
this._meter = this._metricHandler.getMeter();
this._enableLiveMetricsCounters = this._config.enableSendLiveMetrics;
this._lastRequestRate = { count: 0, time: 0, executionInterval: 0 };
this._lastFailureRequestRate = { count: 0, time: 0, executionInterval: 0 };
this._lastRequestDuration = { count: 0, time: 0, executionInterval: 0 };
this._lastDependencyRate = { count: 0, time: 0, executionInterval: 0 };
this._lastFailureDependencyRate = { count: 0, time: 0, executionInterval: 0 };
this._lastDependencyDuration = { count: 0, time: 0, executionInterval: 0 };
this._httpMetrics = HttpMetricsInstrumentation.getInstance();
this._httpMetrics = metricHandler.getHttpMetricsInstrumentation();

// perf counters
this._memoryPrivateBytesGauge = this._meter.createObservableGauge(PerformanceCounter.PRIVATE_BYTES, { description: "Amount of memory process has used in bytes", valueType: ValueType.INT });
Expand Down
Loading