@azure/monitor-opentelemetry-exporter 1.0.0-beta.11 → 1.0.0-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +401 -128
- package/dist-esm/src/Declarations/Constants.js +5 -0
- package/dist-esm/src/Declarations/Constants.js.map +1 -1
- package/dist-esm/src/export/base.js +2 -2
- package/dist-esm/src/export/base.js.map +1 -1
- package/dist-esm/src/export/log.js +53 -0
- package/dist-esm/src/export/log.js.map +1 -0
- package/dist-esm/src/export/trace.js +17 -8
- package/dist-esm/src/export/trace.js.map +1 -1
- package/dist-esm/src/generated/applicationInsightsClient.js +1 -1
- package/dist-esm/src/generated/applicationInsightsClient.js.map +1 -1
- package/dist-esm/src/index.js +1 -0
- package/dist-esm/src/index.js.map +1 -1
- package/dist-esm/src/platform/nodejs/context/context.js +11 -3
- package/dist-esm/src/platform/nodejs/context/context.js.map +1 -1
- package/dist-esm/src/platform/nodejs/persist/fileAccessControl.js +2 -1
- package/dist-esm/src/platform/nodejs/persist/fileAccessControl.js.map +1 -1
- package/dist-esm/src/platform/nodejs/persist/fileSystemPersist.js +2 -1
- package/dist-esm/src/platform/nodejs/persist/fileSystemPersist.js.map +1 -1
- package/dist-esm/src/utils/common.js +101 -15
- package/dist-esm/src/utils/common.js.map +1 -1
- package/dist-esm/src/utils/connectionStringParser.js +2 -1
- package/dist-esm/src/utils/connectionStringParser.js.map +1 -1
- package/dist-esm/src/utils/constants/applicationinsights.js +12 -30
- package/dist-esm/src/utils/constants/applicationinsights.js.map +1 -1
- package/dist-esm/src/utils/logUtils.js +177 -0
- package/dist-esm/src/utils/logUtils.js.map +1 -0
- package/dist-esm/src/utils/metricUtils.js +2 -42
- package/dist-esm/src/utils/metricUtils.js.map +1 -1
- package/dist-esm/src/utils/spanUtils.js +35 -31
- package/dist-esm/src/utils/spanUtils.js.map +1 -1
- package/package.json +13 -11
- package/types/monitor-opentelemetry-exporter.d.ts +27 -0
|
@@ -40,6 +40,11 @@ export const ENV_CONNECTION_STRING = "APPLICATIONINSIGHTS_CONNECTION_STRING";
|
|
|
40
40
|
* @internal
|
|
41
41
|
*/
|
|
42
42
|
export const ENV_INSTRUMENTATION_KEY = "APPINSIGHTS_INSTRUMENTATIONKEY";
|
|
43
|
+
/**
|
|
44
|
+
* Disable Statsbeat environment variable name.
|
|
45
|
+
* @internal
|
|
46
|
+
*/
|
|
47
|
+
export const ENV_DISABLE_STATSBEAT = "APPLICATION_INSIGHTS_NO_STATSBEAT";
|
|
43
48
|
/**
|
|
44
49
|
* QuickPulse metric counter names.
|
|
45
50
|
* @internal
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Constants.js","sourceRoot":"","sources":["../../../src/Declarations/Constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAN,IAAY,iBAKX;AALD,WAAY,iBAAiB;IAC3B;;OAEG;IACH,8CAAyB,CAAA;AAC3B,CAAC,EALW,iBAAiB,KAAjB,iBAAiB,QAK5B;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,sCAAsC,CAAC;AAC9E;;;GAGG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,iBAAiB,CAAC,EAAE,CAAC;AAC/D;;;GAGG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,sCAAsC,CAAC;AACnF;;;GAGG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,8BAA8B,CAAC;AACvE;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,uCAAuC,CAAC;AAC7E;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,gCAAgC,CAAC;
|
|
1
|
+
{"version":3,"file":"Constants.js","sourceRoot":"","sources":["../../../src/Declarations/Constants.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC;;GAEG;AACH,MAAM,CAAN,IAA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AED;;;GAGG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAyC;IAClF,CAAC,kBAAkB,CAAC,cAAc,CAAC,EAAE,iBAAiB,CAAC,cAAc;IACrE,CAAC,kBAAkB,CAAC,YAAY,CAAC,EAAE,iBAAiB,CAAC,YAAY;IACjE,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,EAAE,iBAAiB,CAAC,gBAAgB;IAEzE,kCAAkC;IAClC,CAAC,iBAAiB,CAAC,eAAe,CAAC,EAAE,iBAAiB,CAAC,eAAe;IACtE,CAAC,iBAAiB,CAAC,oBAAoB,CAAC,EAAE,iBAAiB,CAAC,oBAAoB;IAChF,CAAC,iBAAiB,CAAC,eAAe,CAAC,EAAE,iBAAiB,CAAC,eAAe;IACtE,CAAC,iBAAiB,CAAC,uBAAuB,CAAC,EAAE,iBAAiB,CAAC,uBAAuB;IACtF,CAAC,iBAAiB,CAAC,mBAAmB,CAAC,EAAE,iBAAiB,CAAC,mBAAmB;IAC9E,CAAC,iBAAiB,CAAC,cAAc,CAAC,EAAE,iBAAiB,CAAC,cAAc;CACrE,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Azure service API version.\n */\nexport enum ServiceApiVersion {\n /**\n * V2 Version\n */\n V2 = \"2020-09-15_Preview\",\n}\n\n/**\n * Default Breeze endpoint.\n * @internal\n */\nexport const DEFAULT_BREEZE_ENDPOINT = \"https://dc.services.visualstudio.com\";\n/**\n * Default Breeze API version.\n * @internal\n */\nexport const DEFAULT_BREEZE_API_VERSION = ServiceApiVersion.V2;\n/**\n * Default Live Metrics endpoint.\n * @internal\n */\nexport const DEFAULT_LIVEMETRICS_ENDPOINT = \"https://rt.services.visualstudio.com\";\n/**\n * Default Live Metrics host.\n * @internal\n */\nexport const DEFAULT_LIVEMETRICS_HOST = \"rt.services.visualstudio.com\";\n/**\n * Connection string environment variable name.\n * @internal\n */\nexport const ENV_CONNECTION_STRING = \"APPLICATIONINSIGHTS_CONNECTION_STRING\";\n/**\n * Instrumentation key environment variable name.\n * @internal\n */\nexport const ENV_INSTRUMENTATION_KEY = \"APPINSIGHTS_INSTRUMENTATIONKEY\";\n/**\n * Disable Statsbeat environment variable name.\n * @internal\n */\nexport const ENV_DISABLE_STATSBEAT = \"APPLICATION_INSIGHTS_NO_STATSBEAT\";\n\n/**\n * QuickPulse metric counter names.\n * @internal\n */\nexport enum QuickPulseCounter {\n // Memory\n COMMITTED_BYTES = \"\\\\Memory\\\\Committed Bytes\",\n\n // CPU\n PROCESSOR_TIME = \"\\\\Processor(_Total)\\\\% Processor Time\",\n\n // Request\n REQUEST_RATE = \"\\\\ApplicationInsights\\\\Requests/Sec\",\n REQUEST_FAILURE_RATE = \"\\\\ApplicationInsights\\\\Requests Failed/Sec\",\n REQUEST_DURATION = \"\\\\ApplicationInsights\\\\Request Duration\",\n\n // Dependency\n DEPENDENCY_RATE = \"\\\\ApplicationInsights\\\\Dependency Calls/Sec\",\n DEPENDENCY_FAILURE_RATE = \"\\\\ApplicationInsights\\\\Dependency Calls Failed/Sec\",\n DEPENDENCY_DURATION = \"\\\\ApplicationInsights\\\\Dependency Call Duration\",\n\n // Exception\n EXCEPTION_RATE = \"\\\\ApplicationInsights\\\\Exceptions/Sec\",\n}\n\n/**\n * Performance metric counter names.\n * @internal\n */\nexport enum PerformanceCounter {\n // Memory\n PRIVATE_BYTES = \"\\\\Process(??APP_WIN32_PROC??)\\\\Private Bytes\",\n AVAILABLE_BYTES = \"\\\\Memory\\\\Available Bytes\",\n\n // CPU\n PROCESSOR_TIME = \"\\\\Processor(_Total)\\\\% Processor Time\",\n PROCESS_TIME = \"\\\\Process(??APP_WIN32_PROC??)\\\\% Processor Time\",\n\n // Requests\n REQUEST_RATE = \"\\\\ASP.NET Applications(??APP_W3SVC_PROC??)\\\\Requests/Sec\",\n REQUEST_DURATION = \"\\\\ASP.NET Applications(??APP_W3SVC_PROC??)\\\\Request Execution Time\",\n}\n\n/**\n * Map a PerformanceCounter/QuickPulseCounter to a QuickPulseCounter. If no mapping exists, mapping is *undefined*\n * @internal\n */\nexport const PerformanceToQuickPulseCounter: { [key: string]: QuickPulseCounter } = {\n [PerformanceCounter.PROCESSOR_TIME]: QuickPulseCounter.PROCESSOR_TIME,\n [PerformanceCounter.REQUEST_RATE]: QuickPulseCounter.REQUEST_RATE,\n [PerformanceCounter.REQUEST_DURATION]: QuickPulseCounter.REQUEST_DURATION,\n\n // Remap quick pulse only counters\n [QuickPulseCounter.COMMITTED_BYTES]: QuickPulseCounter.COMMITTED_BYTES,\n [QuickPulseCounter.REQUEST_FAILURE_RATE]: QuickPulseCounter.REQUEST_FAILURE_RATE,\n [QuickPulseCounter.DEPENDENCY_RATE]: QuickPulseCounter.DEPENDENCY_RATE,\n [QuickPulseCounter.DEPENDENCY_FAILURE_RATE]: QuickPulseCounter.DEPENDENCY_FAILURE_RATE,\n [QuickPulseCounter.DEPENDENCY_DURATION]: QuickPulseCounter.DEPENDENCY_DURATION,\n [QuickPulseCounter.EXCEPTION_RATE]: QuickPulseCounter.EXCEPTION_RATE,\n};\n\n/**\n * QuickPulse document types.\n * @internal\n */\nexport type QuickPulseDocumentType =\n | \"Event\"\n | \"Exception\"\n | \"Trace\"\n | \"Metric\"\n | \"Request\"\n | \"RemoteDependency\"\n | \"Availability\";\n/**\n * QuickPulse telemetry types.\n * @internal\n */\nexport type QuickPulseType =\n | \"EventTelemetryDocument\"\n | \"ExceptionTelemetryDocument\"\n | \"TraceTelemetryDocument\"\n | \"MetricTelemetryDocument\"\n | \"RequestTelemetryDocument\"\n | \"DependencyTelemetryDocument\"\n | \"AvailabilityTelemetryDocument\";\n"]}
|
|
@@ -5,7 +5,7 @@ import { ExportResultCode } from "@opentelemetry/core";
|
|
|
5
5
|
import { ConnectionStringParser } from "../utils/connectionStringParser";
|
|
6
6
|
import { HttpSender, FileSystemPersist } from "../platform";
|
|
7
7
|
import { isRetriable } from "../utils/breezeUtils";
|
|
8
|
-
import { DEFAULT_BREEZE_ENDPOINT, ENV_CONNECTION_STRING } from "../Declarations/Constants";
|
|
8
|
+
import { DEFAULT_BREEZE_ENDPOINT, ENV_CONNECTION_STRING, ENV_DISABLE_STATSBEAT, } from "../Declarations/Constants";
|
|
9
9
|
import { NetworkStatsbeatMetrics } from "./statsbeat/networkStatsbeatMetrics";
|
|
10
10
|
import { MAX_STATSBEAT_FAILURES } from "./statsbeat/types";
|
|
11
11
|
import { getInstance } from "./statsbeat/longIntervalStatsbeatMetrics";
|
|
@@ -47,7 +47,7 @@ export class AzureMonitorBaseExporter {
|
|
|
47
47
|
}
|
|
48
48
|
this._sender = new HttpSender(this._endpointUrl, this._options);
|
|
49
49
|
this._persister = new FileSystemPersist(this._instrumentationKey, this._options);
|
|
50
|
-
if (!this._isStatsbeatExporter) {
|
|
50
|
+
if (!this._isStatsbeatExporter && !process.env[ENV_DISABLE_STATSBEAT]) {
|
|
51
51
|
// Initialize statsbeatMetrics
|
|
52
52
|
this._networkStatsbeatMetrics = new NetworkStatsbeatMetrics({
|
|
53
53
|
instrumentationKey: this._instrumentationKey,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/export/base.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAErE,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAG5D,OAAO,EAAE,WAAW,EAAkB,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC;AAE3F,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,sBAAsB,EAAE,MAAM,mB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E,CAAsB,CAAC;YACvE,IAAI,SAAS,EAAE;gBACb,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;aACpC;SACF;QAAC,OAAO,GAAQ,EAAE;YACjB,IAAI,CAAC,IAAI,CAAC,gCAAgC,EAAE,GAAG,CAAC,CAAC;SAClD;IACH,CAAC;IAEO,eAAe,CAAC,KAAgB;QACtC,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAoB,EAAE;YAC9D,OAAO,IAAI,CAAC;SACb;QACD,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { diag } from \"@opentelemetry/api\";\nimport { ExportResult, ExportResultCode } from \"@opentelemetry/core\";\nimport { RestError } from \"@azure/core-rest-pipeline\";\nimport { ConnectionStringParser } from \"../utils/connectionStringParser\";\nimport { HttpSender, FileSystemPersist } from \"../platform\";\nimport { AzureMonitorExporterOptions } from \"../config\";\nimport { PersistentStorage, Sender } from \"../types\";\nimport { isRetriable, BreezeResponse } from \"../utils/breezeUtils\";\nimport { DEFAULT_BREEZE_ENDPOINT, ENV_CONNECTION_STRING } from \"../Declarations/Constants\";\nimport { TelemetryItem as Envelope } from \"../generated\";\nimport { NetworkStatsbeatMetrics } from \"./statsbeat/networkStatsbeatMetrics\";\nimport { MAX_STATSBEAT_FAILURES } from \"./statsbeat/types\";\nimport { getInstance } from \"./statsbeat/longIntervalStatsbeatMetrics\";\n\nconst DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS = 60_000;\n/**\n * Azure Monitor OpenTelemetry Trace Exporter.\n */\nexport abstract class AzureMonitorBaseExporter {\n /**\n * Instrumentation key to be used for exported envelopes\n */\n protected _instrumentationKey: string = \"\";\n private _endpointUrl: string = \"\";\n private readonly _persister: PersistentStorage;\n private readonly _sender: Sender;\n private _numConsecutiveRedirects: number;\n private _retryTimer: NodeJS.Timer | null;\n private _networkStatsbeatMetrics: NetworkStatsbeatMetrics | undefined;\n private _longIntervalStatsbeatMetrics;\n private _isStatsbeatExporter: boolean;\n private _statsbeatFailureCount: number = 0;\n private _batchSendRetryIntervalMs: number = DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS;\n /**\n * Exporter internal configuration\n */\n private readonly _options: AzureMonitorExporterOptions;\n\n /**\n * Initializes a new instance of the AzureMonitorBaseExporter class.\n * @param AzureMonitorExporterOptions - Exporter configuration.\n */\n constructor(options: AzureMonitorExporterOptions = {}, isStatsbeatExporter?: boolean) {\n this._options = options;\n this._numConsecutiveRedirects = 0;\n this._instrumentationKey = \"\";\n this._endpointUrl = DEFAULT_BREEZE_ENDPOINT;\n const connectionString = this._options.connectionString || process.env[ENV_CONNECTION_STRING];\n this._isStatsbeatExporter = isStatsbeatExporter ? isStatsbeatExporter : false;\n\n if (connectionString) {\n const parsedConnectionString = ConnectionStringParser.parse(connectionString);\n this._instrumentationKey =\n parsedConnectionString.instrumentationkey || this._instrumentationKey;\n this._endpointUrl = parsedConnectionString.ingestionendpoint?.trim() || this._endpointUrl;\n }\n\n // Instrumentation key is required\n if (!this._instrumentationKey) {\n const message =\n \"No instrumentation key or connection string was provided to the Azure Monitor Exporter\";\n diag.error(message);\n throw new Error(message);\n }\n this._sender = new HttpSender(this._endpointUrl, this._options);\n this._persister = new FileSystemPersist(this._instrumentationKey, this._options);\n\n if (!this._isStatsbeatExporter) {\n // Initialize statsbeatMetrics\n this._networkStatsbeatMetrics = new NetworkStatsbeatMetrics({\n instrumentationKey: this._instrumentationKey,\n endpointUrl: this._endpointUrl,\n });\n this._longIntervalStatsbeatMetrics = getInstance({\n instrumentationKey: this._instrumentationKey,\n endpointUrl: this._endpointUrl,\n });\n }\n this._retryTimer = null;\n diag.debug(\"AzureMonitorExporter was successfully setup\");\n }\n\n /**\n * Persist envelopes to disk\n */\n private async _persist(envelopes: unknown[]): Promise<ExportResult> {\n try {\n const success = await this._persister.push(envelopes);\n return success\n ? { code: ExportResultCode.SUCCESS }\n : {\n code: ExportResultCode.FAILED,\n error: new Error(\"Failed to persist envelope in disk.\"),\n };\n } catch (ex: any) {\n return { code: ExportResultCode.FAILED, error: ex };\n }\n }\n\n /**\n * Shutdown exporter\n */\n protected async _shutdown(): Promise<void> {\n return this._sender.shutdown();\n }\n\n /**\n * Export envelopes\n */\n protected async _exportEnvelopes(envelopes: Envelope[]): Promise<ExportResult> {\n diag.info(`Exporting ${envelopes.length} envelope(s)`);\n\n if (envelopes.length < 1) {\n return { code: ExportResultCode.SUCCESS };\n }\n\n try {\n const startTime = new Date().getTime();\n const { result, statusCode } = await this._sender.send(envelopes);\n const endTime = new Date().getTime();\n const duration = endTime - startTime;\n this._numConsecutiveRedirects = 0;\n\n if (statusCode === 200) {\n // Success -- @todo: start retry timer\n if (!this._retryTimer) {\n this._retryTimer = setTimeout(() => {\n this._retryTimer = null;\n this._sendFirstPersistedFile();\n }, this._batchSendRetryIntervalMs);\n this._retryTimer.unref();\n }\n // If we are not exportings statsbeat and statsbeat is not disabled -- count success\n this._networkStatsbeatMetrics?.countSuccess(duration);\n return { code: ExportResultCode.SUCCESS };\n } else if (statusCode && isRetriable(statusCode)) {\n // Failed -- persist failed data\n if (statusCode === 429 || statusCode === 439) {\n this._networkStatsbeatMetrics?.countThrottle(statusCode);\n }\n if (result) {\n diag.info(result);\n const breezeResponse = JSON.parse(result) as BreezeResponse;\n const filteredEnvelopes: Envelope[] = [];\n if (breezeResponse.errors) {\n breezeResponse.errors.forEach((error) => {\n if (error.statusCode && isRetriable(error.statusCode)) {\n filteredEnvelopes.push(envelopes[error.index]);\n }\n });\n }\n if (filteredEnvelopes.length > 0) {\n this._networkStatsbeatMetrics?.countRetry(statusCode);\n // calls resultCallback(ExportResult) based on result of persister.push\n return await this._persist(filteredEnvelopes);\n }\n // Failed -- not retriable\n this._networkStatsbeatMetrics?.countFailure(duration, statusCode);\n return {\n code: ExportResultCode.FAILED,\n };\n } else {\n // calls resultCallback(ExportResult) based on result of persister.push\n this._networkStatsbeatMetrics?.countRetry(statusCode);\n return await this._persist(envelopes);\n }\n } else {\n // Failed -- not retriable\n if (this._networkStatsbeatMetrics) {\n if (statusCode) {\n this._networkStatsbeatMetrics.countFailure(duration, statusCode);\n }\n } else {\n this._incrementStatsbeatFailure();\n }\n return {\n code: ExportResultCode.FAILED,\n };\n }\n } catch (error: any) {\n const restError = error as RestError;\n if (\n restError.statusCode &&\n (restError.statusCode === 307 || // Temporary redirect\n restError.statusCode === 308)\n ) {\n // Permanent redirect\n this._numConsecutiveRedirects++;\n // To prevent circular redirects\n if (this._numConsecutiveRedirects < 10) {\n if (restError.response && restError.response.headers) {\n const location = restError.response.headers.get(\"location\");\n if (location) {\n // Update sender URL\n this._sender.handlePermanentRedirect(location);\n // Send to redirect endpoint as HTTPs library doesn't handle redirect automatically\n return this._exportEnvelopes(envelopes);\n }\n }\n } else {\n let redirectError = new Error(\"Circular redirect\");\n this._networkStatsbeatMetrics?.countException(redirectError);\n return { code: ExportResultCode.FAILED, error: redirectError };\n }\n } else if (restError.statusCode && isRetriable(restError.statusCode)) {\n this._networkStatsbeatMetrics?.countRetry(restError.statusCode);\n return await this._persist(envelopes);\n }\n if (this._isNetworkError(restError)) {\n if (restError.statusCode) {\n this._networkStatsbeatMetrics?.countRetry(restError.statusCode);\n }\n diag.error(\n \"Retrying due to transient client side error. Error message:\",\n restError.message\n );\n return await this._persist(envelopes);\n }\n this._networkStatsbeatMetrics?.countException(restError);\n diag.error(\n \"Envelopes could not be exported and are not retriable. Error message:\",\n restError.message\n );\n return { code: ExportResultCode.FAILED, error: restError };\n }\n }\n\n // Disable collection of statsbeat metrics after max failures\n private _incrementStatsbeatFailure() {\n this._statsbeatFailureCount++;\n if (this._statsbeatFailureCount > MAX_STATSBEAT_FAILURES) {\n this._isStatsbeatExporter = false;\n this._networkStatsbeatMetrics?.shutdown();\n this._longIntervalStatsbeatMetrics?.shutdown();\n this._networkStatsbeatMetrics = undefined;\n this._statsbeatFailureCount = 0;\n }\n }\n\n private async _sendFirstPersistedFile(): Promise<void> {\n try {\n const envelopes = (await this._persister.shift()) as Envelope[] | null;\n if (envelopes) {\n await this._sender.send(envelopes);\n }\n } catch (err: any) {\n diag.warn(`Failed to fetch persisted file`, err);\n }\n }\n\n private _isNetworkError(error: RestError): boolean {\n if (error && error.code && error.code === \"REQUEST_SEND_ERROR\") {\n return true;\n }\n return false;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/export/base.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAErE,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAG5D,OAAO,EAAE,WAAW,EAAkB,MAAM,sBAAsB,CAAC;AACnE,OAAO,EACL,uBAAuB,EACvB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,0CAA0C,CAAC;AAEvE,MAAM,oCAAoC,GAAG,KAAM,CAAC;AACpD;;GAEG;AACH,MAAM,OAAgB,wBAAwB;IAoB5C;;;OAGG;IACH,YAAY,UAAuC,EAAE,EAAE,mBAA6B;;QAvBpF;;WAEG;QACO,wBAAmB,GAAW,EAAE,CAAC;QACnC,iBAAY,GAAW,EAAE,CAAC;QAQ1B,2BAAsB,GAAW,CAAC,CAAC;QACnC,8BAAyB,GAAW,oCAAoC,CAAC;QAW/E,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACx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IAAI,CAAC;SACb;QACD,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { diag } from \"@opentelemetry/api\";\nimport { ExportResult, ExportResultCode } from \"@opentelemetry/core\";\nimport { RestError } from \"@azure/core-rest-pipeline\";\nimport { ConnectionStringParser } from \"../utils/connectionStringParser\";\nimport { HttpSender, FileSystemPersist } from \"../platform\";\nimport { AzureMonitorExporterOptions } from \"../config\";\nimport { PersistentStorage, Sender } from \"../types\";\nimport { isRetriable, BreezeResponse } from \"../utils/breezeUtils\";\nimport {\n DEFAULT_BREEZE_ENDPOINT,\n ENV_CONNECTION_STRING,\n ENV_DISABLE_STATSBEAT,\n} from \"../Declarations/Constants\";\nimport { TelemetryItem as Envelope } from \"../generated\";\nimport { NetworkStatsbeatMetrics } from \"./statsbeat/networkStatsbeatMetrics\";\nimport { MAX_STATSBEAT_FAILURES } from \"./statsbeat/types\";\nimport { getInstance } from \"./statsbeat/longIntervalStatsbeatMetrics\";\n\nconst DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS = 60_000;\n/**\n * Azure Monitor OpenTelemetry Trace Exporter.\n */\nexport abstract class AzureMonitorBaseExporter {\n /**\n * Instrumentation key to be used for exported envelopes\n */\n protected _instrumentationKey: string = \"\";\n private _endpointUrl: string = \"\";\n private readonly _persister: PersistentStorage;\n private readonly _sender: Sender;\n private _numConsecutiveRedirects: number;\n private _retryTimer: NodeJS.Timer | null;\n private _networkStatsbeatMetrics: NetworkStatsbeatMetrics | undefined;\n private _longIntervalStatsbeatMetrics;\n private _isStatsbeatExporter: boolean;\n private _statsbeatFailureCount: number = 0;\n private _batchSendRetryIntervalMs: number = DEFAULT_BATCH_SEND_RETRY_INTERVAL_MS;\n /**\n * Exporter internal configuration\n */\n private readonly _options: AzureMonitorExporterOptions;\n\n /**\n * Initializes a new instance of the AzureMonitorBaseExporter class.\n * @param AzureMonitorExporterOptions - Exporter configuration.\n */\n constructor(options: AzureMonitorExporterOptions = {}, isStatsbeatExporter?: boolean) {\n this._options = options;\n this._numConsecutiveRedirects = 0;\n this._instrumentationKey = \"\";\n this._endpointUrl = DEFAULT_BREEZE_ENDPOINT;\n const connectionString = this._options.connectionString || process.env[ENV_CONNECTION_STRING];\n this._isStatsbeatExporter = isStatsbeatExporter ? isStatsbeatExporter : false;\n\n if (connectionString) {\n const parsedConnectionString = ConnectionStringParser.parse(connectionString);\n this._instrumentationKey =\n parsedConnectionString.instrumentationkey || this._instrumentationKey;\n this._endpointUrl = parsedConnectionString.ingestionendpoint?.trim() || this._endpointUrl;\n }\n\n // Instrumentation key is required\n if (!this._instrumentationKey) {\n const message =\n \"No instrumentation key or connection string was provided to the Azure Monitor Exporter\";\n diag.error(message);\n throw new Error(message);\n }\n this._sender = new HttpSender(this._endpointUrl, this._options);\n this._persister = new FileSystemPersist(this._instrumentationKey, this._options);\n\n if (!this._isStatsbeatExporter && !process.env[ENV_DISABLE_STATSBEAT]) {\n // Initialize statsbeatMetrics\n this._networkStatsbeatMetrics = new NetworkStatsbeatMetrics({\n instrumentationKey: this._instrumentationKey,\n endpointUrl: this._endpointUrl,\n });\n this._longIntervalStatsbeatMetrics = getInstance({\n instrumentationKey: this._instrumentationKey,\n endpointUrl: this._endpointUrl,\n });\n }\n this._retryTimer = null;\n diag.debug(\"AzureMonitorExporter was successfully setup\");\n }\n\n /**\n * Persist envelopes to disk\n */\n private async _persist(envelopes: unknown[]): Promise<ExportResult> {\n try {\n const success = await this._persister.push(envelopes);\n return success\n ? { code: ExportResultCode.SUCCESS }\n : {\n code: ExportResultCode.FAILED,\n error: new Error(\"Failed to persist envelope in disk.\"),\n };\n } catch (ex: any) {\n return { code: ExportResultCode.FAILED, error: ex };\n }\n }\n\n /**\n * Shutdown exporter\n */\n protected async _shutdown(): Promise<void> {\n return this._sender.shutdown();\n }\n\n /**\n * Export envelopes\n */\n protected async _exportEnvelopes(envelopes: Envelope[]): Promise<ExportResult> {\n diag.info(`Exporting ${envelopes.length} envelope(s)`);\n\n if (envelopes.length < 1) {\n return { code: ExportResultCode.SUCCESS };\n }\n\n try {\n const startTime = new Date().getTime();\n const { result, statusCode } = await this._sender.send(envelopes);\n const endTime = new Date().getTime();\n const duration = endTime - startTime;\n this._numConsecutiveRedirects = 0;\n\n if (statusCode === 200) {\n // Success -- @todo: start retry timer\n if (!this._retryTimer) {\n this._retryTimer = setTimeout(() => {\n this._retryTimer = null;\n this._sendFirstPersistedFile();\n }, this._batchSendRetryIntervalMs);\n this._retryTimer.unref();\n }\n // If we are not exportings statsbeat and statsbeat is not disabled -- count success\n this._networkStatsbeatMetrics?.countSuccess(duration);\n return { code: ExportResultCode.SUCCESS };\n } else if (statusCode && isRetriable(statusCode)) {\n // Failed -- persist failed data\n if (statusCode === 429 || statusCode === 439) {\n this._networkStatsbeatMetrics?.countThrottle(statusCode);\n }\n if (result) {\n diag.info(result);\n const breezeResponse = JSON.parse(result) as BreezeResponse;\n const filteredEnvelopes: Envelope[] = [];\n if (breezeResponse.errors) {\n breezeResponse.errors.forEach((error) => {\n if (error.statusCode && isRetriable(error.statusCode)) {\n filteredEnvelopes.push(envelopes[error.index]);\n }\n });\n }\n if (filteredEnvelopes.length > 0) {\n this._networkStatsbeatMetrics?.countRetry(statusCode);\n // calls resultCallback(ExportResult) based on result of persister.push\n return await this._persist(filteredEnvelopes);\n }\n // Failed -- not retriable\n this._networkStatsbeatMetrics?.countFailure(duration, statusCode);\n return {\n code: ExportResultCode.FAILED,\n };\n } else {\n // calls resultCallback(ExportResult) based on result of persister.push\n this._networkStatsbeatMetrics?.countRetry(statusCode);\n return await this._persist(envelopes);\n }\n } else {\n // Failed -- not retriable\n if (this._networkStatsbeatMetrics) {\n if (statusCode) {\n this._networkStatsbeatMetrics.countFailure(duration, statusCode);\n }\n } else {\n this._incrementStatsbeatFailure();\n }\n return {\n code: ExportResultCode.FAILED,\n };\n }\n } catch (error: any) {\n const restError = error as RestError;\n if (\n restError.statusCode &&\n (restError.statusCode === 307 || // Temporary redirect\n restError.statusCode === 308)\n ) {\n // Permanent redirect\n this._numConsecutiveRedirects++;\n // To prevent circular redirects\n if (this._numConsecutiveRedirects < 10) {\n if (restError.response && restError.response.headers) {\n const location = restError.response.headers.get(\"location\");\n if (location) {\n // Update sender URL\n this._sender.handlePermanentRedirect(location);\n // Send to redirect endpoint as HTTPs library doesn't handle redirect automatically\n return this._exportEnvelopes(envelopes);\n }\n }\n } else {\n let redirectError = new Error(\"Circular redirect\");\n this._networkStatsbeatMetrics?.countException(redirectError);\n return { code: ExportResultCode.FAILED, error: redirectError };\n }\n } else if (restError.statusCode && isRetriable(restError.statusCode)) {\n this._networkStatsbeatMetrics?.countRetry(restError.statusCode);\n return await this._persist(envelopes);\n }\n if (this._isNetworkError(restError)) {\n if (restError.statusCode) {\n this._networkStatsbeatMetrics?.countRetry(restError.statusCode);\n }\n diag.error(\n \"Retrying due to transient client side error. Error message:\",\n restError.message\n );\n return await this._persist(envelopes);\n }\n this._networkStatsbeatMetrics?.countException(restError);\n diag.error(\n \"Envelopes could not be exported and are not retriable. Error message:\",\n restError.message\n );\n return { code: ExportResultCode.FAILED, error: restError };\n }\n }\n\n // Disable collection of statsbeat metrics after max failures\n private _incrementStatsbeatFailure() {\n this._statsbeatFailureCount++;\n if (this._statsbeatFailureCount > MAX_STATSBEAT_FAILURES) {\n this._isStatsbeatExporter = false;\n this._networkStatsbeatMetrics?.shutdown();\n this._longIntervalStatsbeatMetrics?.shutdown();\n this._networkStatsbeatMetrics = undefined;\n this._statsbeatFailureCount = 0;\n }\n }\n\n private async _sendFirstPersistedFile(): Promise<void> {\n try {\n const envelopes = (await this._persister.shift()) as Envelope[] | null;\n if (envelopes) {\n await this._sender.send(envelopes);\n }\n } catch (err: any) {\n diag.warn(`Failed to fetch persisted file`, err);\n }\n }\n\n private _isNetworkError(error: RestError): boolean {\n if (error && error.code && error.code === \"REQUEST_SEND_ERROR\") {\n return true;\n }\n return false;\n }\n}\n"]}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Copyright (c) Microsoft Corporation.
|
|
2
|
+
// Licensed under the MIT license.
|
|
3
|
+
import { diag } from "@opentelemetry/api";
|
|
4
|
+
import { ExportResultCode } from "@opentelemetry/core";
|
|
5
|
+
import { AzureMonitorBaseExporter } from "./base";
|
|
6
|
+
import { logToEnvelope } from "../utils/logUtils";
|
|
7
|
+
/**
|
|
8
|
+
* Azure Monitor OpenTelemetry Log Exporter.
|
|
9
|
+
*/
|
|
10
|
+
export class AzureMonitorLogExporter extends AzureMonitorBaseExporter {
|
|
11
|
+
/**
|
|
12
|
+
* Initializes a new instance of the AzureMonitorLogExporter class.
|
|
13
|
+
* @param AzureExporterConfig - Exporter configuration.
|
|
14
|
+
*/
|
|
15
|
+
constructor(options = {}) {
|
|
16
|
+
super(options);
|
|
17
|
+
/**
|
|
18
|
+
* Flag to determine if Exporter is shutdown.
|
|
19
|
+
*/
|
|
20
|
+
this._isShutdown = false;
|
|
21
|
+
diag.debug("AzureMonitorLogExporter was successfully setup");
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Export OpenTelemetry logs.
|
|
25
|
+
* @param logs - Logs to export.
|
|
26
|
+
* @param resultCallback - Result callback.
|
|
27
|
+
*/
|
|
28
|
+
async export(logs, resultCallback) {
|
|
29
|
+
if (this._isShutdown) {
|
|
30
|
+
diag.info("Exporter shut down. Failed to export spans.");
|
|
31
|
+
setTimeout(() => resultCallback({ code: ExportResultCode.FAILED }), 0);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
diag.info(`Exporting ${logs.length} logs(s). Converting to envelopes...`);
|
|
35
|
+
let envelopes = [];
|
|
36
|
+
logs.forEach((log) => {
|
|
37
|
+
let envelope = logToEnvelope(log, this._instrumentationKey);
|
|
38
|
+
if (envelope) {
|
|
39
|
+
envelopes.push(envelope);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
resultCallback(await this._exportEnvelopes(envelopes));
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Shutdown AzureMonitorLogExporter.
|
|
46
|
+
*/
|
|
47
|
+
async shutdown() {
|
|
48
|
+
this._isShutdown = true;
|
|
49
|
+
diag.info("AzureMonitorLogExporter shutting down");
|
|
50
|
+
return this._shutdown();
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=log.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"log.js","sourceRoot":"","sources":["../../../src/export/log.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,QAAQ,CAAC;AAElD,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAKlD;;GAEG;AACH,MAAM,OAAO,uBAAwB,SAAQ,wBAAwB;IAKnE;;;OAGG;IAEH,YAAY,UAAuC,EAAE;QACnD,KAAK,CAAC,OAAO,CAAC,CAAC;QAVjB;;WAEG;QACK,gBAAW,GAAG,KAAK,CAAC;QAQ1B,IAAI,CAAC,KAAK,CAAC,gDAAgD,CAAC,CAAC;IAC/D,CAAC;IAED;;;;OAIG;IACI,KAAK,CAAC,MAAM,CAAC,IAAyB,EAAE,cAA8C;QAC3F,IAAI,IAAI,CAAC,WAAW,EAAE;YACpB,IAAI,CAAC,IAAI,CAAC,6CAA6C,CAAC,CAAC;YACzD,UAAU,CAAC,GAAG,EAAE,CAAC,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YACvE,OAAO;SACR;QACD,IAAI,CAAC,IAAI,CAAC,aAAa,IAAI,CAAC,MAAM,sCAAsC,CAAC,CAAC;QAE1E,IAAI,SAAS,GAAe,EAAE,CAAC;QAC/B,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;YACnB,IAAI,QAAQ,GAAG,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,mBAAmB,CAAC,CAAC;YAC5D,IAAI,QAAQ,EAAE;gBACZ,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;aAC1B;QACH,CAAC,CAAC,CAAC;QACH,cAAc,CAAC,MAAM,IAAI,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC;IACzD,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,QAAQ;QACnB,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;QACxB,IAAI,CAAC,IAAI,CAAC,uCAAuC,CAAC,CAAC;QACnD,OAAO,IAAI,CAAC,SAAS,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { diag } from \"@opentelemetry/api\";\nimport { ExportResult, ExportResultCode } from \"@opentelemetry/core\";\nimport { AzureMonitorBaseExporter } from \"./base\";\nimport { TelemetryItem as Envelope } from \"../generated\";\nimport { logToEnvelope } from \"../utils/logUtils\";\nimport { AzureMonitorExporterOptions } from \"../config\";\n\nimport type { ReadableLogRecord, LogRecordExporter } from \"@opentelemetry/sdk-logs\";\n\n/**\n * Azure Monitor OpenTelemetry Log Exporter.\n */\nexport class AzureMonitorLogExporter extends AzureMonitorBaseExporter implements LogRecordExporter {\n /**\n * Flag to determine if Exporter is shutdown.\n */\n private _isShutdown = false;\n /**\n * Initializes a new instance of the AzureMonitorLogExporter class.\n * @param AzureExporterConfig - Exporter configuration.\n */\n\n constructor(options: AzureMonitorExporterOptions = {}) {\n super(options);\n diag.debug(\"AzureMonitorLogExporter was successfully setup\");\n }\n\n /**\n * Export OpenTelemetry logs.\n * @param logs - Logs to export.\n * @param resultCallback - Result callback.\n */\n public async export(logs: ReadableLogRecord[], resultCallback: (result: ExportResult) => void) {\n if (this._isShutdown) {\n diag.info(\"Exporter shut down. Failed to export spans.\");\n setTimeout(() => resultCallback({ code: ExportResultCode.FAILED }), 0);\n return;\n }\n diag.info(`Exporting ${logs.length} logs(s). Converting to envelopes...`);\n\n let envelopes: Envelope[] = [];\n logs.forEach((log) => {\n let envelope = logToEnvelope(log, this._instrumentationKey);\n if (envelope) {\n envelopes.push(envelope);\n }\n });\n resultCallback(await this._exportEnvelopes(envelopes));\n }\n\n /**\n * Shutdown AzureMonitorLogExporter.\n */\n public async shutdown(): Promise<void> {\n this._isShutdown = true;\n diag.info(\"AzureMonitorLogExporter shutting down\");\n return this._shutdown();\n }\n}\n"]}
|
|
@@ -4,6 +4,7 @@ import { diag } from "@opentelemetry/api";
|
|
|
4
4
|
import { ExportResultCode } from "@opentelemetry/core";
|
|
5
5
|
import { AzureMonitorBaseExporter } from "./base";
|
|
6
6
|
import { readableSpanToEnvelope, spanEventsToEnvelopes } from "../utils/spanUtils";
|
|
7
|
+
import { createResourceMetricEnvelope } from "../utils/common";
|
|
7
8
|
/**
|
|
8
9
|
* Azure Monitor OpenTelemetry Trace Exporter.
|
|
9
10
|
*/
|
|
@@ -32,15 +33,23 @@ export class AzureMonitorTraceExporter extends AzureMonitorBaseExporter {
|
|
|
32
33
|
return;
|
|
33
34
|
}
|
|
34
35
|
diag.info(`Exporting ${spans.length} span(s). Converting to envelopes...`);
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
envelopes.push(...spanEventEnvelopes);
|
|
36
|
+
if (spans.length > 0) {
|
|
37
|
+
let envelopes = [];
|
|
38
|
+
const resourceMetricEnvelope = createResourceMetricEnvelope(spans[0].resource, this._instrumentationKey);
|
|
39
|
+
if (resourceMetricEnvelope) {
|
|
40
|
+
envelopes.push(resourceMetricEnvelope);
|
|
41
41
|
}
|
|
42
|
-
|
|
43
|
-
|
|
42
|
+
spans.forEach((span) => {
|
|
43
|
+
envelopes.push(readableSpanToEnvelope(span, this._instrumentationKey));
|
|
44
|
+
let spanEventEnvelopes = spanEventsToEnvelopes(span, this._instrumentationKey);
|
|
45
|
+
if (spanEventEnvelopes.length > 0) {
|
|
46
|
+
envelopes.push(...spanEventEnvelopes);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
resultCallback(await this._exportEnvelopes(envelopes));
|
|
50
|
+
}
|
|
51
|
+
// No data to export
|
|
52
|
+
resultCallback({ code: ExportResultCode.SUCCESS });
|
|
44
53
|
}
|
|
45
54
|
/**
|
|
46
55
|
* Shutdown AzureMonitorTraceExporter.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trace.js","sourceRoot":"","sources":["../../../src/export/trace.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAErE,OAAO,EAAE,wBAAwB,EAAE,MAAM,QAAQ,CAAC;AAGlD,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"trace.js","sourceRoot":"","sources":["../../../src/export/trace.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAErE,OAAO,EAAE,wBAAwB,EAAE,MAAM,QAAQ,CAAC;AAGlD,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AACnF,OAAO,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAC;AAE/D;;GAEG;AACH,MAAM,OAAO,yBAA0B,SAAQ,wBAAwB;IAMrE;;;OAGG;IACH,YAAY,UAAuC,EAAE;QACnD,KAAK,CAAC,OAAO,CAAC,CAAC;QAVjB;;WAEG;QACK,gBA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AAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;IACrD,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,QAAQ;QACZ,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;QACxB,IAAI,CAAC,IAAI,CAAC,yCAAyC,CAAC,CAAC;QACrD,OAAO,IAAI,CAAC,SAAS,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { diag } from \"@opentelemetry/api\";\nimport { ExportResult, ExportResultCode } from \"@opentelemetry/core\";\nimport { ReadableSpan, SpanExporter } from \"@opentelemetry/sdk-trace-base\";\nimport { AzureMonitorBaseExporter } from \"./base\";\nimport { AzureMonitorExporterOptions } from \"../config\";\nimport { TelemetryItem as Envelope } from \"../generated\";\nimport { readableSpanToEnvelope, spanEventsToEnvelopes } from \"../utils/spanUtils\";\nimport { createResourceMetricEnvelope } from \"../utils/common\";\n\n/**\n * Azure Monitor OpenTelemetry Trace Exporter.\n */\nexport class AzureMonitorTraceExporter extends AzureMonitorBaseExporter implements SpanExporter {\n /**\n * Flag to determine if Exporter is shutdown.\n */\n private _isShutdown = false;\n\n /**\n * Initializes a new instance of the AzureMonitorTraceExporter class.\n * @param AzureExporterConfig - Exporter configuration.\n */\n constructor(options: AzureMonitorExporterOptions = {}) {\n super(options);\n diag.debug(\"AzureMonitorTraceExporter was successfully setup\");\n }\n\n /**\n * Export OpenTelemetry spans.\n * @param spans - Spans to export.\n * @param resultCallback - Result callback.\n */\n async export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): Promise<void> {\n if (this._isShutdown) {\n diag.info(\"Exporter shut down. Failed to export spans.\");\n setTimeout(() => resultCallback({ code: ExportResultCode.FAILED }), 0);\n return;\n }\n\n diag.info(`Exporting ${spans.length} span(s). Converting to envelopes...`);\n\n if (spans.length > 0) {\n let envelopes: Envelope[] = [];\n const resourceMetricEnvelope = createResourceMetricEnvelope(\n spans[0].resource,\n this._instrumentationKey\n );\n if (resourceMetricEnvelope) {\n envelopes.push(resourceMetricEnvelope);\n }\n spans.forEach((span) => {\n envelopes.push(readableSpanToEnvelope(span, this._instrumentationKey));\n let spanEventEnvelopes = spanEventsToEnvelopes(span, this._instrumentationKey);\n if (spanEventEnvelopes.length > 0) {\n envelopes.push(...spanEventEnvelopes);\n }\n });\n resultCallback(await this._exportEnvelopes(envelopes));\n }\n // No data to export\n resultCallback({ code: ExportResultCode.SUCCESS });\n }\n\n /**\n * Shutdown AzureMonitorTraceExporter.\n */\n async shutdown(): Promise<void> {\n this._isShutdown = true;\n diag.info(\"AzureMonitorTraceExporter shutting down\");\n return this._shutdown();\n }\n}\n"]}
|
|
@@ -23,7 +23,7 @@ export class ApplicationInsightsClient extends coreClient.ServiceClient {
|
|
|
23
23
|
const defaults = {
|
|
24
24
|
requestContentType: "application/json; charset=utf-8"
|
|
25
25
|
};
|
|
26
|
-
const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.
|
|
26
|
+
const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.13`;
|
|
27
27
|
const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix
|
|
28
28
|
? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
|
|
29
29
|
: `${packageDetails}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"applicationInsightsClient.js","sourceRoot":"","sources":["../../../src/generated/applicationInsightsClient.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,UAAU,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,gBAAgB,MAAM,2BAA2B,CAAC;AAC9D,OAAO,KAAK,UAAU,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,OAAO,MAAM,kBAAkB,CAAC;AAQ5C,MAAM,OAAO,yBAA0B,SAAQ,UAAU,CAAC,aAAa;IAGrE;;;OAGG;IACH,YAAY,OA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U,CAAC,MAAM,CAAC;IAC7D,SAAS,EAAE,MAAM;IACjB,UAAU;CACX,CAAC","sourcesContent":["/*\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n *\n * Code generated by Microsoft (R) AutoRest Code Generator.\n * Changes may cause incorrect behavior and will be lost if the code is regenerated.\n */\n\nimport * as coreClient from \"@azure/core-client\";\nimport * as coreRestPipeline from \"@azure/core-rest-pipeline\";\nimport * as Parameters from \"./models/parameters\";\nimport * as Mappers from \"./models/mappers\";\nimport {\n ApplicationInsightsClientOptionalParams,\n TelemetryItem,\n TrackOptionalParams,\n TrackOperationResponse\n} from \"./models\";\n\nexport class ApplicationInsightsClient extends coreClient.ServiceClient {\n host: string;\n\n /**\n * Initializes a new instance of the ApplicationInsightsClient class.\n * @param options The parameter options\n */\n constructor(options?: ApplicationInsightsClientOptionalParams) {\n // Initializing default values for options\n if (!options) {\n options = {};\n }\n const defaults: ApplicationInsightsClientOptionalParams = {\n requestContentType: \"application/json; charset=utf-8\"\n };\n\n const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.
|
|
1
|
+
{"version":3,"file":"applicationInsightsClient.js","sourceRoot":"","sources":["../../../src/generated/applicationInsightsClient.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,UAAU,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,gBAAgB,MAAM,2BAA2B,CAAC;AAC9D,OAAO,KAAK,UAAU,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,OAAO,MAAM,kBAAkB,CAAC;AAQ5C,MAAM,OAAO,yBAA0B,SAAQ,UAAU,CAAC,aAAa;IAGrE;;;OAGG;IACH,YAAY,OAAiD;;QAC3D,0CAA0C;QAC1C,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,EAAE,CAAC;SACd;QACD,MAAM,QAAQ,GAA4C;YACxD,kBAAkB,EAAE,iCAAiC;SACtD,CAAC;QAEF,MAAM,cAAc,GA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I,sCAAsC,CAAC;IACrE,CAAC;IAED;;;;OAIG;IACH,KAAK,CACH,IAAqB,EACrB,OAA6B;QAE7B,OAAO,IAAI,CAAC,oBAAoB,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,kBAAkB,CAAC,CAAC;IAC1E,CAAC;CACF;AACD,2BAA2B;AAC3B,MAAM,UAAU,GAAG,UAAU,CAAC,gBAAgB,CAAC,OAAO,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC;AAE3E,MAAM,kBAAkB,GAA6B;IACnD,IAAI,EAAE,QAAQ;IACd,UAAU,EAAE,MAAM;IAClB,SAAS,EAAE;QACT,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;SAClC;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;SAClC;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;QACD,GAAG,EAAE;YACH,UAAU,EAAE,OAAO,CAAC,aAAa;YACjC,OAAO,EAAE,IAAI;SACd;KACF;IACD,WAAW,EAAE,UAAU,CAAC,IAAI;IAC5B,aAAa,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;IAChC,gBAAgB,EAAE,CAAC,UAAU,CAAC,WAAW,EAAE,UAAU,CAAC,MAAM,CAAC;IAC7D,SAAS,EAAE,MAAM;IACjB,UAAU;CACX,CAAC","sourcesContent":["/*\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n *\n * Code generated by Microsoft (R) AutoRest Code Generator.\n * Changes may cause incorrect behavior and will be lost if the code is regenerated.\n */\n\nimport * as coreClient from \"@azure/core-client\";\nimport * as coreRestPipeline from \"@azure/core-rest-pipeline\";\nimport * as Parameters from \"./models/parameters\";\nimport * as Mappers from \"./models/mappers\";\nimport {\n ApplicationInsightsClientOptionalParams,\n TelemetryItem,\n TrackOptionalParams,\n TrackOperationResponse\n} from \"./models\";\n\nexport class ApplicationInsightsClient extends coreClient.ServiceClient {\n host: string;\n\n /**\n * Initializes a new instance of the ApplicationInsightsClient class.\n * @param options The parameter options\n */\n constructor(options?: ApplicationInsightsClientOptionalParams) {\n // Initializing default values for options\n if (!options) {\n options = {};\n }\n const defaults: ApplicationInsightsClientOptionalParams = {\n requestContentType: \"application/json; charset=utf-8\"\n };\n\n const packageDetails = `azsdk-js-monitor-opentelemetry-exporter/1.0.0-beta.13`;\n const userAgentPrefix =\n options.userAgentOptions && options.userAgentOptions.userAgentPrefix\n ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`\n : `${packageDetails}`;\n\n const optionsWithDefaults = {\n ...defaults,\n ...options,\n userAgentOptions: {\n userAgentPrefix\n },\n baseUri: options.endpoint ?? options.baseUri ?? \"{Host}/v2.1\"\n };\n super(optionsWithDefaults);\n\n if (options?.pipeline && options.pipeline.getOrderedPolicies().length > 0) {\n const pipelinePolicies: coreRestPipeline.PipelinePolicy[] = options.pipeline.getOrderedPolicies();\n const bearerTokenAuthenticationPolicyFound = pipelinePolicies.some(\n (pipelinePolicy) =>\n pipelinePolicy.name ===\n coreRestPipeline.bearerTokenAuthenticationPolicyName\n );\n if (!bearerTokenAuthenticationPolicyFound) {\n this.pipeline.removePolicy({\n name: coreRestPipeline.bearerTokenAuthenticationPolicyName\n });\n this.pipeline.addPolicy(\n coreRestPipeline.bearerTokenAuthenticationPolicy({\n scopes: `${optionsWithDefaults.baseUri}/.default`,\n challengeCallbacks: {\n authorizeRequestOnChallenge:\n coreClient.authorizeRequestOnClaimChallenge\n }\n })\n );\n }\n }\n\n // Assigning values to Constant parameters\n this.host = options.host || \"https://dc.services.visualstudio.com\";\n }\n\n /**\n * This operation sends a sequence of telemetry events that will be monitored by Azure Monitor.\n * @param body The list of telemetry events to track.\n * @param options The options parameters.\n */\n track(\n body: TelemetryItem[],\n options?: TrackOptionalParams\n ): Promise<TrackOperationResponse> {\n return this.sendOperationRequest({ body, options }, trackOperationSpec);\n }\n}\n// Operation Specifications\nconst serializer = coreClient.createSerializer(Mappers, /* isXml */ false);\n\nconst trackOperationSpec: coreClient.OperationSpec = {\n path: \"/track\",\n httpMethod: \"POST\",\n responses: {\n 200: {\n bodyMapper: Mappers.TrackResponse\n },\n 206: {\n bodyMapper: Mappers.TrackResponse\n },\n 400: {\n bodyMapper: Mappers.TrackResponse,\n isError: true\n },\n 402: {\n bodyMapper: Mappers.TrackResponse,\n isError: true\n },\n 429: {\n bodyMapper: Mappers.TrackResponse,\n isError: true\n },\n 500: {\n bodyMapper: Mappers.TrackResponse,\n isError: true\n },\n 503: {\n bodyMapper: Mappers.TrackResponse,\n isError: true\n }\n },\n requestBody: Parameters.body,\n urlParameters: [Parameters.host],\n headerParameters: [Parameters.contentType, Parameters.accept],\n mediaType: \"json\",\n serializer\n};\n"]}
|
package/dist-esm/src/index.js
CHANGED
|
@@ -4,6 +4,7 @@ export { ApplicationInsightsSampler } from "./sampling";
|
|
|
4
4
|
export { AzureMonitorBaseExporter } from "./export/base";
|
|
5
5
|
export { AzureMonitorTraceExporter } from "./export/trace";
|
|
6
6
|
export { AzureMonitorMetricExporter } from "./export/metric";
|
|
7
|
+
export { AzureMonitorLogExporter } from "./export/log";
|
|
7
8
|
export { AzureMonitorStatsbeatExporter } from "./export/statsbeat/statsbeatExporter";
|
|
8
9
|
export { ServiceApiVersion } from "./Declarations/Constants";
|
|
9
10
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAErF,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport { ApplicationInsightsSampler } from \"./sampling\";\nexport { AzureMonitorBaseExporter } from \"./export/base\";\nexport { AzureMonitorTraceExporter } from \"./export/trace\";\nexport { AzureMonitorMetricExporter } from \"./export/metric\";\nexport { AzureMonitorStatsbeatExporter } from \"./export/statsbeat/statsbeatExporter\";\nexport { AzureMonitorExporterOptions } from \"./config\";\nexport { ServiceApiVersion } from \"./Declarations/Constants\";\nexport {\n ApplicationInsightsClientOptionalParams,\n MonitorBase,\n MonitorDomain,\n TelemetryItem,\n} from \"./generated/models\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AACzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAErF,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nexport { ApplicationInsightsSampler } from \"./sampling\";\nexport { AzureMonitorBaseExporter } from \"./export/base\";\nexport { AzureMonitorTraceExporter } from \"./export/trace\";\nexport { AzureMonitorMetricExporter } from \"./export/metric\";\nexport { AzureMonitorLogExporter } from \"./export/log\";\nexport { AzureMonitorStatsbeatExporter } from \"./export/statsbeat/statsbeatExporter\";\nexport { AzureMonitorExporterOptions } from \"./config\";\nexport { ServiceApiVersion } from \"./Declarations/Constants\";\nexport {\n ApplicationInsightsClientOptionalParams,\n MonitorBase,\n MonitorDomain,\n TelemetryItem,\n} from \"./generated/models\";\n"]}
|
|
@@ -10,7 +10,7 @@ let instance = null;
|
|
|
10
10
|
* Azure Telemetry context.
|
|
11
11
|
* @internal
|
|
12
12
|
*/
|
|
13
|
-
|
|
13
|
+
class Context {
|
|
14
14
|
constructor() {
|
|
15
15
|
this.tags = {};
|
|
16
16
|
this._loadDeviceContext();
|
|
@@ -24,14 +24,22 @@ export class Context {
|
|
|
24
24
|
[Context.nodeVersion] = node.split(".");
|
|
25
25
|
Context.opentelemetryVersion = SDK_INFO[SemanticResourceAttributes.TELEMETRY_SDK_VERSION];
|
|
26
26
|
Context.sdkVersion = ai.packageVersion;
|
|
27
|
-
|
|
27
|
+
let prefix = process.env["AZURE_MONITOR_AGENT_PREFIX"]
|
|
28
|
+
? process.env["AZURE_MONITOR_AGENT_PREFIX"]
|
|
29
|
+
: "";
|
|
30
|
+
let version = process.env["AZURE_MONITOR_DISTRO_VERSION"]
|
|
31
|
+
? `dst${process.env["AZURE_MONITOR_DISTRO_VERSION"]}`
|
|
32
|
+
: `ext${Context.sdkVersion}`;
|
|
33
|
+
let internalSdkVersion = `${prefix}node${Context.nodeVersion}:otel${Context.opentelemetryVersion}:${version}`;
|
|
34
|
+
this.tags[KnownContextTagKeys.AiInternalSdkVersion] = internalSdkVersion;
|
|
28
35
|
}
|
|
29
36
|
}
|
|
30
37
|
Context.sdkVersion = null;
|
|
31
38
|
Context.opentelemetryVersion = null;
|
|
32
39
|
Context.nodeVersion = "";
|
|
40
|
+
export { Context };
|
|
33
41
|
/**
|
|
34
|
-
* Singleton Context instance
|
|
42
|
+
* Singleton Context instance
|
|
35
43
|
* @internal
|
|
36
44
|
*/
|
|
37
45
|
export function getInstance() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/context/context.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAC;AAEjF,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,KAAK,EAAE,MAAM,8CAA8C,CAAC;AAGnE,IAAI,QAAQ,GAAmB,IAAI,CAAC;AAEpC;;;GAGG;AACH,
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/context/context.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAqC,CAAC;AAEjF,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,KAAK,EAAE,MAAM,8CAA8C,CAAC;AAGnE,IAAI,QAAQ,GAAmB,IAAI,CAAC;AAEpC;;;GAGG;AACH,MAAa,OAAO;IASlB;QACE,IAAI,CAAC,IAAI,GAAG,EAAE,CAAC;QACf,IAAI,CAAC,kBAAkB,EAAE,CAAC;QAC1B,IAAI,CAAC,oBAAoB,EAAE,CAAC;IAC9B,CAAC;IAEO,kBAAkB;QACxB,IAAI,CAAC,IAAI,CAAC,mBAAmB,CA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AAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as os from \"os\";\nimport { SDK_INFO } from \"@opentelemetry/core\";\nimport { SemanticResourceAttributes } from \"@opentelemetry/semantic-conventions\";\n\nimport { KnownContextTagKeys } from \"../../../generated\";\nimport * as ai from \"../../../utils/constants/applicationinsights\";\nimport { Tags } from \"../../../types\";\n\nlet instance: Context | null = null;\n\n/**\n * Azure Telemetry context.\n * @internal\n */\nexport class Context {\n public tags: Tags;\n\n public static sdkVersion: string | null = null;\n\n public static opentelemetryVersion: string | null = null;\n\n public static nodeVersion: string = \"\";\n\n constructor() {\n this.tags = {};\n this._loadDeviceContext();\n this._loadInternalContext();\n }\n\n private _loadDeviceContext(): void {\n this.tags[KnownContextTagKeys.AiDeviceOsVersion] = os && `${os.type()} ${os.release()}`;\n }\n\n private _loadInternalContext(): void {\n const { node } = process.versions;\n [Context.nodeVersion] = node.split(\".\");\n Context.opentelemetryVersion = SDK_INFO[SemanticResourceAttributes.TELEMETRY_SDK_VERSION];\n Context.sdkVersion = ai.packageVersion;\n\n let prefix = process.env[\"AZURE_MONITOR_AGENT_PREFIX\"]\n ? process.env[\"AZURE_MONITOR_AGENT_PREFIX\"]\n : \"\";\n let version = process.env[\"AZURE_MONITOR_DISTRO_VERSION\"]\n ? `dst${process.env[\"AZURE_MONITOR_DISTRO_VERSION\"]}`\n : `ext${Context.sdkVersion}`;\n let internalSdkVersion = `${prefix}node${Context.nodeVersion}:otel${Context.opentelemetryVersion}:${version}`;\n this.tags[KnownContextTagKeys.AiInternalSdkVersion] = internalSdkVersion;\n }\n}\n\n/**\n * Singleton Context instance\n * @internal\n */\nexport function getInstance(): Context {\n if (!instance) {\n instance = new Context();\n }\n return instance;\n}\n"]}
|
|
@@ -4,7 +4,7 @@ import * as fs from "fs";
|
|
|
4
4
|
import * as os from "os";
|
|
5
5
|
import * as child_process from "child_process";
|
|
6
6
|
import { diag } from "@opentelemetry/api";
|
|
7
|
-
|
|
7
|
+
class FileAccessControl {
|
|
8
8
|
// Check if file access control could be enabled
|
|
9
9
|
static checkFileProtection() {
|
|
10
10
|
if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION &&
|
|
@@ -168,4 +168,5 @@ FileAccessControl.ACL_IDENTITY = null;
|
|
|
168
168
|
FileAccessControl.OS_FILE_PROTECTION_CHECKED = false;
|
|
169
169
|
FileAccessControl.OS_PROVIDES_FILE_PROTECTION = false;
|
|
170
170
|
FileAccessControl.USE_ICACLS = os.type() === "Windows_NT";
|
|
171
|
+
export { FileAccessControl };
|
|
171
172
|
//# sourceMappingURL=fileAccessControl.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileAccessControl.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileAccessControl.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,aAAa,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,MAAM,OAAO,iBAAiB;IAS5B,gDAAgD;IACzC,MAAM,CAAC,mBAAmB;QAC/B,IACE,CAAC,iBAAiB,CAAC,2BAA2B;YAC9C,CAAC,iBAAiB,CAAC,0BAA0B,EAC7C;YACA,iBAAiB,CAAC,0BAA0B,GAAG,IAAI,CAAC;YACpD,2EAA2E;YAC3E,4EAA4E;YAC5E,8DAA8D;YAC9D,IAAI,iBAAiB,CAAC,UAAU,EAAE;gBAChC,2EAA2E;gBAC3E,yEAAyE;gBACzE,IAAI;oBACF,iBAAiB,CAAC,2BAA2B,GAAG,EAAE,CAAC,UAAU,CAC3D,iBAAiB,CAAC,WAAW,CAC9B,CAAC;iBACH;gBAAC,OAAO,CAAM,EAAE;oBACf,eAAe;iBAChB;gBACD,IAAI,CAAC,iBAAiB,CAAC,2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8B,EAAE,CAAC;AAClD,8BAAY,GAAkB,IAAI,CAAC;AACnC,4CAA0B,GAAG,KAAK,CAAC;AACpC,6CAA2B,GAAG,KAAK,CAAC;AACpC,4BAAU,GAAG,EAAE,CAAC,IAAI,EAAE,KAAK,YAAY,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as os from \"os\";\nimport * as child_process from \"child_process\";\nimport { diag } from \"@opentelemetry/api\";\n\nexport class FileAccessControl {\n private static ICACLS_PATH = `${process.env.systemdrive}/windows/system32/icacls.exe`;\n private static POWERSHELL_PATH = `${process.env.systemdrive}/windows/system32/windowspowershell/v1.0/powershell.exe`;\n private static ACLED_DIRECTORIES: { [id: string]: boolean } = {};\n private static ACL_IDENTITY: string | null = null;\n private static OS_FILE_PROTECTION_CHECKED = false;\n public static OS_PROVIDES_FILE_PROTECTION = false;\n public static USE_ICACLS = os.type() === \"Windows_NT\";\n\n // Check if file access control could be enabled\n public static checkFileProtection() {\n if (\n !FileAccessControl.OS_PROVIDES_FILE_PROTECTION &&\n !FileAccessControl.OS_FILE_PROTECTION_CHECKED\n ) {\n FileAccessControl.OS_FILE_PROTECTION_CHECKED = true;\n // Node's chmod levels do not appropriately restrict file access on Windows\n // Use the built-in command line tool ICACLS on Windows to properly restrict\n // access to the temporary directory used for disk retry mode.\n if (FileAccessControl.USE_ICACLS) {\n // This should be async - but it's currently safer to have this synchronous\n // This guarantees we can immediately fail setDiskRetryMode if we need to\n try {\n FileAccessControl.OS_PROVIDES_FILE_PROTECTION = fs.existsSync(\n FileAccessControl.ICACLS_PATH\n );\n } catch (e: any) {\n // Ignore error\n }\n if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {\n diag.warn(\n \"Could not find ICACLS in expected location! This is necessary to use disk retry mode on Windows.\"\n );\n }\n } else {\n // chmod works everywhere else\n FileAccessControl.OS_PROVIDES_FILE_PROTECTION = true;\n }\n }\n }\n\n public static async applyACLRules(directory: string): Promise<void> {\n if (FileAccessControl.USE_ICACLS) {\n if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {\n // Avoid multiple calls race condition by setting ACLED_DIRECTORIES to false for this directory immediately\n // If batches are being failed faster than the processes spawned below return, some data won't be stored to disk\n // This is better than the alternative of potentially infinitely spawned processes\n FileAccessControl.ACLED_DIRECTORIES[directory] = false;\n try {\n // Restrict this directory to only current user and administrator access\n let identity = await this._getACLIdentity();\n await this._runICACLS(this._getACLArguments(directory, identity));\n FileAccessControl.ACLED_DIRECTORIES[directory] = true;\n } catch (ex: any) {\n FileAccessControl.ACLED_DIRECTORIES[directory] = false; // false is used to cache failed (vs undefined which is \"not yet tried\")\n throw ex;\n }\n } else {\n if (!FileAccessControl.ACLED_DIRECTORIES[directory]) {\n throw new Error(\"Setting ACL restrictions did not succeed (cached result)\");\n }\n }\n }\n }\n\n public static applyACLRulesSync(directory: string) {\n if (FileAccessControl.USE_ICACLS) {\n // For performance, only run ACL rules if we haven't already during this session\n if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {\n this._runICACLSSync(this._getACLArguments(directory, this._getACLIdentitySync()));\n FileAccessControl.ACLED_DIRECTORIES[directory] = true; // If we get here, it succeeded. _runIACLSSync will throw on failures\n return;\n } else if (!FileAccessControl.ACLED_DIRECTORIES[directory]) {\n // falsy but not undefined\n throw new Error(\"Setting ACL restrictions did not succeed (cached result)\");\n }\n }\n }\n\n private static _runICACLS(args: string[]): Promise<void> {\n return new Promise((resolve, reject) => {\n var aclProc = child_process.spawn(FileAccessControl.ICACLS_PATH, args, <any>{\n windowsHide: true,\n });\n aclProc.on(\"error\", (e: Error) => reject(e));\n aclProc.on(\"close\", (code: number) => {\n if (code === 0) {\n resolve();\n } else {\n reject(\n new Error(`Setting ACL restrictions did not succeed (ICACLS returned code ${code})`)\n );\n }\n });\n });\n }\n\n private static _runICACLSSync(args: string[]) {\n // Some very old versions of Node (< 0.11) don't have this\n if (child_process.spawnSync) {\n var aclProc = child_process.spawnSync(FileAccessControl.ICACLS_PATH, args, <any>{\n windowsHide: true,\n });\n if (aclProc.error) {\n throw aclProc.error;\n } else if (aclProc.status !== 0) {\n throw new Error(\n `Setting ACL restrictions did not succeed (ICACLS returned code ${aclProc.status})`\n );\n }\n } else {\n throw new Error(\"Could not synchronously call ICACLS under current version of Node.js\");\n }\n }\n\n private static _getACLIdentity(): Promise<string> {\n return new Promise((resolve, reject) => {\n if (FileAccessControl.ACL_IDENTITY) {\n resolve(FileAccessControl.ACL_IDENTITY);\n }\n var psProc = child_process.spawn(\n FileAccessControl.POWERSHELL_PATH,\n [\"-Command\", \"[System.Security.Principal.WindowsIdentity]::GetCurrent().Name\"],\n <any>{\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"], // Needed to prevent hanging on Win 7\n }\n );\n let data = \"\";\n psProc.stdout.on(\"data\", (d: string) => (data += d));\n psProc.on(\"error\", (e: Error) => reject(e));\n psProc.on(\"close\", (code: number) => {\n FileAccessControl.ACL_IDENTITY = data && data.trim();\n if (code === 0) {\n resolve(FileAccessControl.ACL_IDENTITY);\n } else {\n reject(new Error(`Getting ACL identity did not succeed (PS returned code ${code})`));\n }\n });\n });\n }\n\n private static _getACLIdentitySync() {\n if (FileAccessControl.ACL_IDENTITY) {\n return FileAccessControl.ACL_IDENTITY;\n }\n // Some very old versions of Node (< 0.11) don't have this\n if (child_process.spawnSync) {\n var psProc = child_process.spawnSync(\n FileAccessControl.POWERSHELL_PATH,\n [\"-Command\", \"[System.Security.Principal.WindowsIdentity]::GetCurrent().Name\"],\n <any>{\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"], // Needed to prevent hanging on Win 7\n }\n );\n if (psProc.error) {\n throw psProc.error;\n } else if (psProc.status !== 0) {\n throw new Error(`Getting ACL identity did not succeed (PS returned code ${psProc.status})`);\n }\n FileAccessControl.ACL_IDENTITY = psProc.stdout && psProc.stdout.toString().trim();\n return FileAccessControl.ACL_IDENTITY;\n } else {\n throw new Error(\"Could not synchronously get ACL identity under current version of Node.js\");\n }\n }\n\n private static _getACLArguments(directory: string, identity: string) {\n return [\n directory,\n \"/grant\",\n \"*S-1-5-32-544:(OI)(CI)F\", // Full permission for Administrators\n \"/grant\",\n `${identity}:(OI)(CI)F`, // Full permission for current user\n \"/inheritance:r\",\n ]; // Remove all inherited permissions\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fileAccessControl.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileAccessControl.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,aAAa,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,MAAa,iBAAiB;IAS5B,gDAAgD;IACzC,MAAM,CAAC,mBAAmB;QAC/B,IACE,CAAC,iBAAiB,CAAC,2BAA2B;YAC9C,CAAC,iBAAiB,CAAC,0BAA0B,EAC7C;YACA,iBAAiB,CAAC,0BAA0B,GAAG,IAAI,CAAC;YACpD,2EAA2E;YAC3E,4EAA4E;YAC5E,8DAA8D;YAC9D,IAAI,iBAAiB,CAAC,UAAU,EAAE;gBAChC,2EAA2E;gBAC3E,yEAAyE;gBACzE,IAAI;oBACF,iBAAiB,CAAC,2BAA2B,GAAG,EAAE,CAAC,UAAU,CAC3D,iBAAiB,CAAC,WAAW,CAC9B,CAAC;iBACH;gBAAC,OAAO,CAAM,EAAE;oBACf,eAAe;iBAChB;gBACD,IAAI,CAAC,iBAAiB,CAAC,2BAA2B,EAAE;oBAClD,IAAI,CAAC,IAAI,CACP,kGAAkG,CACnG,CAAC;iBACH;aACF;iBAAM;gBACL,8BAA8B;gBAC9B,iBAAiB,CAAC,2BAA2B,GAAG,IAAI,CAAC;aACtD;SACF;IACH,CAAC;IAEM,MAAM,CAAC,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AiB","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as os from \"os\";\nimport * as child_process from \"child_process\";\nimport { diag } from \"@opentelemetry/api\";\n\nexport class FileAccessControl {\n private static ICACLS_PATH = `${process.env.systemdrive}/windows/system32/icacls.exe`;\n private static POWERSHELL_PATH = `${process.env.systemdrive}/windows/system32/windowspowershell/v1.0/powershell.exe`;\n private static ACLED_DIRECTORIES: { [id: string]: boolean } = {};\n private static ACL_IDENTITY: string | null = null;\n private static OS_FILE_PROTECTION_CHECKED = false;\n public static OS_PROVIDES_FILE_PROTECTION = false;\n public static USE_ICACLS = os.type() === \"Windows_NT\";\n\n // Check if file access control could be enabled\n public static checkFileProtection() {\n if (\n !FileAccessControl.OS_PROVIDES_FILE_PROTECTION &&\n !FileAccessControl.OS_FILE_PROTECTION_CHECKED\n ) {\n FileAccessControl.OS_FILE_PROTECTION_CHECKED = true;\n // Node's chmod levels do not appropriately restrict file access on Windows\n // Use the built-in command line tool ICACLS on Windows to properly restrict\n // access to the temporary directory used for disk retry mode.\n if (FileAccessControl.USE_ICACLS) {\n // This should be async - but it's currently safer to have this synchronous\n // This guarantees we can immediately fail setDiskRetryMode if we need to\n try {\n FileAccessControl.OS_PROVIDES_FILE_PROTECTION = fs.existsSync(\n FileAccessControl.ICACLS_PATH\n );\n } catch (e: any) {\n // Ignore error\n }\n if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {\n diag.warn(\n \"Could not find ICACLS in expected location! This is necessary to use disk retry mode on Windows.\"\n );\n }\n } else {\n // chmod works everywhere else\n FileAccessControl.OS_PROVIDES_FILE_PROTECTION = true;\n }\n }\n }\n\n public static async applyACLRules(directory: string): Promise<void> {\n if (FileAccessControl.USE_ICACLS) {\n if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {\n // Avoid multiple calls race condition by setting ACLED_DIRECTORIES to false for this directory immediately\n // If batches are being failed faster than the processes spawned below return, some data won't be stored to disk\n // This is better than the alternative of potentially infinitely spawned processes\n FileAccessControl.ACLED_DIRECTORIES[directory] = false;\n try {\n // Restrict this directory to only current user and administrator access\n let identity = await this._getACLIdentity();\n await this._runICACLS(this._getACLArguments(directory, identity));\n FileAccessControl.ACLED_DIRECTORIES[directory] = true;\n } catch (ex: any) {\n FileAccessControl.ACLED_DIRECTORIES[directory] = false; // false is used to cache failed (vs undefined which is \"not yet tried\")\n throw ex;\n }\n } else {\n if (!FileAccessControl.ACLED_DIRECTORIES[directory]) {\n throw new Error(\"Setting ACL restrictions did not succeed (cached result)\");\n }\n }\n }\n }\n\n public static applyACLRulesSync(directory: string) {\n if (FileAccessControl.USE_ICACLS) {\n // For performance, only run ACL rules if we haven't already during this session\n if (FileAccessControl.ACLED_DIRECTORIES[directory] === undefined) {\n this._runICACLSSync(this._getACLArguments(directory, this._getACLIdentitySync()));\n FileAccessControl.ACLED_DIRECTORIES[directory] = true; // If we get here, it succeeded. _runIACLSSync will throw on failures\n return;\n } else if (!FileAccessControl.ACLED_DIRECTORIES[directory]) {\n // falsy but not undefined\n throw new Error(\"Setting ACL restrictions did not succeed (cached result)\");\n }\n }\n }\n\n private static _runICACLS(args: string[]): Promise<void> {\n return new Promise((resolve, reject) => {\n var aclProc = child_process.spawn(FileAccessControl.ICACLS_PATH, args, <any>{\n windowsHide: true,\n });\n aclProc.on(\"error\", (e: Error) => reject(e));\n aclProc.on(\"close\", (code: number) => {\n if (code === 0) {\n resolve();\n } else {\n reject(\n new Error(`Setting ACL restrictions did not succeed (ICACLS returned code ${code})`)\n );\n }\n });\n });\n }\n\n private static _runICACLSSync(args: string[]) {\n // Some very old versions of Node (< 0.11) don't have this\n if (child_process.spawnSync) {\n var aclProc = child_process.spawnSync(FileAccessControl.ICACLS_PATH, args, <any>{\n windowsHide: true,\n });\n if (aclProc.error) {\n throw aclProc.error;\n } else if (aclProc.status !== 0) {\n throw new Error(\n `Setting ACL restrictions did not succeed (ICACLS returned code ${aclProc.status})`\n );\n }\n } else {\n throw new Error(\"Could not synchronously call ICACLS under current version of Node.js\");\n }\n }\n\n private static _getACLIdentity(): Promise<string> {\n return new Promise((resolve, reject) => {\n if (FileAccessControl.ACL_IDENTITY) {\n resolve(FileAccessControl.ACL_IDENTITY);\n }\n var psProc = child_process.spawn(\n FileAccessControl.POWERSHELL_PATH,\n [\"-Command\", \"[System.Security.Principal.WindowsIdentity]::GetCurrent().Name\"],\n <any>{\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"], // Needed to prevent hanging on Win 7\n }\n );\n let data = \"\";\n psProc.stdout.on(\"data\", (d: string) => (data += d));\n psProc.on(\"error\", (e: Error) => reject(e));\n psProc.on(\"close\", (code: number) => {\n FileAccessControl.ACL_IDENTITY = data && data.trim();\n if (code === 0) {\n resolve(FileAccessControl.ACL_IDENTITY);\n } else {\n reject(new Error(`Getting ACL identity did not succeed (PS returned code ${code})`));\n }\n });\n });\n }\n\n private static _getACLIdentitySync() {\n if (FileAccessControl.ACL_IDENTITY) {\n return FileAccessControl.ACL_IDENTITY;\n }\n // Some very old versions of Node (< 0.11) don't have this\n if (child_process.spawnSync) {\n var psProc = child_process.spawnSync(\n FileAccessControl.POWERSHELL_PATH,\n [\"-Command\", \"[System.Security.Principal.WindowsIdentity]::GetCurrent().Name\"],\n <any>{\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"], // Needed to prevent hanging on Win 7\n }\n );\n if (psProc.error) {\n throw psProc.error;\n } else if (psProc.status !== 0) {\n throw new Error(`Getting ACL identity did not succeed (PS returned code ${psProc.status})`);\n }\n FileAccessControl.ACL_IDENTITY = psProc.stdout && psProc.stdout.toString().trim();\n return FileAccessControl.ACL_IDENTITY;\n } else {\n throw new Error(\"Could not synchronously get ACL identity under current version of Node.js\");\n }\n }\n\n private static _getACLArguments(directory: string, identity: string) {\n return [\n directory,\n \"/grant\",\n \"*S-1-5-32-544:(OI)(CI)F\", // Full permission for Administrators\n \"/grant\",\n `${identity}:(OI)(CI)F`, // Full permission for current user\n \"/inheritance:r\",\n ]; // Remove all inherited permissions\n }\n}\n"]}
|
|
@@ -16,7 +16,7 @@ const writeFileAsync = promisify(fs.writeFile);
|
|
|
16
16
|
* File system persist class.
|
|
17
17
|
* @internal
|
|
18
18
|
*/
|
|
19
|
-
|
|
19
|
+
class FileSystemPersist {
|
|
20
20
|
constructor(instrumentationKey, _options) {
|
|
21
21
|
var _a, _b;
|
|
22
22
|
this._options = _options;
|
|
@@ -176,4 +176,5 @@ export class FileSystemPersist {
|
|
|
176
176
|
}
|
|
177
177
|
FileSystemPersist.TEMPDIR_PREFIX = "ot-azure-exporter-";
|
|
178
178
|
FileSystemPersist.FILENAME_SUFFIX = ".ai.json";
|
|
179
|
+
export { FileSystemPersist };
|
|
179
180
|
//# sourceMappingURL=fileSystemPersist.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileSystemPersist.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemPersist.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAChF,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAGjC,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACrC,MAAM,YAAY,GAAG,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC;AAC3C,MAAM,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;AAC7C,MAAM,W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AAM,CAAC,CAAC,CAAC,EAAE,EAAE,CACnC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAC7D,CAAC;gBACF,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;oBACtB,OAAO,KAAK,CAAC;iBACd;qBAAM;oBACL,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;wBAC3B,mBAAmB;wBACnB,MAAM,gBAAgB,GAAS,IAAI,IAAI,CACrC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAC3D,CAAC;wBACF,MAAM,OAAO,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,EAAE,GAAG,IAAI,CAAC,oBAAoB,CAAC,GAAG,gBAAgB,CAAC;wBACrF,IAAI,OAAO,EAAE;4BACX,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;4BACtD,MAAM,WAAW,CAAC,QAAQ,CAAC,CAAC;yBAC7B;oBACH,CAAC,CAAC,CAAC;oBACH,OAAO,IAAI,CAAC;iBACb;aACF;YACD,OAAO,KAAK,CAAC;SACd;QAAC,OAAO,KAAU,EAAE;YACnB,IAAI,CAAC,IAAI,CAAC,yDAAyD,EAAE,KAAK,CAAC,CAAC;YAC5E,OAAO,KAAK,CAAC;SACd;IACH,CAAC;;AAnLM,gCAAc,GAAG,oBAAoB,CAAC;AACtC,iCAAe,GAAG,UAAU,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\nimport { diag } from \"@opentelemetry/api\";\nimport { PersistentStorage } from \"../../../types\";\nimport { FileAccessControl } from \"./fileAccessControl\";\nimport { confirmDirExists, getShallowDirectorySize } from \"./fileSystemHelpers\";\nimport { promisify } from \"util\";\nimport { AzureMonitorExporterOptions } from \"../../../config\";\n\nconst statAsync = promisify(fs.stat);\nconst readdirAsync = promisify(fs.readdir);\nconst readFileAsync = promisify(fs.readFile);\nconst unlinkAsync = promisify(fs.unlink);\nconst writeFileAsync = promisify(fs.writeFile);\n\n/**\n * File system persist class.\n * @internal\n */\nexport class FileSystemPersist implements PersistentStorage {\n static TEMPDIR_PREFIX = \"ot-azure-exporter-\";\n static FILENAME_SUFFIX = \".ai.json\";\n\n fileRetemptionPeriod = 2 * 24 * 60 * 60 * 1000; // 2 days\n cleanupTimeOut = 60 * 60 * 1000; // 1 hour\n maxBytesOnDisk: number = 50_000_000; // ~50MB\n\n private _enabled: boolean;\n private _tempDirectory: string = \"\";\n private _fileCleanupTimer: NodeJS.Timer | null = null;\n private _instrumentationKey: string;\n\n constructor(instrumentationKey: string, private _options?: AzureMonitorExporterOptions) {\n this._instrumentationKey = instrumentationKey;\n if (this._options?.disableOfflineStorage) {\n this._enabled = false;\n return;\n }\n this._enabled = true;\n FileAccessControl.checkFileProtection();\n\n if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {\n this._enabled = false;\n diag.error(\n \"Sufficient file protection capabilities were not detected. Files will not be persisted\"\n );\n }\n\n if (!this._instrumentationKey) {\n this._enabled = false;\n diag.error(\n `No instrumentation key was provided to FileSystemPersister. Files will not be persisted`\n );\n }\n if (this._enabled) {\n this._tempDirectory = path.join(\n this._options?.storageDirectory || os.tmpdir(),\n \"Microsoft\",\n \"AzureMonitor\",\n FileSystemPersist.TEMPDIR_PREFIX + this._instrumentationKey\n );\n\n // Starts file cleanup task\n if (!this._fileCleanupTimer) {\n this._fileCleanupTimer = setTimeout(() => {\n this._fileCleanupTask();\n }, this.cleanupTimeOut);\n this._fileCleanupTimer.unref();\n }\n }\n }\n\n push(value: unknown[]): Promise<boolean> {\n if (this._enabled) {\n diag.debug(\"Pushing value to persistent storage\", value.toString());\n return this._storeToDisk(JSON.stringify(value));\n }\n return new Promise((resolve) => {\n resolve(false);\n });\n }\n\n async shift(): Promise<unknown> {\n if (this._enabled) {\n diag.debug(\"Searching for filesystem persisted files\");\n try {\n const buffer = await this._getFirstFileOnDisk();\n if (buffer) {\n return JSON.parse(buffer.toString(\"utf8\"));\n }\n } catch (e: any) {\n diag.debug(\"Failed to read persisted file\", e);\n }\n return null;\n }\n return new Promise((resolve) => {\n resolve(null);\n });\n }\n\n /**\n * Check for temp telemetry files\n * reads the first file if exist, deletes it and tries to send its load\n */\n private async _getFirstFileOnDisk(): Promise<Buffer | null> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX)\n );\n if (files.length === 0) {\n return null;\n } else {\n const firstFile = files[0];\n const filePath = path.join(this._tempDirectory, firstFile);\n const payload = await readFileAsync(filePath);\n // delete the file first to prevent double sending\n await unlinkAsync(filePath);\n return payload;\n }\n }\n return null;\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n // File does not exist -- return null instead of throwing\n return null;\n } else {\n throw e;\n }\n }\n }\n\n private async _storeToDisk(payload: string): Promise<boolean> {\n try {\n await confirmDirExists(this._tempDirectory);\n } catch (error: any) {\n diag.warn(`Error while checking/creating directory: `, error && error.message);\n return false;\n }\n\n try {\n const size = await getShallowDirectorySize(this._tempDirectory);\n if (size > this.maxBytesOnDisk) {\n diag.warn(\n `Not saving data due to max size limit being met. Directory size in bytes is: ${size}`\n );\n return false;\n }\n } catch (error: any) {\n diag.warn(`Error while checking size of persistence directory: `, error && error.message);\n return false;\n }\n\n const fileName = `${new Date().getTime()}${FileSystemPersist.FILENAME_SUFFIX}`;\n const fileFullPath = path.join(this._tempDirectory, fileName);\n\n // Mode 600 is w/r for creator and no read access for others\n diag.info(`saving data to disk at: ${fileFullPath}`);\n try {\n await writeFileAsync(fileFullPath, payload, { mode: 0o600 });\n } catch (writeError: any) {\n diag.warn(`Error writing file to persistent file storage`, writeError);\n return false;\n }\n return true;\n }\n\n private async _fileCleanupTask(): Promise<boolean> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX)\n );\n if (files.length === 0) {\n return false;\n } else {\n files.forEach(async (file) => {\n // Check expiration\n const fileCreationDate: Date = new Date(\n parseInt(file.split(FileSystemPersist.FILENAME_SUFFIX)[0])\n );\n const expired = new Date(+new Date() - this.fileRetemptionPeriod) > fileCreationDate;\n if (expired) {\n const filePath = path.join(this._tempDirectory, file);\n await unlinkAsync(filePath);\n }\n });\n return true;\n }\n }\n return false;\n } catch (error: any) {\n diag.info(`Failed cleanup of persistent file storage expired files`, error);\n return false;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fileSystemPersist.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemPersist.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAChF,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAGjC,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACrC,MAAM,YAAY,GAAG,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC;AAC3C,MAAM,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC,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M,KAAK,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CACnC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAC7D,CAAC;gBACF,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;oBACtB,OAAO,KAAK,CAAC;iBACd;qBAAM;oBACL,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;wBAC3B,mBAAmB;wBACnB,MAAM,gBAAgB,GAAS,IAAI,IAAI,CACrC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,CAC3D,CAAC;wBACF,MAAM,OAAO,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,EAAE,GAAG,IAAI,CAAC,oBAAoB,CAAC,GAAG,gBAAgB,CAAC;wBACrF,IAAI,OAAO,EAAE;4BACX,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;4BACtD,MAAM,WAAW,CAAC,QAAQ,CAAC,CAAC;yBAC7B;oBACH,CAAC,CAAC,CAAC;oBACH,OAAO,IAAI,CAAC;iBACb;aACF;YACD,OAAO,KAAK,CAAC;SACd;QAAC,OAAO,KAAU,EAAE;YACnB,IAAI,CAAC,IAAI,CAAC,yDAAyD,EAAE,KAAK,CAAC,CAAC;YAC5E,OAAO,KAAK,CAAC;SACd;IACH,CAAC;;AAnLM,gCAAc,GAAG,oBAAoB,AAAvB,CAAwB;AACtC,iCAAe,GAAG,UAAU,AAAb,CAAc;SAFzB,iBAAiB","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as os from \"os\";\nimport * as path from \"path\";\nimport { diag } from \"@opentelemetry/api\";\nimport { PersistentStorage } from \"../../../types\";\nimport { FileAccessControl } from \"./fileAccessControl\";\nimport { confirmDirExists, getShallowDirectorySize } from \"./fileSystemHelpers\";\nimport { promisify } from \"util\";\nimport { AzureMonitorExporterOptions } from \"../../../config\";\n\nconst statAsync = promisify(fs.stat);\nconst readdirAsync = promisify(fs.readdir);\nconst readFileAsync = promisify(fs.readFile);\nconst unlinkAsync = promisify(fs.unlink);\nconst writeFileAsync = promisify(fs.writeFile);\n\n/**\n * File system persist class.\n * @internal\n */\nexport class FileSystemPersist implements PersistentStorage {\n static TEMPDIR_PREFIX = \"ot-azure-exporter-\";\n static FILENAME_SUFFIX = \".ai.json\";\n\n fileRetemptionPeriod = 2 * 24 * 60 * 60 * 1000; // 2 days\n cleanupTimeOut = 60 * 60 * 1000; // 1 hour\n maxBytesOnDisk: number = 50_000_000; // ~50MB\n\n private _enabled: boolean;\n private _tempDirectory: string = \"\";\n private _fileCleanupTimer: NodeJS.Timer | null = null;\n private _instrumentationKey: string;\n\n constructor(instrumentationKey: string, private _options?: AzureMonitorExporterOptions) {\n this._instrumentationKey = instrumentationKey;\n if (this._options?.disableOfflineStorage) {\n this._enabled = false;\n return;\n }\n this._enabled = true;\n FileAccessControl.checkFileProtection();\n\n if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {\n this._enabled = false;\n diag.error(\n \"Sufficient file protection capabilities were not detected. Files will not be persisted\"\n );\n }\n\n if (!this._instrumentationKey) {\n this._enabled = false;\n diag.error(\n `No instrumentation key was provided to FileSystemPersister. Files will not be persisted`\n );\n }\n if (this._enabled) {\n this._tempDirectory = path.join(\n this._options?.storageDirectory || os.tmpdir(),\n \"Microsoft\",\n \"AzureMonitor\",\n FileSystemPersist.TEMPDIR_PREFIX + this._instrumentationKey\n );\n\n // Starts file cleanup task\n if (!this._fileCleanupTimer) {\n this._fileCleanupTimer = setTimeout(() => {\n this._fileCleanupTask();\n }, this.cleanupTimeOut);\n this._fileCleanupTimer.unref();\n }\n }\n }\n\n push(value: unknown[]): Promise<boolean> {\n if (this._enabled) {\n diag.debug(\"Pushing value to persistent storage\", value.toString());\n return this._storeToDisk(JSON.stringify(value));\n }\n return new Promise((resolve) => {\n resolve(false);\n });\n }\n\n async shift(): Promise<unknown> {\n if (this._enabled) {\n diag.debug(\"Searching for filesystem persisted files\");\n try {\n const buffer = await this._getFirstFileOnDisk();\n if (buffer) {\n return JSON.parse(buffer.toString(\"utf8\"));\n }\n } catch (e: any) {\n diag.debug(\"Failed to read persisted file\", e);\n }\n return null;\n }\n return new Promise((resolve) => {\n resolve(null);\n });\n }\n\n /**\n * Check for temp telemetry files\n * reads the first file if exist, deletes it and tries to send its load\n */\n private async _getFirstFileOnDisk(): Promise<Buffer | null> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX)\n );\n if (files.length === 0) {\n return null;\n } else {\n const firstFile = files[0];\n const filePath = path.join(this._tempDirectory, firstFile);\n const payload = await readFileAsync(filePath);\n // delete the file first to prevent double sending\n await unlinkAsync(filePath);\n return payload;\n }\n }\n return null;\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n // File does not exist -- return null instead of throwing\n return null;\n } else {\n throw e;\n }\n }\n }\n\n private async _storeToDisk(payload: string): Promise<boolean> {\n try {\n await confirmDirExists(this._tempDirectory);\n } catch (error: any) {\n diag.warn(`Error while checking/creating directory: `, error && error.message);\n return false;\n }\n\n try {\n const size = await getShallowDirectorySize(this._tempDirectory);\n if (size > this.maxBytesOnDisk) {\n diag.warn(\n `Not saving data due to max size limit being met. Directory size in bytes is: ${size}`\n );\n return false;\n }\n } catch (error: any) {\n diag.warn(`Error while checking size of persistence directory: `, error && error.message);\n return false;\n }\n\n const fileName = `${new Date().getTime()}${FileSystemPersist.FILENAME_SUFFIX}`;\n const fileFullPath = path.join(this._tempDirectory, fileName);\n\n // Mode 600 is w/r for creator and no read access for others\n diag.info(`saving data to disk at: ${fileFullPath}`);\n try {\n await writeFileAsync(fileFullPath, payload, { mode: 0o600 });\n } catch (writeError: any) {\n diag.warn(`Error writing file to persistent file storage`, writeError);\n return false;\n }\n return true;\n }\n\n private async _fileCleanupTask(): Promise<boolean> {\n try {\n const stats = await statAsync(this._tempDirectory);\n if (stats.isDirectory()) {\n const origFiles = await readdirAsync(this._tempDirectory);\n const files = origFiles.filter((f) =>\n path.basename(f).includes(FileSystemPersist.FILENAME_SUFFIX)\n );\n if (files.length === 0) {\n return false;\n } else {\n files.forEach(async (file) => {\n // Check expiration\n const fileCreationDate: Date = new Date(\n parseInt(file.split(FileSystemPersist.FILENAME_SUFFIX)[0])\n );\n const expired = new Date(+new Date() - this.fileRetemptionPeriod) > fileCreationDate;\n if (expired) {\n const filePath = path.join(this._tempDirectory, file);\n await unlinkAsync(filePath);\n }\n });\n return true;\n }\n }\n return false;\n } catch (error: any) {\n diag.info(`Failed cleanup of persistent file storage expired files`, error);\n return false;\n }\n }\n}\n"]}
|