Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add otlp exporter support behind config option #745

Merged
merged 11 commits into from
Mar 14, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
514 changes: 334 additions & 180 deletions package-lock.json

Large diffs are not rendered by default.

27 changes: 14 additions & 13 deletions packages/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,19 +47,20 @@
],
"dependencies": {
"@babel/runtime": "^7.22.6",
"@opentelemetry/api": "^1.6.0",
"@opentelemetry/core": "^1.17.1",
"@opentelemetry/exporter-zipkin": "^1.17.1",
"@opentelemetry/instrumentation": "^0.44.0",
"@opentelemetry/instrumentation-document-load": "^0.33.2",
"@opentelemetry/instrumentation-fetch": "^0.44.0",
"@opentelemetry/instrumentation-xml-http-request": "^0.44.0",
"@opentelemetry/resources": "^1.17.1",
"@opentelemetry/sdk-trace-base": "^1.17.1",
"@opentelemetry/sdk-trace-web": "^1.17.1",
"@opentelemetry/semantic-conventions": "^1.17.1",
"@opentelemetry/api": "^1.7.0",
"@opentelemetry/core": "^1.21.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.48.0",
"@opentelemetry/exporter-zipkin": "^1.21.0",
"@opentelemetry/instrumentation": "^0.48.0",
"@opentelemetry/instrumentation-document-load": "^0.35.0",
"@opentelemetry/instrumentation-fetch": "^0.48.0",
"@opentelemetry/instrumentation-xml-http-request": "^0.48.0",
"@opentelemetry/resources": "^1.21.0",
"@opentelemetry/sdk-trace-base": "^1.21.0",
"@opentelemetry/sdk-trace-web": "^1.21.0",
"@opentelemetry/semantic-conventions": "^1.21.0",
"shimmer": "^1.2.1",
"web-vitals": "^3.4.0"
"web-vitals": "^3.5.2"
},
"devDependencies": {
"@babel/plugin-transform-runtime": "^7.22.9",
Expand All @@ -79,7 +80,7 @@
"browserstack-local": "^1.5.3",
"chai": "^4.3.7",
"chrome-launcher": "^1.0.0",
"chromedriver": "^119.0.1",
"chromedriver": "^121.0.0",
"codecov": "^3.8.2",
"compression": "^1.7.4",
"cors": "^2.8.5",
Expand Down
45 changes: 45 additions & 0 deletions packages/web/src/exporters/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
Copyright 2024 Splunk Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { Attributes } from '@opentelemetry/api';
import { ReadableSpan } from '@opentelemetry/sdk-trace-base';

export interface SplunkExporterConfig {
url: string;
onAttributesSerializing?: (attributes: Attributes, span: ReadableSpan) => Attributes,
xhrSender?: (url: string, data: string, headers?: Record<string, string>) => void,
beaconSender?: (url: string, data: string, headers?: Record<string, string>) => void,
}

export function NOOP_ATTRIBUTES_TRANSFORMER(attributes: Attributes): Attributes {
return attributes;
}
export function NATIVE_XHR_SENDER(url: string, data: string, headers?: Record<string, string>): void {
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
const defaultHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
Object.entries(Object.assign(Object.assign({}, defaultHeaders), headers)).forEach(([k, v]) => {
xhr.setRequestHeader(k, v);
});
xhr.send(data);
}
export function NATIVE_BEACON_SENDER(url: string, data: string, blobPropertyBag?: BlobPropertyBag): void {
const payload = blobPropertyBag ? new Blob([data], blobPropertyBag) : data;
navigator.sendBeacon(url, payload);
}
70 changes: 70 additions & 0 deletions packages/web/src/exporters/otlp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
Copyright 2024 Splunk Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { diag } from '@opentelemetry/api';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { NOOP_ATTRIBUTES_TRANSFORMER, NATIVE_XHR_SENDER, NATIVE_BEACON_SENDER, SplunkExporterConfig } from './common';
import { IExportTraceServiceRequest } from '@opentelemetry/otlp-transformer';
import { ReadableSpan } from '@opentelemetry/sdk-trace-base';

export class SplunkOTLPTraceExporter extends OTLPTraceExporter {
protected readonly _onAttributesSerializing: SplunkExporterConfig['onAttributesSerializing'];
protected readonly _xhrSender: SplunkExporterConfig['xhrSender'] = NATIVE_XHR_SENDER;
protected readonly _beaconSender: SplunkExporterConfig['beaconSender'] = typeof navigator !== 'undefined' && navigator.sendBeacon ? NATIVE_BEACON_SENDER : undefined;

constructor(options: SplunkExporterConfig) {
super(options);
this._onAttributesSerializing = options.onAttributesSerializing || NOOP_ATTRIBUTES_TRANSFORMER;
}

convert(spans: ReadableSpan[]): IExportTraceServiceRequest {
// Changes: Add attribute serializing hook to remove data before export
spans = spans.map(span => {
// @ts-expect-error Yep we're overwriting a readonly property here. Deal with it
span.attributes = this._onAttributesSerializing ? this._onAttributesSerializing(span.attributes, span) : span.attributes;
Copy link
Contributor

Choose a reason for hiding this comment

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

this._onAttributesSerializing alway true no?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

should be, tho types says maybe

return span;
});

return super.convert(spans);
}

send(
items: ReadableSpan[],
onSuccess: () => void,
): void {
if (this._shutdownOnce.isCalled) {
diag.debug('Shutdown already started. Cannot send objects');
return;
}
const serviceRequest = this.convert(items);
const body = JSON.stringify(serviceRequest);

// Changed: Determine which exporter to use at the time of export
if (document.hidden && this._beaconSender && body.length <= 64000) {
this._beaconSender(this.url, body, { type: 'application/json' });
} else {
this._xhrSender!(this.url, body, {
// These headers may only be necessary for otel's collector,
// need to test with actual ingest
Accept: 'application/json',
'Content-Type': 'application/json',
...this.headers
});
}

onSuccess();
}
}
75 changes: 75 additions & 0 deletions packages/web/src/exporters/rate-limit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
Copyright 2024 Splunk Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { Context } from '@opentelemetry/api';

import { ReadableSpan, Span, SpanProcessor } from '@opentelemetry/sdk-trace-base';

const SPAN_RATE_LIMIT_PERIOD = 30000; // millis, sweep to clear out span counts
const MAX_SPANS_PER_PERIOD_PER_COMPONENT = 100;

export class RateLimitProcessor implements SpanProcessor {
protected readonly _spanCounts = new Map<string, number>();
protected readonly _parents = new Map<string, boolean>();
protected readonly _limiterHandle: number;

constructor(
protected _processor: SpanProcessor
) {
this._limiterHandle = window.setInterval(() => {
this._spanCounts.clear();
}, SPAN_RATE_LIMIT_PERIOD);
}

forceFlush(): Promise<void> {
return this._processor.forceFlush();
}

protected _filter(span: ReadableSpan): boolean {
if (span.parentSpanId) {
this._parents.set(span.parentSpanId, true);
}
const component = (span.attributes?.component ?? 'unknown').toString();
if (!this._spanCounts.has(component)) {
this._spanCounts.set(component, -1);
t2t2 marked this conversation as resolved.
Show resolved Hide resolved
}
const counter = (this._spanCounts.get(component) || 0) + 1;
this._spanCounts.set(component, counter);

const { spanId } = span.spanContext();
if (this._parents.has(spanId)) {
this._parents.delete(spanId);
return true;
}
return counter < MAX_SPANS_PER_PERIOD_PER_COMPONENT;
}

onStart(span: Span, parentContext: Context): void {
return this._processor.onStart(span, parentContext);
}

onEnd(span: ReadableSpan): void {
if (this._filter(span)) {
this._processor.onEnd(span);
}
}

shutdown(): Promise<void> {
clearInterval(this._limiterHandle);
return this._processor.shutdown();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,32 +20,14 @@ import {
defaultStatusErrorTagName,
} from '@opentelemetry/exporter-zipkin/build/src/transform.js';
import { ExportResult, ExportResultCode } from '@opentelemetry/core';
import { limitLen } from './utils';
import { SpanAttributes, SpanKind } from '@opentelemetry/api';
import { SpanKind } from '@opentelemetry/api';
import { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';
import { limitLen } from '../utils';
import { NOOP_ATTRIBUTES_TRANSFORMER, NATIVE_XHR_SENDER, NATIVE_BEACON_SENDER, SplunkExporterConfig } from './common';

const MAX_VALUE_LIMIT = 4096;
const SPAN_RATE_LIMIT_PERIOD = 30000; // millis, sweep to clear out span counts
const MAX_SPANS_PER_PERIOD_PER_COMPONENT = 100;
const SERVICE_NAME = 'browser';

export interface SplunkExporterConfig {
beaconUrl: string;
onAttributesSerializing?: (attributes: SpanAttributes, span: ReadableSpan) => SpanAttributes,
xhrSender?: (url: string, data) => void,
beaconSender?: (url: string, data: BodyInit) => void,
}

export const NOOP_ATTRIBUTES_TRANSFORMER: SplunkExporterConfig['onAttributesSerializing'] = (attributes) => attributes;
export const NATIVE_XHR_SENDER: SplunkExporterConfig['xhrSender'] = (url: string, data) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Accept', '*/*');
xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
xhr.send(data);
};
export const NATIVE_BEACON_SENDER: SplunkExporterConfig['beaconSender'] = typeof navigator !== 'undefined' && navigator.sendBeacon ? (url, data) => navigator.sendBeacon(url, data) : undefined;

// TODO: upstream proper exports from ZipkinExporter
export interface ZipkinAnnotation {
timestamp: number;
Expand Down Expand Up @@ -83,70 +65,46 @@ export interface ZipkinSpan {
/**
* SplunkExporter is based on Zipkin V2. It includes Splunk-specific modifications.
*/
export class SplunkExporter implements SpanExporter {
export class SplunkZipkinExporter implements SpanExporter {
// TODO: a test which relies on beaconUrl needs to be fixed first
public readonly beaconUrl: string;
private readonly _onAttributesSerializing: SplunkExporterConfig['onAttributesSerializing'];
private readonly _xhrSender: SplunkExporterConfig['xhrSender'];
private readonly _beaconSender: SplunkExporterConfig['beaconSender'];
private readonly _spanCounts = new Map<string, number>();
private readonly _parents = new Map<string, boolean>();
private readonly _limiterHandle: number;

constructor({
beaconUrl,
url,
onAttributesSerializing = NOOP_ATTRIBUTES_TRANSFORMER,
xhrSender = NATIVE_XHR_SENDER,
beaconSender = NATIVE_BEACON_SENDER,
}: SplunkExporterConfig) {
this.beaconUrl = beaconUrl;
this.beaconUrl = url;
this._onAttributesSerializing = onAttributesSerializing;
this._xhrSender = xhrSender;
this._beaconSender = beaconSender;
this._limiterHandle = window.setInterval(() => {
this._spanCounts.clear();
}, SPAN_RATE_LIMIT_PERIOD);
}

export(
spans: ReadableSpan[],
resultCallback: (result: ExportResult) => void
): void {
spans = spans.filter(span => this._filter(span));
const zspans = spans.map(span => this._mapToZipkinSpan(span));
const zJson = JSON.stringify(zspans);
if (document.hidden && this._beaconSender && zJson.length <= 64000) {
this._beaconSender(this.beaconUrl, zJson);
} else {
this._xhrSender(this.beaconUrl, zJson);
this._xhrSender(this.beaconUrl, zJson, {
Accept: '*/*',
'Content-Type': 'text/plain;charset=UTF-8',
});
}
resultCallback({ code: ExportResultCode.SUCCESS });
}

shutdown(): Promise<void> {
clearInterval(this._limiterHandle);
return Promise.resolve();
}

private _filter(span: ReadableSpan) {
if (span.parentSpanId) {
this._parents.set(span.parentSpanId, true);
}
const component = (span.attributes?.component ?? 'unknown').toString();
if (!this._spanCounts.has(component)) {
this._spanCounts.set(component, -1);
}
const counter = this._spanCounts.get(component) + 1;
this._spanCounts.set(component, counter);

const { spanId } = span.spanContext();
if (this._parents.has(spanId)) {
this._parents.delete(spanId);
return true;
}
return counter < MAX_SPANS_PER_PERIOD_PER_COMPONENT;
}

private _mapToZipkinSpan(span: ReadableSpan): ZipkinSpan {
const preparedSpan = this._preTranslateSpan(span);
const zspan = toZipkinSpan(preparedSpan, SERVICE_NAME, defaultStatusCodeTagName, defaultStatusErrorTagName);
Expand Down
Loading
Loading