@azure/monitor-opentelemetry-exporter 1.0.0-beta.7 → 1.0.0-beta.9
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/README.md +47 -9
- package/dist/index.js +656 -261
- package/dist-esm/src/config.js +1 -14
- package/dist-esm/src/config.js.map +1 -1
- package/dist-esm/src/export/base.js +174 -0
- package/dist-esm/src/export/base.js.map +1 -0
- package/dist-esm/src/export/metric.js +64 -0
- package/dist-esm/src/export/metric.js.map +1 -0
- package/dist-esm/src/export/trace.js +25 -146
- package/dist-esm/src/export/trace.js.map +1 -1
- package/dist-esm/src/generated/applicationInsightsClient.js +36 -3
- package/dist-esm/src/generated/applicationInsightsClient.js.map +1 -1
- package/dist-esm/src/generated/index.js +0 -1
- package/dist-esm/src/generated/index.js.map +1 -1
- package/dist-esm/src/generated/models/index.js +35 -0
- package/dist-esm/src/generated/models/index.js.map +1 -1
- package/dist-esm/src/index.js +3 -0
- package/dist-esm/src/index.js.map +1 -1
- package/dist-esm/src/platform/nodejs/httpSender.js +5 -8
- package/dist-esm/src/platform/nodejs/httpSender.js.map +1 -1
- package/dist-esm/src/platform/nodejs/persist/fileAccessControl.js.map +1 -1
- package/dist-esm/src/platform/nodejs/persist/fileSystemHelpers.js +2 -1
- package/dist-esm/src/platform/nodejs/persist/fileSystemHelpers.js.map +1 -1
- package/dist-esm/src/platform/nodejs/persist/fileSystemPersist.js +10 -5
- package/dist-esm/src/platform/nodejs/persist/fileSystemPersist.js.map +1 -1
- package/dist-esm/src/sampling.js +81 -0
- package/dist-esm/src/sampling.js.map +1 -0
- package/dist-esm/src/utils/breezeUtils.js +3 -1
- package/dist-esm/src/utils/breezeUtils.js.map +1 -1
- package/dist-esm/src/utils/constants/applicationinsights.js +2 -1
- package/dist-esm/src/utils/constants/applicationinsights.js.map +1 -1
- package/dist-esm/src/utils/metricUtils.js +67 -0
- package/dist-esm/src/utils/metricUtils.js.map +1 -0
- package/dist-esm/src/utils/resourceUtils.js +35 -0
- package/dist-esm/src/utils/resourceUtils.js.map +1 -0
- package/dist-esm/src/utils/spanUtils.js +123 -44
- package/dist-esm/src/utils/spanUtils.js.map +1 -1
- package/package.json +20 -19
- package/types/monitor-opentelemetry-exporter.d.ts +181 -13
- package/CHANGELOG.md +0 -51
- package/dist-esm/src/generated/applicationInsightsClientContext.js +0 -34
- package/dist-esm/src/generated/applicationInsightsClientContext.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/generated/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/generated/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,cAAc,UAAU,CAAC;AACzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,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\nexport * from \"./models\";\nexport { ApplicationInsightsClient } from \"./applicationInsightsClient\";\n"]}
|
|
@@ -8,48 +8,83 @@
|
|
|
8
8
|
/** Known values of {@link DataPointType} that the service accepts. */
|
|
9
9
|
export var KnownDataPointType;
|
|
10
10
|
(function (KnownDataPointType) {
|
|
11
|
+
/** Measurement */
|
|
11
12
|
KnownDataPointType["Measurement"] = "Measurement";
|
|
13
|
+
/** Aggregation */
|
|
12
14
|
KnownDataPointType["Aggregation"] = "Aggregation";
|
|
13
15
|
})(KnownDataPointType || (KnownDataPointType = {}));
|
|
14
16
|
/** Known values of {@link SeverityLevel} that the service accepts. */
|
|
15
17
|
export var KnownSeverityLevel;
|
|
16
18
|
(function (KnownSeverityLevel) {
|
|
19
|
+
/** Verbose */
|
|
17
20
|
KnownSeverityLevel["Verbose"] = "Verbose";
|
|
21
|
+
/** Information */
|
|
18
22
|
KnownSeverityLevel["Information"] = "Information";
|
|
23
|
+
/** Warning */
|
|
19
24
|
KnownSeverityLevel["Warning"] = "Warning";
|
|
25
|
+
/** Error */
|
|
20
26
|
KnownSeverityLevel["Error"] = "Error";
|
|
27
|
+
/** Critical */
|
|
21
28
|
KnownSeverityLevel["Critical"] = "Critical";
|
|
22
29
|
})(KnownSeverityLevel || (KnownSeverityLevel = {}));
|
|
23
30
|
/** Known values of {@link ContextTagKeys} that the service accepts. */
|
|
24
31
|
export var KnownContextTagKeys;
|
|
25
32
|
(function (KnownContextTagKeys) {
|
|
33
|
+
/** AiApplicationVer */
|
|
26
34
|
KnownContextTagKeys["AiApplicationVer"] = "ai.application.ver";
|
|
35
|
+
/** AiDeviceId */
|
|
27
36
|
KnownContextTagKeys["AiDeviceId"] = "ai.device.id";
|
|
37
|
+
/** AiDeviceLocale */
|
|
28
38
|
KnownContextTagKeys["AiDeviceLocale"] = "ai.device.locale";
|
|
39
|
+
/** AiDeviceModel */
|
|
29
40
|
KnownContextTagKeys["AiDeviceModel"] = "ai.device.model";
|
|
41
|
+
/** AiDeviceOemName */
|
|
30
42
|
KnownContextTagKeys["AiDeviceOemName"] = "ai.device.oemName";
|
|
43
|
+
/** AiDeviceOsVersion */
|
|
31
44
|
KnownContextTagKeys["AiDeviceOsVersion"] = "ai.device.osVersion";
|
|
45
|
+
/** AiDeviceType */
|
|
32
46
|
KnownContextTagKeys["AiDeviceType"] = "ai.device.type";
|
|
47
|
+
/** AiLocationIp */
|
|
33
48
|
KnownContextTagKeys["AiLocationIp"] = "ai.location.ip";
|
|
49
|
+
/** AiLocationCountry */
|
|
34
50
|
KnownContextTagKeys["AiLocationCountry"] = "ai.location.country";
|
|
51
|
+
/** AiLocationProvince */
|
|
35
52
|
KnownContextTagKeys["AiLocationProvince"] = "ai.location.province";
|
|
53
|
+
/** AiLocationCity */
|
|
36
54
|
KnownContextTagKeys["AiLocationCity"] = "ai.location.city";
|
|
55
|
+
/** AiOperationId */
|
|
37
56
|
KnownContextTagKeys["AiOperationId"] = "ai.operation.id";
|
|
57
|
+
/** AiOperationName */
|
|
38
58
|
KnownContextTagKeys["AiOperationName"] = "ai.operation.name";
|
|
59
|
+
/** AiOperationParentId */
|
|
39
60
|
KnownContextTagKeys["AiOperationParentId"] = "ai.operation.parentId";
|
|
61
|
+
/** AiOperationSyntheticSource */
|
|
40
62
|
KnownContextTagKeys["AiOperationSyntheticSource"] = "ai.operation.syntheticSource";
|
|
63
|
+
/** AiOperationCorrelationVector */
|
|
41
64
|
KnownContextTagKeys["AiOperationCorrelationVector"] = "ai.operation.correlationVector";
|
|
65
|
+
/** AiSessionId */
|
|
42
66
|
KnownContextTagKeys["AiSessionId"] = "ai.session.id";
|
|
67
|
+
/** AiSessionIsFirst */
|
|
43
68
|
KnownContextTagKeys["AiSessionIsFirst"] = "ai.session.isFirst";
|
|
69
|
+
/** AiUserAccountId */
|
|
44
70
|
KnownContextTagKeys["AiUserAccountId"] = "ai.user.accountId";
|
|
71
|
+
/** AiUserId */
|
|
45
72
|
KnownContextTagKeys["AiUserId"] = "ai.user.id";
|
|
73
|
+
/** AiUserAuthUserId */
|
|
46
74
|
KnownContextTagKeys["AiUserAuthUserId"] = "ai.user.authUserId";
|
|
75
|
+
/** AiCloudRole */
|
|
47
76
|
KnownContextTagKeys["AiCloudRole"] = "ai.cloud.role";
|
|
77
|
+
/** AiCloudRoleVer */
|
|
48
78
|
KnownContextTagKeys["AiCloudRoleVer"] = "ai.cloud.roleVer";
|
|
79
|
+
/** AiCloudRoleInstance */
|
|
49
80
|
KnownContextTagKeys["AiCloudRoleInstance"] = "ai.cloud.roleInstance";
|
|
81
|
+
/** AiCloudLocation */
|
|
50
82
|
KnownContextTagKeys["AiCloudLocation"] = "ai.cloud.location";
|
|
83
|
+
/** AiInternalSdkVersion */
|
|
51
84
|
KnownContextTagKeys["AiInternalSdkVersion"] = "ai.internal.sdkVersion";
|
|
85
|
+
/** AiInternalAgentVersion */
|
|
52
86
|
KnownContextTagKeys["AiInternalAgentVersion"] = "ai.internal.agentVersion";
|
|
87
|
+
/** AiInternalNodeName */
|
|
53
88
|
KnownContextTagKeys["AiInternalNodeName"] = "ai.internal.nodeName";
|
|
54
89
|
})(KnownContextTagKeys || (KnownContextTagKeys = {}));
|
|
55
90
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/generated/models/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAyQH,sEAAsE;AACtE,MAAM,CAAN,IAAY,kBAGX;AAHD,WAAY,kBAAkB;IAC5B,iDAA2B,CAAA;IAC3B,iDAA2B,CAAA;AAC7B,CAAC,EAHW,kBAAkB,KAAlB,kBAAkB,QAG7B;AAYD,sEAAsE;AACtE,MAAM,CAAN,IAAY,kBAMX;AAND,WAAY,kBAAkB;IAC5B,yCAAmB,CAAA;IACnB,iDAA2B,CAAA;IAC3B,yCAAmB,CAAA;IACnB,qCAAe,CAAA;IACf,2CAAqB,CAAA;AACvB,CAAC,EANW,kBAAkB,KAAlB,kBAAkB,QAM7B;AAeD,uEAAuE;AACvE,MAAM,CAAN,IAAY,mBA6BX;AA7BD,WAAY,mBAAmB;IAC7B,8DAAuC,CAAA;IACvC,kDAA2B,CAAA;IAC3B,0DAAmC,CAAA;IACnC,wDAAiC,CAAA;IACjC,4DAAqC,CAAA;IACrC,gEAAyC,CAAA;IACzC,sDAA+B,CAAA;IAC/B,sDAA+B,CAAA;IAC/B,gEAAyC,CAAA;IACzC,kEAA2C,CAAA;IAC3C,0DAAmC,CAAA;IACnC,wDAAiC,CAAA;IACjC,4DAAqC,CAAA;IACrC,oEAA6C,CAAA;IAC7C,kFAA2D,CAAA;IAC3D,sFAA+D,CAAA;IAC/D,oDAA6B,CAAA;IAC7B,8DAAuC,CAAA;IACvC,4DAAqC,CAAA;IACrC,8CAAuB,CAAA;IACvB,8DAAuC,CAAA;IACvC,oDAA6B,CAAA;IAC7B,0DAAmC,CAAA;IACnC,oEAA6C,CAAA;IAC7C,4DAAqC,CAAA;IACrC,sEAA+C,CAAA;IAC/C,0EAAmD,CAAA;IACnD,kEAA2C,CAAA;AAC7C,CAAC,EA7BW,mBAAmB,KAAnB,mBAAmB,QA6B9B","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\";\n\n/** System variables for a telemetry item. */\nexport interface TelemetryItem {\n /** Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. */\n version?: number;\n /** Type name of telemetry data item. */\n name: string;\n /** Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. */\n time: Date;\n /** Sampling rate used in application. This telemetry item represents 100 / sampleRate actual telemetry items. */\n sampleRate?: number;\n /** Sequence field used to track absolute order of uploaded events. */\n sequence?: string;\n /** The instrumentation key of the Application Insights resource. */\n instrumentationKey?: string;\n /** Key/value collection of context properties. See ContextTagKeys for information on available properties. */\n tags?: { [propertyName: string]: string };\n /** Telemetry data item. */\n data?: MonitorBase;\n}\n\n/** Data struct to contain only C section with custom fields. */\nexport interface MonitorBase {\n /** Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. */\n baseType?: string;\n /** The data payload for the telemetry request */\n baseData?: MonitorDomain;\n}\n\n/** The abstract common base of all domains. */\nexport interface MonitorDomain {\n /** Describes unknown properties. The value of an unknown property can be of \"any\" type. */\n [property: string]: any;\n /** Schema version */\n version: number;\n}\n\n/** Response containing the status of each telemetry item. */\nexport interface TrackResponse {\n /** The number of items received. */\n itemsReceived?: number;\n /** The number of items accepted. */\n itemsAccepted?: number;\n /** An array of error detail objects. */\n errors?: TelemetryErrorDetails[];\n}\n\n/** The error details */\nexport interface TelemetryErrorDetails {\n /** The index in the original payload of the item. */\n index?: number;\n /** The item specific [HTTP Response status code](#Response Status Codes). */\n statusCode?: number;\n /** The error message. */\n message?: string;\n}\n\n/** Metric data single measurement. */\nexport interface MetricDataPoint {\n /** Namespace of the metric. */\n namespace?: string;\n /** Name of the metric. */\n name: string;\n /** Metric type. Single measurement or the aggregated value. */\n dataPointType?: DataPointType;\n /** Single value for measurement. Sum of individual measurements for the aggregation. */\n value: number;\n /** Metric weight of the aggregated metric. Should not be set for a measurement. */\n count?: number;\n /** Minimum value of the aggregated metric. Should not be set for a measurement. */\n min?: number;\n /** Maximum value of the aggregated metric. Should not be set for a measurement. */\n max?: number;\n /** Standard deviation of the aggregated metric. Should not be set for a measurement. */\n stdDev?: number;\n}\n\n/** Exception details of the exception in a chain. */\nexport interface TelemetryExceptionDetails {\n /** In case exception is nested (outer exception contains inner one), the id and outerId properties are used to represent the nesting. */\n id?: number;\n /** The value of outerId is a reference to an element in ExceptionDetails that represents the outer exception */\n outerId?: number;\n /** Exception type name. */\n typeName?: string;\n /** Exception message. */\n message: string;\n /** Indicates if full exception stack is provided in the exception. The stack may be trimmed, such as in the case of a StackOverflow exception. */\n hasFullStack?: boolean;\n /** Text describing the stack. Either stack or parsedStack should have a value. */\n stack?: string;\n /** List of stack frames. Either stack or parsedStack should have a value. */\n parsedStack?: StackFrame[];\n}\n\n/** Stack frame information. */\nexport interface StackFrame {\n level: number;\n /** Method name. */\n method: string;\n /** Name of the assembly (dll, jar, etc.) containing this function. */\n assembly?: string;\n /** File name or URL of the method implementation. */\n fileName?: string;\n /** Line number of the code implementation. */\n line?: number;\n}\n\n/** Instances of AvailabilityData represent the result of executing an availability test. */\nexport type AvailabilityData = MonitorDomain & {\n /** Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service. */\n id: string;\n /** Name of the test that these availability results represent. */\n name: string;\n /** Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Success flag. */\n success: boolean;\n /** Name of the location where the test was run from. */\n runLocation?: string;\n /** Diagnostic message for the result. */\n message?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name. */\nexport type TelemetryEventData = MonitorDomain & {\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application. */\nexport type TelemetryExceptionData = MonitorDomain & {\n /** Exception chain - list of inner exceptions. */\n exceptions: TelemetryExceptionDetails[];\n /** Severity level. Mostly used to indicate exception severity level when it is reported by logging library. */\n severityLevel?: SeverityLevel;\n /** Identifier of where the exception was thrown in code. Used for exceptions grouping. Typically a combination of exception type and a function from the call stack. */\n problemId?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into instances of this type. The message does not have measurements. */\nexport type MessageData = MonitorDomain & {\n /** Trace message */\n message: string;\n /** Trace severity level. */\n severityLevel?: SeverityLevel;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of the Metric item is a list of measurements (single data points) and/or aggregations. */\nexport type MetricsData = MonitorDomain & {\n /** List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used. */\n metrics: MetricDataPoint[];\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n};\n\n/** An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView. */\nexport type PageViewData = MonitorDomain & {\n /** Identifier of a page view instance. Used for correlation between page view and other telemetry items. */\n id: string;\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Request URL with all query string parameters */\n url?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */\n duration?: string;\n /** Fully qualified page URI or URL of the referring page; if unknown, leave blank */\n referredUri?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of PageViewPerf represents: a page view with no performance data, a page view with performance data, or just the performance data of an earlier page request. */\nexport type PageViewPerfData = MonitorDomain & {\n /** Identifier of a page view instance. Used for correlation between page view and other telemetry items. */\n id: string;\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Request URL with all query string parameters */\n url?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */\n duration?: string;\n /** Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n perfTotal?: string;\n /** Network connection time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n networkConnect?: string;\n /** Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n sentRequest?: string;\n /** Received response time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n receivedResponse?: string;\n /** DOM processing time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n domProcessing?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint. */\nexport type RemoteDependencyData = MonitorDomain & {\n /** Identifier of a dependency call instance. Used for correlation with the request telemetry item corresponding to this dependency call. */\n id?: string;\n /** Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. */\n name: string;\n /** Result code of a dependency call. Examples are SQL error code and HTTP status code. */\n resultCode?: string;\n /** Command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters. */\n data?: string;\n /** Dependency type name. Very low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. */\n type?: string;\n /** Target site of a dependency call. Examples are server name, host address. */\n target?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Indication of successful or unsuccessful call. */\n success?: boolean;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results. */\nexport type RequestData = MonitorDomain & {\n /** Identifier of a request call instance. Used for correlation between request and other telemetry items. */\n id: string;\n /** Name of the request. Represents code path taken to process request. Low cardinality value to allow better grouping of requests. For HTTP requests it represents the HTTP method and URL path template like 'GET /values/{id}'. */\n name?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Indication of successful or unsuccessful call. */\n success: boolean;\n /** Result of a request execution. HTTP status code for HTTP requests. */\n responseCode: string;\n /** Source of the request. Examples are the instrumentation key of the caller or the ip address of the caller. */\n source?: string;\n /** Request URL with all query string parameters. */\n url?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n};\n\n/** Known values of {@link DataPointType} that the service accepts. */\nexport enum KnownDataPointType {\n Measurement = \"Measurement\",\n Aggregation = \"Aggregation\"\n}\n\n/**\n * Defines values for DataPointType. \\\n * {@link KnownDataPointType} can be used interchangeably with DataPointType,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **Measurement** \\\n * **Aggregation**\n */\nexport type DataPointType = string;\n\n/** Known values of {@link SeverityLevel} that the service accepts. */\nexport enum KnownSeverityLevel {\n Verbose = \"Verbose\",\n Information = \"Information\",\n Warning = \"Warning\",\n Error = \"Error\",\n Critical = \"Critical\"\n}\n\n/**\n * Defines values for SeverityLevel. \\\n * {@link KnownSeverityLevel} can be used interchangeably with SeverityLevel,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **Verbose** \\\n * **Information** \\\n * **Warning** \\\n * **Error** \\\n * **Critical**\n */\nexport type SeverityLevel = string;\n\n/** Known values of {@link ContextTagKeys} that the service accepts. */\nexport enum KnownContextTagKeys {\n AiApplicationVer = \"ai.application.ver\",\n AiDeviceId = \"ai.device.id\",\n AiDeviceLocale = \"ai.device.locale\",\n AiDeviceModel = \"ai.device.model\",\n AiDeviceOemName = \"ai.device.oemName\",\n AiDeviceOsVersion = \"ai.device.osVersion\",\n AiDeviceType = \"ai.device.type\",\n AiLocationIp = \"ai.location.ip\",\n AiLocationCountry = \"ai.location.country\",\n AiLocationProvince = \"ai.location.province\",\n AiLocationCity = \"ai.location.city\",\n AiOperationId = \"ai.operation.id\",\n AiOperationName = \"ai.operation.name\",\n AiOperationParentId = \"ai.operation.parentId\",\n AiOperationSyntheticSource = \"ai.operation.syntheticSource\",\n AiOperationCorrelationVector = \"ai.operation.correlationVector\",\n AiSessionId = \"ai.session.id\",\n AiSessionIsFirst = \"ai.session.isFirst\",\n AiUserAccountId = \"ai.user.accountId\",\n AiUserId = \"ai.user.id\",\n AiUserAuthUserId = \"ai.user.authUserId\",\n AiCloudRole = \"ai.cloud.role\",\n AiCloudRoleVer = \"ai.cloud.roleVer\",\n AiCloudRoleInstance = \"ai.cloud.roleInstance\",\n AiCloudLocation = \"ai.cloud.location\",\n AiInternalSdkVersion = \"ai.internal.sdkVersion\",\n AiInternalAgentVersion = \"ai.internal.agentVersion\",\n AiInternalNodeName = \"ai.internal.nodeName\"\n}\n\n/**\n * Defines values for ContextTagKeys. \\\n * {@link KnownContextTagKeys} can be used interchangeably with ContextTagKeys,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **ai.application.ver** \\\n * **ai.device.id** \\\n * **ai.device.locale** \\\n * **ai.device.model** \\\n * **ai.device.oemName** \\\n * **ai.device.osVersion** \\\n * **ai.device.type** \\\n * **ai.location.ip** \\\n * **ai.location.country** \\\n * **ai.location.province** \\\n * **ai.location.city** \\\n * **ai.operation.id** \\\n * **ai.operation.name** \\\n * **ai.operation.parentId** \\\n * **ai.operation.syntheticSource** \\\n * **ai.operation.correlationVector** \\\n * **ai.session.id** \\\n * **ai.session.isFirst** \\\n * **ai.user.accountId** \\\n * **ai.user.id** \\\n * **ai.user.authUserId** \\\n * **ai.cloud.role** \\\n * **ai.cloud.roleVer** \\\n * **ai.cloud.roleInstance** \\\n * **ai.cloud.location** \\\n * **ai.internal.sdkVersion** \\\n * **ai.internal.agentVersion** \\\n * **ai.internal.nodeName**\n */\nexport type ContextTagKeys = string;\n\n/** Optional parameters. */\nexport interface TrackOptionalParams extends coreClient.OperationOptions {}\n\n/** Contains response data for the track operation. */\nexport type TrackOperationResponse = TrackResponse;\n\n/** Optional parameters. */\nexport interface ApplicationInsightsClientOptionalParams\n extends coreClient.ServiceClientOptions {\n /** Breeze endpoint: https://dc.services.visualstudio.com */\n host?: string;\n /** Overrides client endpoint. */\n endpoint?: string;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/generated/models/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAyQH,sEAAsE;AACtE,MAAM,CAAN,IAAY,kBAKX;AALD,WAAY,kBAAkB;IAC5B,kBAAkB;IAClB,iDAA2B,C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,0DAAmC,CAAA;IACnC,0BAA0B;IAC1B,oEAA6C,CAAA;IAC7C,sBAAsB;IACtB,4DAAqC,CAAA;IACrC,2BAA2B;IAC3B,sEAA+C,CAAA;IAC/C,6BAA6B;IAC7B,0EAAmD,CAAA;IACnD,yBAAyB;IACzB,kEAA2C,CAAA;AAC7C,CAAC,EAzDW,mBAAmB,KAAnB,mBAAmB,QAyD9B","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\";\n\n/** System variables for a telemetry item. */\nexport interface TelemetryItem {\n /** Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1. */\n version?: number;\n /** Type name of telemetry data item. */\n name: string;\n /** Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z. */\n time: Date;\n /** Sampling rate used in application. This telemetry item represents 100 / sampleRate actual telemetry items. */\n sampleRate?: number;\n /** Sequence field used to track absolute order of uploaded events. */\n sequence?: string;\n /** The instrumentation key of the Application Insights resource. */\n instrumentationKey?: string;\n /** Key/value collection of context properties. See ContextTagKeys for information on available properties. */\n tags?: { [propertyName: string]: string };\n /** Telemetry data item. */\n data?: MonitorBase;\n}\n\n/** Data struct to contain only C section with custom fields. */\nexport interface MonitorBase {\n /** Name of item (B section) if any. If telemetry data is derived straight from this, this should be null. */\n baseType?: string;\n /** The data payload for the telemetry request */\n baseData?: MonitorDomain;\n}\n\n/** The abstract common base of all domains. */\nexport interface MonitorDomain {\n /** Describes unknown properties. The value of an unknown property can be of \"any\" type. */\n [property: string]: any;\n /** Schema version */\n version: number;\n}\n\n/** Response containing the status of each telemetry item. */\nexport interface TrackResponse {\n /** The number of items received. */\n itemsReceived?: number;\n /** The number of items accepted. */\n itemsAccepted?: number;\n /** An array of error detail objects. */\n errors?: TelemetryErrorDetails[];\n}\n\n/** The error details */\nexport interface TelemetryErrorDetails {\n /** The index in the original payload of the item. */\n index?: number;\n /** The item specific [HTTP Response status code](#Response Status Codes). */\n statusCode?: number;\n /** The error message. */\n message?: string;\n}\n\n/** Metric data single measurement. */\nexport interface MetricDataPoint {\n /** Namespace of the metric. */\n namespace?: string;\n /** Name of the metric. */\n name: string;\n /** Metric type. Single measurement or the aggregated value. */\n dataPointType?: DataPointType;\n /** Single value for measurement. Sum of individual measurements for the aggregation. */\n value: number;\n /** Metric weight of the aggregated metric. Should not be set for a measurement. */\n count?: number;\n /** Minimum value of the aggregated metric. Should not be set for a measurement. */\n min?: number;\n /** Maximum value of the aggregated metric. Should not be set for a measurement. */\n max?: number;\n /** Standard deviation of the aggregated metric. Should not be set for a measurement. */\n stdDev?: number;\n}\n\n/** Exception details of the exception in a chain. */\nexport interface TelemetryExceptionDetails {\n /** In case exception is nested (outer exception contains inner one), the id and outerId properties are used to represent the nesting. */\n id?: number;\n /** The value of outerId is a reference to an element in ExceptionDetails that represents the outer exception */\n outerId?: number;\n /** Exception type name. */\n typeName?: string;\n /** Exception message. */\n message: string;\n /** Indicates if full exception stack is provided in the exception. The stack may be trimmed, such as in the case of a StackOverflow exception. */\n hasFullStack?: boolean;\n /** Text describing the stack. Either stack or parsedStack should have a value. */\n stack?: string;\n /** List of stack frames. Either stack or parsedStack should have a value. */\n parsedStack?: StackFrame[];\n}\n\n/** Stack frame information. */\nexport interface StackFrame {\n level: number;\n /** Method name. */\n method: string;\n /** Name of the assembly (dll, jar, etc.) containing this function. */\n assembly?: string;\n /** File name or URL of the method implementation. */\n fileName?: string;\n /** Line number of the code implementation. */\n line?: number;\n}\n\n/** Instances of AvailabilityData represent the result of executing an availability test. */\nexport interface AvailabilityData extends MonitorDomain {\n /** Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service. */\n id: string;\n /** Name of the test that these availability results represent. */\n name: string;\n /** Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Success flag. */\n success: boolean;\n /** Name of the location where the test was run from. */\n runLocation?: string;\n /** Diagnostic message for the result. */\n message?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n}\n\n/** Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name. */\nexport interface TelemetryEventData extends MonitorDomain {\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n}\n\n/** An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application. */\nexport interface TelemetryExceptionData extends MonitorDomain {\n /** Exception chain - list of inner exceptions. */\n exceptions: TelemetryExceptionDetails[];\n /** Severity level. Mostly used to indicate exception severity level when it is reported by logging library. */\n severityLevel?: SeverityLevel;\n /** Identifier of where the exception was thrown in code. Used for exceptions grouping. Typically a combination of exception type and a function from the call stack. */\n problemId?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n}\n\n/** Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into instances of this type. The message does not have measurements. */\nexport interface MessageData extends MonitorDomain {\n /** Trace message */\n message: string;\n /** Trace severity level. */\n severityLevel?: SeverityLevel;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n}\n\n/** An instance of the Metric item is a list of measurements (single data points) and/or aggregations. */\nexport interface MetricsData extends MonitorDomain {\n /** List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used. */\n metrics: MetricDataPoint[];\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n}\n\n/** An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView. */\nexport interface PageViewData extends MonitorDomain {\n /** Identifier of a page view instance. Used for correlation between page view and other telemetry items. */\n id: string;\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Request URL with all query string parameters */\n url?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */\n duration?: string;\n /** Fully qualified page URI or URL of the referring page; if unknown, leave blank */\n referredUri?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n}\n\n/** An instance of PageViewPerf represents: a page view with no performance data, a page view with performance data, or just the performance data of an earlier page request. */\nexport interface PageViewPerfData extends MonitorDomain {\n /** Identifier of a page view instance. Used for correlation between page view and other telemetry items. */\n id: string;\n /** Event name. Keep it low cardinality to allow proper grouping and useful metrics. */\n name: string;\n /** Request URL with all query string parameters */\n url?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days. */\n duration?: string;\n /** Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n perfTotal?: string;\n /** Network connection time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n networkConnect?: string;\n /** Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n sentRequest?: string;\n /** Received response time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n receivedResponse?: string;\n /** DOM processing time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff */\n domProcessing?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n}\n\n/** An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint. */\nexport interface RemoteDependencyData extends MonitorDomain {\n /** Identifier of a dependency call instance. Used for correlation with the request telemetry item corresponding to this dependency call. */\n id?: string;\n /** Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. */\n name: string;\n /** Result code of a dependency call. Examples are SQL error code and HTTP status code. */\n resultCode?: string;\n /** Command initiated by this dependency call. Examples are SQL statement and HTTP URL with all query parameters. */\n data?: string;\n /** Dependency type name. Very low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP. */\n type?: string;\n /** Target site of a dependency call. Examples are server name, host address. */\n target?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Indication of successful or unsuccessful call. */\n success?: boolean;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n}\n\n/** An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results. */\nexport interface RequestData extends MonitorDomain {\n /** Identifier of a request call instance. Used for correlation between request and other telemetry items. */\n id: string;\n /** Name of the request. Represents code path taken to process request. Low cardinality value to allow better grouping of requests. For HTTP requests it represents the HTTP method and URL path template like 'GET /values/{id}'. */\n name?: string;\n /** Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days. */\n duration: string;\n /** Indication of successful or unsuccessful call. */\n success: boolean;\n /** Result of a request execution. HTTP status code for HTTP requests. */\n responseCode: string;\n /** Source of the request. Examples are the instrumentation key of the caller or the ip address of the caller. */\n source?: string;\n /** Request URL with all query string parameters. */\n url?: string;\n /** Collection of custom properties. */\n properties?: { [propertyName: string]: string };\n /** Collection of custom measurements. */\n measurements?: { [propertyName: string]: number };\n}\n\n/** Known values of {@link DataPointType} that the service accepts. */\nexport enum KnownDataPointType {\n /** Measurement */\n Measurement = \"Measurement\",\n /** Aggregation */\n Aggregation = \"Aggregation\"\n}\n\n/**\n * Defines values for DataPointType. \\\n * {@link KnownDataPointType} can be used interchangeably with DataPointType,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **Measurement** \\\n * **Aggregation**\n */\nexport type DataPointType = string;\n\n/** Known values of {@link SeverityLevel} that the service accepts. */\nexport enum KnownSeverityLevel {\n /** Verbose */\n Verbose = \"Verbose\",\n /** Information */\n Information = \"Information\",\n /** Warning */\n Warning = \"Warning\",\n /** Error */\n Error = \"Error\",\n /** Critical */\n Critical = \"Critical\"\n}\n\n/**\n * Defines values for SeverityLevel. \\\n * {@link KnownSeverityLevel} can be used interchangeably with SeverityLevel,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **Verbose** \\\n * **Information** \\\n * **Warning** \\\n * **Error** \\\n * **Critical**\n */\nexport type SeverityLevel = string;\n\n/** Known values of {@link ContextTagKeys} that the service accepts. */\nexport enum KnownContextTagKeys {\n /** AiApplicationVer */\n AiApplicationVer = \"ai.application.ver\",\n /** AiDeviceId */\n AiDeviceId = \"ai.device.id\",\n /** AiDeviceLocale */\n AiDeviceLocale = \"ai.device.locale\",\n /** AiDeviceModel */\n AiDeviceModel = \"ai.device.model\",\n /** AiDeviceOemName */\n AiDeviceOemName = \"ai.device.oemName\",\n /** AiDeviceOsVersion */\n AiDeviceOsVersion = \"ai.device.osVersion\",\n /** AiDeviceType */\n AiDeviceType = \"ai.device.type\",\n /** AiLocationIp */\n AiLocationIp = \"ai.location.ip\",\n /** AiLocationCountry */\n AiLocationCountry = \"ai.location.country\",\n /** AiLocationProvince */\n AiLocationProvince = \"ai.location.province\",\n /** AiLocationCity */\n AiLocationCity = \"ai.location.city\",\n /** AiOperationId */\n AiOperationId = \"ai.operation.id\",\n /** AiOperationName */\n AiOperationName = \"ai.operation.name\",\n /** AiOperationParentId */\n AiOperationParentId = \"ai.operation.parentId\",\n /** AiOperationSyntheticSource */\n AiOperationSyntheticSource = \"ai.operation.syntheticSource\",\n /** AiOperationCorrelationVector */\n AiOperationCorrelationVector = \"ai.operation.correlationVector\",\n /** AiSessionId */\n AiSessionId = \"ai.session.id\",\n /** AiSessionIsFirst */\n AiSessionIsFirst = \"ai.session.isFirst\",\n /** AiUserAccountId */\n AiUserAccountId = \"ai.user.accountId\",\n /** AiUserId */\n AiUserId = \"ai.user.id\",\n /** AiUserAuthUserId */\n AiUserAuthUserId = \"ai.user.authUserId\",\n /** AiCloudRole */\n AiCloudRole = \"ai.cloud.role\",\n /** AiCloudRoleVer */\n AiCloudRoleVer = \"ai.cloud.roleVer\",\n /** AiCloudRoleInstance */\n AiCloudRoleInstance = \"ai.cloud.roleInstance\",\n /** AiCloudLocation */\n AiCloudLocation = \"ai.cloud.location\",\n /** AiInternalSdkVersion */\n AiInternalSdkVersion = \"ai.internal.sdkVersion\",\n /** AiInternalAgentVersion */\n AiInternalAgentVersion = \"ai.internal.agentVersion\",\n /** AiInternalNodeName */\n AiInternalNodeName = \"ai.internal.nodeName\"\n}\n\n/**\n * Defines values for ContextTagKeys. \\\n * {@link KnownContextTagKeys} can be used interchangeably with ContextTagKeys,\n * this enum contains the known values that the service supports.\n * ### Known values supported by the service\n * **ai.application.ver** \\\n * **ai.device.id** \\\n * **ai.device.locale** \\\n * **ai.device.model** \\\n * **ai.device.oemName** \\\n * **ai.device.osVersion** \\\n * **ai.device.type** \\\n * **ai.location.ip** \\\n * **ai.location.country** \\\n * **ai.location.province** \\\n * **ai.location.city** \\\n * **ai.operation.id** \\\n * **ai.operation.name** \\\n * **ai.operation.parentId** \\\n * **ai.operation.syntheticSource** \\\n * **ai.operation.correlationVector** \\\n * **ai.session.id** \\\n * **ai.session.isFirst** \\\n * **ai.user.accountId** \\\n * **ai.user.id** \\\n * **ai.user.authUserId** \\\n * **ai.cloud.role** \\\n * **ai.cloud.roleVer** \\\n * **ai.cloud.roleInstance** \\\n * **ai.cloud.location** \\\n * **ai.internal.sdkVersion** \\\n * **ai.internal.agentVersion** \\\n * **ai.internal.nodeName**\n */\nexport type ContextTagKeys = string;\n\n/** Optional parameters. */\nexport interface TrackOptionalParams extends coreClient.OperationOptions {}\n\n/** Contains response data for the track operation. */\nexport type TrackOperationResponse = TrackResponse;\n\n/** Optional parameters. */\nexport interface ApplicationInsightsClientOptionalParams\n extends coreClient.ServiceClientOptions {\n /** Breeze endpoint: https://dc.services.visualstudio.com */\n host?: string;\n /** Overrides client endpoint. */\n endpoint?: string;\n}\n"]}
|
package/dist-esm/src/index.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
// Copyright (c) Microsoft Corporation.
|
|
2
2
|
// Licensed under the MIT license.
|
|
3
|
+
export { ApplicationInsightsSampler } from "./sampling";
|
|
4
|
+
export { AzureMonitorBaseExporter } from "./export/base";
|
|
3
5
|
export { AzureMonitorTraceExporter } from "./export/trace";
|
|
6
|
+
export { AzureMonitorMetricExporter } from "./export/metric";
|
|
4
7
|
export { ServiceApiVersion } from "./Declarations/Constants";
|
|
5
8
|
//# 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,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;
|
|
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;AAE7D,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 { AzureMonitorExporterOptions } from \"./config\";\nexport { ServiceApiVersion } from \"./Declarations/Constants\";\nexport {\n ApplicationInsightsClientOptionalParams,\n MonitorBase,\n MonitorDomain,\n TelemetryItem,\n} from \"./generated/models\";\n"]}
|
|
@@ -10,19 +10,16 @@ const applicationInsightsResource = "https://monitor.azure.com//.default";
|
|
|
10
10
|
* @internal
|
|
11
11
|
*/
|
|
12
12
|
export class HttpSender {
|
|
13
|
-
constructor(
|
|
14
|
-
this._exporterOptions = _exporterOptions;
|
|
13
|
+
constructor(endpointUrl, options) {
|
|
15
14
|
// Build endpoint using provided configuration or default values
|
|
16
|
-
this._appInsightsClientOptions = {
|
|
17
|
-
|
|
18
|
-
};
|
|
19
|
-
this._appInsightsClient = new ApplicationInsightsClient(Object.assign({}, this._appInsightsClientOptions));
|
|
15
|
+
this._appInsightsClientOptions = Object.assign({ host: endpointUrl }, options);
|
|
16
|
+
this._appInsightsClient = new ApplicationInsightsClient(this._appInsightsClientOptions);
|
|
20
17
|
// Handle redirects in HTTP Sender
|
|
21
18
|
this._appInsightsClient.pipeline.removePolicy({ name: redirectPolicyName });
|
|
22
|
-
if (
|
|
19
|
+
if (options === null || options === void 0 ? void 0 : options.aadTokenCredential) {
|
|
23
20
|
let scopes = [applicationInsightsResource];
|
|
24
21
|
this._appInsightsClient.pipeline.addPolicy(bearerTokenAuthenticationPolicy({
|
|
25
|
-
credential:
|
|
22
|
+
credential: options === null || options === void 0 ? void 0 : options.aadTokenCredential,
|
|
26
23
|
scopes: scopes,
|
|
27
24
|
}));
|
|
28
25
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpSender.js","sourceRoot":"","sources":["../../../../src/platform/nodejs/httpSender.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,+BAA+B,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAEhG,OAAO,EAEL,yBAAyB,GAG1B,MAAM,iBAAiB,CAAC;AAGzB,MAAM,2BAA2B,GAAG,qCAAqC,CAAC;AAE1E;;;GAGG;AACH,MAAM,OAAO,UAAU;IAIrB,
|
|
1
|
+
{"version":3,"file":"httpSender.js","sourceRoot":"","sources":["../../../../src/platform/nodejs/httpSender.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAClC,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,+BAA+B,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAEhG,OAAO,EAEL,yBAAyB,GAG1B,MAAM,iBAAiB,CAAC;AAGzB,MAAM,2BAA2B,GAAG,qCAAqC,CAAC;AAE1E;;;GAGG;AACH,MAAM,OAAO,UAAU;IAIrB,YAAY,WAAmB,EAAE,OAAqC;QACpE,gEAAgE;QAChE,IAAI,CAAC,yBAAyB,mBAC5B,IAAI,EAAE,WAAW,IACd,OAAO,CACX,CAAC;QACF,IAAI,CAAC,kBAAkB,GAAG,IAAI,yBAAyB,CAAC,IAAI,CAAC,yBAAyB,CAAC,CAAC;QAExF,kCAAkC;QAClC,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,kBAAkB,EAAE,CAAC,CAAC;QAE5E,IAAI,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,kBAAkB,EAAE;YAC/B,IAAI,MAAM,GAAa,CAAC,2BAA2B,CAAC,CAAC;YACrD,IAAI,CAAC,kBAAk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Microsoft Corporation.\n// Licensed under the MIT license.\nimport url from \"url\";\nimport { diag } from \"@opentelemetry/api\";\nimport { FullOperationResponse } from \"@azure/core-client\";\nimport { bearerTokenAuthenticationPolicy, redirectPolicyName } from \"@azure/core-rest-pipeline\";\nimport { Sender, SenderResult } from \"../../types\";\nimport {\n TelemetryItem as Envelope,\n ApplicationInsightsClient,\n ApplicationInsightsClientOptionalParams,\n TrackOptionalParams,\n} from \"../../generated\";\nimport { AzureMonitorExporterOptions } from \"../../config\";\n\nconst applicationInsightsResource = \"https://monitor.azure.com//.default\";\n\n/**\n * Exporter HTTP sender class\n * @internal\n */\nexport class HttpSender implements Sender {\n private readonly _appInsightsClient: ApplicationInsightsClient;\n private _appInsightsClientOptions: ApplicationInsightsClientOptionalParams;\n\n constructor(endpointUrl: string, options?: AzureMonitorExporterOptions) {\n // Build endpoint using provided configuration or default values\n this._appInsightsClientOptions = {\n host: endpointUrl,\n ...options,\n };\n this._appInsightsClient = new ApplicationInsightsClient(this._appInsightsClientOptions);\n\n // Handle redirects in HTTP Sender\n this._appInsightsClient.pipeline.removePolicy({ name: redirectPolicyName });\n\n if (options?.aadTokenCredential) {\n let scopes: string[] = [applicationInsightsResource];\n this._appInsightsClient.pipeline.addPolicy(\n bearerTokenAuthenticationPolicy({\n credential: options?.aadTokenCredential,\n scopes: scopes,\n })\n );\n }\n }\n\n /**\n * Send Azure envelopes\n * @internal\n */\n async send(envelopes: Envelope[]): Promise<SenderResult> {\n let options: TrackOptionalParams = {};\n try {\n let response: FullOperationResponse | undefined;\n function onResponse(rawResponse: FullOperationResponse, flatResponse: unknown): void {\n response = rawResponse;\n if (options.onResponse) {\n options.onResponse(rawResponse, flatResponse);\n }\n }\n await this._appInsightsClient.track(envelopes, {\n ...options,\n onResponse,\n });\n\n return { statusCode: response?.status, result: response?.bodyAsText ?? \"\" };\n } catch (e: any) {\n throw e;\n }\n }\n\n /**\n * Shutdown sender\n * @internal\n */\n async shutdown(): Promise<void> {\n diag.info(\"HttpSender shutting down\");\n }\n\n handlePermanentRedirect(location: string | undefined) {\n if (location) {\n const locUrl = new url.URL(location);\n if (locUrl && locUrl.host) {\n this._appInsightsClient.host = \"https://\" + locUrl.host;\n }\n }\n }\n}\n"]}
|
|
@@ -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,CAAC,EAAE;oBACV,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,KAAK,CAAC,aAAa,CAAC,SAAiB;QACjD,IAAI,iBAAiB,CAAC,U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import * 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) {\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) {\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,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,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,KAAK,CAAC,aAAa,CAAC,SAAiB;QACjD,IAAI,iBAAiB,CAAC,UAAU,EAAE;YAChC,IAAI,iBAAiB,CAAC,iBAAiB,CAAC,SAAS,CAAC,KAAK,SAAS,EAAE;gBAChE,2GAA2G;gBAC3G,gHAAgH;gBAChH,kFAAkF;gBAClF,iBAAiB,CAAC,iBAAiB,CAAC,SAAS,CAAC,GAAG,K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AAC;YACF,IAAI,MAAM,CAAC,KAAK,EAAE;gBAChB,MAAM,MAAM,CAAC,KAAK,CAAC;aACpB;iBAAM,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;gBAC9B,MAAM,IAAI,KAAK,CAAC,0DAA0D,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC;aAC7F;YACD,iBAAiB,CAAC,YAAY,GAAG,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC;YAClF,OAAO,iBAAiB,CAAC,YAAY,CAAC;SACvC;aAAM;YACL,MAAM,IAAI,KAAK,CAAC,2EAA2E,CAAC,CAAC;SAC9F;IACH,CAAC;IAEO,MAAM,CAAC,gBAAgB,CAAC,SAAiB,EAAE,QAAgB;QACjE,OAAO;YACL,SAAS;YACT,QAAQ;YACR,yBAAyB;YACzB,QAAQ;YACR,GAAG,QAAQ,YAAY;YACvB,gBAAgB;SACjB,CAAC,CAAC,mCAAmC;IACxC,CAAC;;AAhLc,6BAAW,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,8BAA8B,CAAC;AACvE,iCAAe,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,yDAAyD,CAAC;AACtG,mCAAiB,GAA8B,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"]}
|
|
@@ -38,7 +38,8 @@ export const confirmDirExists = async (directory) => {
|
|
|
38
38
|
catch (err) {
|
|
39
39
|
if (err && err.code === "ENOENT") {
|
|
40
40
|
try {
|
|
41
|
-
|
|
41
|
+
const options = { recursive: true };
|
|
42
|
+
await mkdirAsync(directory, options);
|
|
42
43
|
}
|
|
43
44
|
catch (mkdirErr) {
|
|
44
45
|
if (mkdirErr && mkdirErr.code !== "EEXIST") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileSystemHelpers.js","sourceRoot":"","sources":["../../../../../src/platform/nodejs/persist/fileSystemHelpers.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAElC,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAEjC,MAAM,YAAY,GAAG,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC;AAC3C,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACrC,MAAM,UAAU,GAAG,SAAS,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;AACvC,MAAM,UAAU,GAAG,SAAS,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;AAEvC;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,KAAK,EAAE,SAAiB,EAAmB,EAAE;IAClF,4BAA4B;IAC5B,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,SAAS,CAAC,CAAC;IAE5C,IAAI,SAAS,GAAG,CAAC,CAAC;IAElB,uBAAuB;IACvB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;QACxB,MAAM,SAAS,GAAG,MAAM,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;QAC9D,IAAI,SAAS,CAAC,MAAM,EAAE,EAAE;YACtB,SAAS,IAAI,SAAS,CAAC,IAAI,CAAC;SAC7B;KACF;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,EAAE,SAAiB,EAAiB,EAAE;IACzE,IAAI;QACF,M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,CAAC,MAAM,gBAAgB,GAAG,KAAK,EAAE,SAAiB,EAAiB,EAAE;IACzE,IAAI;QACF,MAAM,KAAK,GAAG,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC;QAC1C,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE;YACxB,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;SACzD;KACF;IAAC,OAAO,GAAQ,EAAE;QACjB,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE;YAChC,IAAI;gBACF,MAAM,OAAO,GAA4B,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;gBAC7D,MAAM,UAAU,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;aACtC;YAAC,OAAO,QAAa,EAAE;gBACtB,IAAI,QAAQ,IAAI,QAAQ,CAAC,IAAI,KAAK,QAAQ,EAAE;oBAC1C,2CAA2C;oBAC3C,MAAM,QAAQ,CAAC;iBAChB;aACF;SACF;KACF;AACH,CAAC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { promisify } from \"util\";\n\nconst readdirAsync = promisify(fs.readdir);\nconst statAsync = promisify(fs.stat);\nconst lstatAsync = promisify(fs.lstat);\nconst mkdirAsync = promisify(fs.mkdir);\n\n/**\n * Computes the size (in bytes) of all files in a directory at the root level. Asynchronously.\n * @internal\n */\nexport const getShallowDirectorySize = async (directory: string): Promise<number> => {\n // Get the directory listing\n const files = await readdirAsync(directory);\n\n let totalSize = 0;\n\n // Query all file sizes\n for (const file of files) {\n const fileStats = await statAsync(path.join(directory, file));\n if (fileStats.isFile()) {\n totalSize += fileStats.size;\n }\n }\n\n return totalSize;\n};\n\n/**\n * Validate directory exists.\n * @internal\n */\nexport const confirmDirExists = async (directory: string): Promise<void> => {\n try {\n const stats = await lstatAsync(directory);\n if (!stats.isDirectory()) {\n throw new Error(\"Path existed but was not a directory\");\n }\n } catch (err: any) {\n if (err && err.code === \"ENOENT\") {\n try {\n const options: fs.MakeDirectoryOptions = { recursive: true };\n await mkdirAsync(directory, options);\n } catch (mkdirErr: any) {\n if (mkdirErr && mkdirErr.code !== \"EEXIST\") {\n // Handle race condition by ignoring EEXIST\n throw mkdirErr;\n }\n }\n }\n }\n};\n"]}
|
|
@@ -4,7 +4,6 @@ import * as fs from "fs";
|
|
|
4
4
|
import * as os from "os";
|
|
5
5
|
import * as path from "path";
|
|
6
6
|
import { diag } from "@opentelemetry/api";
|
|
7
|
-
import { DEFAULT_EXPORTER_CONFIG } from "../../../config";
|
|
8
7
|
import { FileAccessControl } from "./fileAccessControl";
|
|
9
8
|
import { confirmDirExists, getShallowDirectorySize } from "./fileSystemHelpers";
|
|
10
9
|
import { promisify } from "util";
|
|
@@ -18,25 +17,31 @@ const writeFileAsync = promisify(fs.writeFile);
|
|
|
18
17
|
* @internal
|
|
19
18
|
*/
|
|
20
19
|
export class FileSystemPersist {
|
|
21
|
-
constructor(
|
|
20
|
+
constructor(instrumentationKey, _options) {
|
|
21
|
+
var _a, _b;
|
|
22
|
+
this._options = _options;
|
|
22
23
|
this.fileRetemptionPeriod = 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
23
24
|
this.cleanupTimeOut = 60 * 60 * 1000; // 1 hour
|
|
24
25
|
this.maxBytesOnDisk = 50000000; // ~50MB
|
|
25
26
|
this._tempDirectory = "";
|
|
26
27
|
this._fileCleanupTimer = null;
|
|
27
|
-
this.
|
|
28
|
+
this._instrumentationKey = instrumentationKey;
|
|
29
|
+
if ((_a = this._options) === null || _a === void 0 ? void 0 : _a.disableOfflineStorage) {
|
|
30
|
+
this._enabled = false;
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
28
33
|
this._enabled = true;
|
|
29
34
|
FileAccessControl.checkFileProtection();
|
|
30
35
|
if (!FileAccessControl.OS_PROVIDES_FILE_PROTECTION) {
|
|
31
36
|
this._enabled = false;
|
|
32
37
|
diag.error("Sufficient file protection capabilities were not detected. Files will not be persisted");
|
|
33
38
|
}
|
|
34
|
-
if (!this.
|
|
39
|
+
if (!this._instrumentationKey) {
|
|
35
40
|
this._enabled = false;
|
|
36
41
|
diag.error(`No instrumentation key was provided to FileSystemPersister. Files will not be persisted`);
|
|
37
42
|
}
|
|
38
43
|
if (this._enabled) {
|
|
39
|
-
this._tempDirectory = path.join(os.tmpdir(), FileSystemPersist.TEMPDIR_PREFIX + this.
|
|
44
|
+
this._tempDirectory = path.join(((_b = this._options) === null || _b === void 0 ? void 0 : _b.storageDirectory) || os.tmpdir(), "Microsoft", "AzureMonitor", FileSystemPersist.TEMPDIR_PREFIX + this._instrumentationKey);
|
|
40
45
|
// Starts file cleanup task
|
|
41
46
|
if (!this._fileCleanupTimer) {
|
|
42
47
|
this._fileCleanupTimer = setTimeout(() => {
|
|
@@ -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,uBAAuB,EAA+B,MAAM,iBAAiB,CAAC;AACvF,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;AAEjC,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;AACrC,MAAM,YAAY,GAAG,SAAS,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC;AAC3C,MAAM,aAAa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AC;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,KAAK,EAAE;YACd,IAAI,CAAC,IAAI,CAAC,yDAAyD,EAAE,KAAK,CAAC,CAAC;YAC5E,OAAO,KAAK,CAAC;SACd;IACH,CAAC;;AA9KM,gCAAc,GAAG,oBAAoB,CAAC;AAEtC,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 { DEFAULT_EXPORTER_CONFIG, AzureExporterInternalConfig } from \"../../../config\";\nimport { FileAccessControl } from \"./fileAccessControl\";\nimport { confirmDirExists, getShallowDirectorySize } from \"./fileSystemHelpers\";\nimport { promisify } from \"util\";\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\n static FILENAME_SUFFIX = \".ai.json\";\n\n fileRetemptionPeriod = 7 * 24 * 60 * 60 * 1000; // 7 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\n private readonly _options: AzureExporterInternalConfig;\n\n constructor(options: Partial<AzureExporterInternalConfig> = {}) {\n this._options = { ...DEFAULT_EXPORTER_CONFIG, ...options };\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._options.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 os.tmpdir(),\n FileSystemPersist.TEMPDIR_PREFIX + this._options.instrumentationKey\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) {\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) {\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) {\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) {\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) {\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) {\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,QAAQ,CAAC,CAAC;AAC7C,MAAM,WAAW,GAAG,SAAS,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC;AACzC,MAAM,cAAc,GAAG,SAAS,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC;AAE/C;;;GAGG;AACH,MAAM,OAAO,iB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,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 = 7 * 24 * 60 * 60 * 1000; // 7 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"]}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { SamplingDecision } from "@opentelemetry/sdk-trace-base";
|
|
2
|
+
import { AzureMonitorSampleRate } from "./utils/constants/applicationinsights";
|
|
3
|
+
/**
|
|
4
|
+
* ApplicationInsightsSampler is responsible for the following:
|
|
5
|
+
* Implements same trace id hashing algorithm so that traces are sampled the same across multiple nodes
|
|
6
|
+
* Adds item count to span attribute if span is sampled (needed for ingestion service)
|
|
7
|
+
* @param samplingRatio - 0 to 1 value.
|
|
8
|
+
*/
|
|
9
|
+
export class ApplicationInsightsSampler {
|
|
10
|
+
constructor(samplingRatio = 1) {
|
|
11
|
+
this._samplingRatio = samplingRatio;
|
|
12
|
+
if (this._samplingRatio > 1) {
|
|
13
|
+
throw new Error("Wrong sampling rate, data will not be sampled out");
|
|
14
|
+
}
|
|
15
|
+
this._sampleRate = Math.round(this._samplingRatio * 100);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Checks whether span needs to be created and tracked.
|
|
19
|
+
*
|
|
20
|
+
* @param context Parent Context which may contain a span.
|
|
21
|
+
* @param traceId of the span to be created. It can be different from the
|
|
22
|
+
* traceId in the {@link SpanContext}. Typically in situations when the
|
|
23
|
+
* span to be created starts a new trace.
|
|
24
|
+
* @param spanName of the span to be created.
|
|
25
|
+
* @param spanKind of the span to be created.
|
|
26
|
+
* @param attributes Initial set of SpanAttributes for the Span being constructed.
|
|
27
|
+
* @param links Collection of links that will be associated with the Span to
|
|
28
|
+
* be created. Typically useful for batch operations.
|
|
29
|
+
* @returns a {@link SamplingResult}.
|
|
30
|
+
*/
|
|
31
|
+
shouldSample(
|
|
32
|
+
// @ts-ignore
|
|
33
|
+
context, traceId,
|
|
34
|
+
// @ts-ignore
|
|
35
|
+
spanName,
|
|
36
|
+
// @ts-ignore
|
|
37
|
+
spanKind, attributes,
|
|
38
|
+
// @ts-ignore
|
|
39
|
+
links) {
|
|
40
|
+
let isSampledIn = false;
|
|
41
|
+
if (this._sampleRate == 100) {
|
|
42
|
+
isSampledIn = true;
|
|
43
|
+
}
|
|
44
|
+
else if (this._sampleRate == 0) {
|
|
45
|
+
isSampledIn = false;
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
isSampledIn = this._getSamplingHashCode(traceId) < this._sampleRate;
|
|
49
|
+
}
|
|
50
|
+
// Add sample rate as span attribute
|
|
51
|
+
attributes = attributes || {};
|
|
52
|
+
attributes[AzureMonitorSampleRate] = this._sampleRate;
|
|
53
|
+
return isSampledIn
|
|
54
|
+
? { decision: SamplingDecision.RECORD_AND_SAMPLED, attributes: attributes }
|
|
55
|
+
: { decision: SamplingDecision.NOT_RECORD, attributes: attributes };
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Return Sampler description
|
|
59
|
+
*/
|
|
60
|
+
toString() {
|
|
61
|
+
return `ApplicationInsightsSampler{${this._samplingRatio}}`;
|
|
62
|
+
}
|
|
63
|
+
_getSamplingHashCode(input) {
|
|
64
|
+
var csharpMin = -2147483648;
|
|
65
|
+
var csharpMax = 2147483647;
|
|
66
|
+
var hash = 5381;
|
|
67
|
+
if (!input) {
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
while (input.length < 8) {
|
|
71
|
+
input = input + input;
|
|
72
|
+
}
|
|
73
|
+
for (var i = 0; i < input.length; i++) {
|
|
74
|
+
// JS doesn't respond to integer overflow by wrapping around. Simulate it with bitwise operators ( | 0)
|
|
75
|
+
hash = ((((hash << 5) + hash) | 0) + input.charCodeAt(i)) | 0;
|
|
76
|
+
}
|
|
77
|
+
hash = hash <= csharpMin ? csharpMax : Math.abs(hash);
|
|
78
|
+
return (hash / csharpMax) * 100;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=sampling.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sampling.js","sourceRoot":"","sources":["../../src/sampling.ts"],"names":[],"mappings":"AAGA,OAAO,EAAW,gBAAgB,EAAkB,MAAM,+BAA+B,CAAC;AAC1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAE/E;;;;;GAKG;AACH,MAAM,OAAO,0BAA0B;IAIrC,YAAY,gBAAwB,CAAC;QACnC,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;QACpC,IAAI,IAAI,CAAC,cAAc,GAAG,CAAC,EAAE;YAC3B,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;SACtE;QACD,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,CAAC;IAC3D,CAAC;IAED;;;;;;;;;;;;;OAaG;IACI,YAAY;IACjB,aAAa;IACb,OAAgB,EAChB,OAAe;IACf,aAAa;IACb,QAAgB;IAChB,aAAa;IACb,QAAkB,EAClB,UAAsB;IACtB,aAAa;IACb,KAAa;QAEb,IAAI,WAAW,GAAG,KAAK,CAAC;QACxB,IAAI,IAAI,CAAC,WAAW,IAAI,GAAG,EAAE;YAC3B,WAAW,GAAG,IAAI,CAAC;SACpB;aAAM,IAAI,IAAI,CAAC,WAAW,IAAI,CAAC,EAAE;YAChC,WAAW,GAAG,KAAK,CAAC;SACrB;aAAM;YACL,WAAW,GAAG,IAAI,CAAC,oBAAoB,CAAC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IAClC,CAAC;CACF","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\nimport { Link, Attributes, SpanKind, Context } from \"@opentelemetry/api\";\nimport { Sampler, SamplingDecision, SamplingResult } from \"@opentelemetry/sdk-trace-base\";\nimport { AzureMonitorSampleRate } from \"./utils/constants/applicationinsights\";\n\n/**\n * ApplicationInsightsSampler is responsible for the following:\n * Implements same trace id hashing algorithm so that traces are sampled the same across multiple nodes\n * Adds item count to span attribute if span is sampled (needed for ingestion service)\n * @param samplingRatio - 0 to 1 value.\n */\nexport class ApplicationInsightsSampler implements Sampler {\n private readonly _sampleRate: number;\n private readonly _samplingRatio: number;\n\n constructor(samplingRatio: number = 1) {\n this._samplingRatio = samplingRatio;\n if (this._samplingRatio > 1) {\n throw new Error(\"Wrong sampling rate, data will not be sampled out\");\n }\n this._sampleRate = Math.round(this._samplingRatio * 100);\n }\n\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of SpanAttributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n public shouldSample(\n // @ts-ignore\n context: Context,\n traceId: string,\n // @ts-ignore\n spanName: string,\n // @ts-ignore\n spanKind: SpanKind,\n attributes: Attributes,\n // @ts-ignore\n links: Link[]\n ): SamplingResult {\n let isSampledIn = false;\n if (this._sampleRate == 100) {\n isSampledIn = true;\n } else if (this._sampleRate == 0) {\n isSampledIn = false;\n } else {\n isSampledIn = this._getSamplingHashCode(traceId) < this._sampleRate;\n }\n // Add sample rate as span attribute\n attributes = attributes || {};\n attributes[AzureMonitorSampleRate] = this._sampleRate;\n return isSampledIn\n ? { decision: SamplingDecision.RECORD_AND_SAMPLED, attributes: attributes }\n : { decision: SamplingDecision.NOT_RECORD, attributes: attributes };\n }\n\n /**\n * Return Sampler description\n */\n public toString(): string {\n return `ApplicationInsightsSampler{${this._samplingRatio}}`;\n }\n\n private _getSamplingHashCode(input: string): number {\n var csharpMin = -2147483648;\n var csharpMax = 2147483647;\n var hash = 5381;\n\n if (!input) {\n return 0;\n }\n\n while (input.length < 8) {\n input = input + input;\n }\n\n for (var i = 0; i < input.length; i++) {\n // JS doesn't respond to integer overflow by wrapping around. Simulate it with bitwise operators ( | 0)\n hash = ((((hash << 5) + hash) | 0) + input.charCodeAt(i)) | 0;\n }\n\n hash = hash <= csharpMin ? csharpMax : Math.abs(hash);\n return (hash / csharpMax) * 100;\n }\n}\n"]}
|
|
@@ -11,7 +11,9 @@ export function isRetriable(statusCode) {
|
|
|
11
11
|
statusCode === 408 || // Timeout
|
|
12
12
|
statusCode === 429 || // Too many requests
|
|
13
13
|
statusCode === 500 || // Server Error
|
|
14
|
-
statusCode ===
|
|
14
|
+
statusCode === 502 || // Bad Gateway
|
|
15
|
+
statusCode === 503 || // Server Unavailable
|
|
16
|
+
statusCode === 504 // Gateway Timeout
|
|
15
17
|
);
|
|
16
18
|
}
|
|
17
19
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"breezeUtils.js","sourceRoot":"","sources":["../../../src/utils/breezeUtils.ts"],"names":[],"mappings":"AAAA,uCAAuC;AACvC,kCAAkC;AAsBlC;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,UAAkB;IAC5C,OAAO,CACL,UAAU,KAAK,GAAG,IAAI,iBAAiB;QACvC,UAAU,KAAK,GAAG,IAAI,eAAe;QACrC,UAAU,KAAK,GAAG,IAAI,YAAY;QAClC,UAAU,KAAK,GAAG,IAAI,UAAU;QAChC,UAAU,KAAK,GAAG,IAAI,oBAAoB;QAC1C,UAAU,KAAK,GAAG,IAAI,eAAe;QACrC,UAAU,KAAK,GAAG,
|
|
1
|
+
{"version":3,"file":"breezeUtils.js","sourceRoot":"","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AI,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IAEzD,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IAC7C,GAAG,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;IACvC,IAAI,GAAG,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IAC3C,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;IAE5C,OAAO,GAAG,QAAQ,GAAG,IAAI,IAAI,GAAG,IAAI,GAAG,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n/**\n * Breeze errors.\n * @internal\n */\nexport interface BreezeError {\n index: number;\n statusCode: number;\n message: string;\n}\n\n/**\n * Breeze response definition.\n * @internal\n */\nexport interface BreezeResponse {\n itemsReceived: number;\n itemsAccepted: number;\n errors: BreezeError[];\n}\n\n/**\n * Breeze retriable status codes.\n * @internal\n */\nexport function isRetriable(statusCode: number): boolean {\n return (\n statusCode === 206 || // Partial Accept\n statusCode === 401 || // Unauthorized\n statusCode === 403 || // Forbidden\n statusCode === 408 || // Timeout\n statusCode === 429 || // Too many requests\n statusCode === 500 || // Server Error\n statusCode === 502 || // Bad Gateway\n statusCode === 503 || // Server Unavailable\n statusCode === 504 // Gateway Timeout\n );\n}\n\n/**\n * Convert milliseconds to Breeze expected time.\n * @internal\n */\nexport function msToTimeSpan(ms: number): string {\n let totalms = ms;\n if (Number.isNaN(totalms) || totalms < 0 || !Number.isFinite(ms)) {\n totalms = 0;\n }\n\n let sec = ((totalms / 1000) % 60).toFixed(7).replace(/0{0,4}$/, \"\");\n let min = `${Math.floor(totalms / (1000 * 60)) % 60}`;\n let hour = `${Math.floor(totalms / (1000 * 60 * 60)) % 24}`;\n const days = Math.floor(totalms / (1000 * 60 * 60 * 24));\n\n sec = sec.indexOf(\".\") < 2 ? `0${sec}` : sec;\n min = min.length < 2 ? `0${min}` : min;\n hour = hour.length < 2 ? `0${hour}` : hour;\n const daysText = days > 0 ? `${days}.` : \"\";\n\n return `${daysText + hour}:${min}:${sec}`;\n}\n"]}
|