-
Notifications
You must be signed in to change notification settings - Fork 471
/
instrumentation.ts
299 lines (280 loc) · 9.5 KB
/
instrumentation.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/*
* Copyright The OpenTelemetry Authors
*
* 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
*
* https://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 {
isWrapped,
InstrumentationBase,
InstrumentationConfig,
InstrumentationNodeModuleDefinition,
} from '@opentelemetry/instrumentation';
import {
context,
diag,
trace,
Span,
SpanKind,
SpanStatusCode,
} from '@opentelemetry/api';
import * as pgTypes from 'pg';
import * as pgPoolTypes from 'pg-pool';
import {
PgClientExtended,
NormalizedQueryConfig,
PostgresCallback,
PgPoolExtended,
PgPoolCallback,
PgInstrumentationConfig,
} from './types';
import * as utils from './utils';
import { AttributeNames } from './enums/AttributeNames';
import {
SemanticAttributes,
DbSystemValues,
} from '@opentelemetry/semantic-conventions';
import { VERSION } from './version';
const PG_POOL_COMPONENT = 'pg-pool';
export class PgInstrumentation extends InstrumentationBase {
static readonly COMPONENT = 'pg';
static readonly BASE_SPAN_NAME = PgInstrumentation.COMPONENT + '.query';
constructor(config: PgInstrumentationConfig = {}) {
super(
'@opentelemetry/instrumentation-pg',
VERSION,
Object.assign({}, config)
);
}
protected init() {
const modulePG = new InstrumentationNodeModuleDefinition<typeof pgTypes>(
'pg',
['7.*', '8.*'],
moduleExports => {
if (isWrapped(moduleExports.Client.prototype.query)) {
this._unwrap(moduleExports.Client.prototype, 'query');
}
this._wrap(
moduleExports.Client.prototype,
'query',
this._getClientQueryPatch() as never
);
return moduleExports;
},
moduleExports => {
if (isWrapped(moduleExports.Client.prototype.query)) {
this._unwrap(moduleExports.Client.prototype, 'query');
}
}
);
const modulePGPool = new InstrumentationNodeModuleDefinition<
typeof pgPoolTypes
>(
'pg-pool',
['2.*', '3.*'],
moduleExports => {
if (isWrapped(moduleExports.prototype.connect)) {
this._unwrap(moduleExports.prototype, 'connect');
}
this._wrap(
moduleExports.prototype,
'connect',
this._getPoolConnectPatch() as never
);
return moduleExports;
},
moduleExports => {
if (isWrapped(moduleExports.prototype.connect)) {
this._unwrap(moduleExports.prototype, 'connect');
}
}
);
return [modulePG, modulePGPool];
}
private _getClientQueryPatch() {
const plugin = this;
return (original: typeof pgTypes.Client.prototype.query) => {
diag.debug(
`Patching ${PgInstrumentation.COMPONENT}.Client.prototype.query`
);
return function query(this: PgClientExtended, ...args: unknown[]) {
let span: Span;
// Handle different client.query(...) signatures
if (typeof args[0] === 'string') {
const query = args[0];
if (args.length > 1 && args[1] instanceof Array) {
const params = args[1];
span = utils.handleParameterizedQuery.call(
this,
plugin.tracer,
plugin.getConfig() as PgInstrumentationConfig &
InstrumentationConfig,
query,
params
);
} else {
span = utils.handleTextQuery.call(this, plugin.tracer, query);
}
} else if (typeof args[0] === 'object') {
const queryConfig = args[0] as NormalizedQueryConfig;
span = utils.handleConfigQuery.call(
this,
plugin.tracer,
plugin.getConfig() as PgInstrumentationConfig &
InstrumentationConfig,
queryConfig
);
} else {
return utils.handleInvalidQuery.call(
this,
plugin.tracer,
original,
...args
);
}
// Bind callback to parent span
if (args.length > 0) {
const parentSpan = trace.getSpan(context.active());
if (typeof args[args.length - 1] === 'function') {
// Patch ParameterQuery callback
args[args.length - 1] = utils.patchCallback(
plugin.getConfig() as PgInstrumentationConfig &
InstrumentationConfig,
span,
args[args.length - 1] as PostgresCallback
);
// If a parent span exists, bind the callback
if (parentSpan) {
args[args.length - 1] = context.bind(
context.active(),
args[args.length - 1]
);
}
} else if (
typeof (args[0] as NormalizedQueryConfig).callback === 'function'
) {
// Patch ConfigQuery callback
let callback = utils.patchCallback(
plugin.getConfig() as PgInstrumentationConfig &
InstrumentationConfig,
span,
(args[0] as NormalizedQueryConfig).callback!
);
// If a parent span existed, bind the callback
if (parentSpan) {
callback = context.bind(context.active(), callback);
}
// Copy the callback instead of writing to args.callback so that we don't modify user's
// original callback reference
args[0] = { ...(args[0] as object), callback };
}
}
// Perform the original query
const result: unknown = original.apply(this, args as never);
// Bind promise to parent span and end the span
if (result instanceof Promise) {
return result
.then((result: unknown) => {
// Return a pass-along promise which ends the span and then goes to user's orig resolvers
return new Promise(resolve => {
utils.handleExecutionResult(
plugin.getConfig() as PgInstrumentationConfig &
InstrumentationConfig,
span,
result
);
span.end();
resolve(result);
});
})
.catch((error: Error) => {
return new Promise((_, reject) => {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message,
});
span.end();
reject(error);
});
});
}
// else returns void
return result; // void
};
};
}
private _getPoolConnectPatch() {
const plugin = this;
return (originalConnect: typeof pgPoolTypes.prototype.connect) => {
return function connect(this: PgPoolExtended, callback?: PgPoolCallback) {
const jdbcString = utils.getJDBCString(this.options);
// setup span
const span = plugin.tracer.startSpan(`${PG_POOL_COMPONENT}.connect`, {
kind: SpanKind.CLIENT,
attributes: {
[SemanticAttributes.DB_SYSTEM]: DbSystemValues.POSTGRESQL,
[SemanticAttributes.DB_NAME]: this.options.database, // required
[SemanticAttributes.NET_PEER_NAME]: this.options.host, // required
[SemanticAttributes.DB_CONNECTION_STRING]: jdbcString, // required
[SemanticAttributes.NET_PEER_PORT]: this.options.port,
[SemanticAttributes.DB_USER]: this.options.user,
[AttributeNames.IDLE_TIMEOUT_MILLIS]:
this.options.idleTimeoutMillis,
[AttributeNames.MAX_CLIENT]: this.options.maxClient,
},
});
if (callback) {
const parentSpan = trace.getSpan(context.active());
callback = utils.patchCallbackPGPool(
span,
callback
) as PgPoolCallback;
// If a parent span exists, bind the callback
if (parentSpan) {
callback = context.bind(context.active(), callback);
}
}
const connectResult: unknown = originalConnect.call(
this,
callback as never
);
// No callback was provided, return a promise instead
if (connectResult instanceof Promise) {
const connectResultPromise = connectResult as Promise<unknown>;
return context.bind(
context.active(),
connectResultPromise
.then(result => {
// Return a pass-along promise which ends the span and then goes to user's orig resolvers
return new Promise(resolve => {
span.end();
resolve(result);
});
})
.catch((error: Error) => {
return new Promise((_, reject) => {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message,
});
span.end();
reject(error);
});
})
);
}
// Else a callback was provided, so just return the result
return connectResult;
};
};
}
}