-
Notifications
You must be signed in to change notification settings - Fork 38
/
elasticsearch.ts
178 lines (157 loc) · 6.61 KB
/
elasticsearch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import { diag, context, trace, Span } from '@opentelemetry/api';
import { suppressTracing } from '@opentelemetry/core';
import type elasticsearch from '@elastic/elasticsearch';
import { ElasticsearchInstrumentationConfig } from './types';
import {
InstrumentationBase,
InstrumentationModuleDefinition,
InstrumentationNodeModuleDefinition,
InstrumentationNodeModuleFile,
} from '@opentelemetry/instrumentation';
import { VERSION } from './version';
import { AttributeNames } from './enums';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import {
startSpan,
onError,
onResponse,
defaultDbStatementSerializer,
normalizeArguments,
getIndexName,
} from './utils';
import { ELASTICSEARCH_API_FILES } from './helpers';
export class ElasticsearchInstrumentation extends InstrumentationBase<typeof elasticsearch> {
static readonly component = '@elastic/elasticsearch';
protected override _config: ElasticsearchInstrumentationConfig;
private _isEnabled = false;
private moduleVersion: string;
constructor(config: ElasticsearchInstrumentationConfig = {}) {
super('opentelemetry-instrumentation-elasticsearch', VERSION, Object.assign({}, config));
}
override setConfig(config: ElasticsearchInstrumentationConfig = {}) {
this._config = Object.assign({}, config);
}
protected init(): InstrumentationModuleDefinition<typeof elasticsearch> {
const apiModuleFiles = ELASTICSEARCH_API_FILES.map(
({ path, operationClassName }) =>
new InstrumentationNodeModuleFile<any>(
`@elastic/elasticsearch/api/${path}`,
['*'],
this.patch.bind(this, operationClassName),
this.unpatch.bind(this)
)
);
const module = new InstrumentationNodeModuleDefinition<typeof elasticsearch>(
ElasticsearchInstrumentation.component,
['*'],
undefined,
undefined,
apiModuleFiles
);
return module;
}
private patchObject(operationClassName: string, object) {
Object.keys(object).forEach((functionName) => {
if (typeof object[functionName] === 'object') {
this.patchObject(functionName, object[functionName]);
} else {
this._wrap(object, functionName, this.wrappedApiRequest.bind(this, operationClassName, functionName));
}
});
}
protected patch(operationClassName: string, moduleExports, moduleVersion: string) {
diag.debug(`elasticsearch instrumentation: patch elasticsearch ${operationClassName}.`);
this.moduleVersion = moduleVersion;
this._isEnabled = true;
const modulePrototypeKeys = Object.keys(moduleExports.prototype);
if (modulePrototypeKeys.length > 0) {
modulePrototypeKeys.forEach((functionName) => {
this._wrap(
moduleExports.prototype,
functionName,
this.wrappedApiRequest.bind(this, operationClassName, functionName)
);
});
return moduleExports;
}
// For versions <= 7.9.0
const self = this;
return function (opts) {
const module = moduleExports(opts);
self.patchObject(operationClassName, module);
return module;
};
}
protected unpatch(moduleExports) {
diag.debug(`elasticsearch instrumentation: unpatch elasticsearch.`);
this._isEnabled = false;
const modulePrototypeKeys = Object.keys(moduleExports.prototype);
if (modulePrototypeKeys.length > 0) {
modulePrototypeKeys.forEach((functionName) => {
this._unwrap(moduleExports.prototype, functionName);
});
} else {
// Unable to unwrap function for versions <= 7.9.0. Using _isEnabled flag instead.
}
}
private wrappedApiRequest(apiClassName: string, functionName: string, originalFunction: Function) {
const self = this;
return function (...args) {
if (!self._isEnabled) {
return originalFunction.apply(this, args);
}
const [params, options, originalCallback] = normalizeArguments(args[0], args[1], args[2]);
const operation = `${apiClassName}.${functionName}`;
const span = startSpan({
tracer: self.tracer,
attributes: {
[SemanticAttributes.DB_OPERATION]: operation,
[AttributeNames.ELASTICSEARCH_INDICES]: getIndexName(params),
[SemanticAttributes.DB_STATEMENT]: (
self._config.dbStatementSerializer || defaultDbStatementSerializer
)(operation, params, options),
},
});
self._addModuleVersionIfNeeded(span);
if (originalCallback) {
const wrappedCallback = function (err, result) {
if (err) {
onError(span, err);
} else {
onResponse(span, result, self._config.responseHook);
}
return originalCallback.call(this, err, result);
};
return self._callOriginalFunction(span, () =>
originalFunction.call(this, params, options, wrappedCallback)
);
} else {
const promise = self._callOriginalFunction(span, () => originalFunction.apply(this, args));
promise.then(
(result) => {
onResponse(span, result, self._config.responseHook);
return result;
},
(err) => {
onError(span, err);
return err;
}
);
return promise;
}
};
}
private _callOriginalFunction<T>(span: Span, originalFunction: (...args: any[]) => T): T {
if (this._config?.suppressInternalInstrumentation) {
return context.with(suppressTracing(context.active()), originalFunction);
} else {
const activeContextWithSpan = trace.setSpan(context.active(), span);
return context.with(activeContextWithSpan, originalFunction);
}
}
private _addModuleVersionIfNeeded(span: Span) {
if (this._config.moduleVersionAttributeName) {
span.setAttribute(this._config.moduleVersionAttributeName, this.moduleVersion);
}
}
}