forked from elastic/apm-agent-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodb.js
188 lines (172 loc) · 6.29 KB
/
mongodb.js
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
/*
* Copyright Elasticsearch B.V. and other contributors where applicable.
* Licensed under the BSD 2-Clause License; you may not use this file except in
* compliance with the BSD 2-Clause License.
*/
'use strict';
const semver = require('semver');
const { getDBDestination } = require('../context');
const shimmer = require('../shimmer');
const kListenersAdded = Symbol('kListenersAdded');
// Match expected `<hostname>:<port>`, e.g. "mongo:27017", "::1:27017",
// "127.0.0.1:27017".
const HOSTNAME_PORT_RE = /^(.+):(\d+)$/;
module.exports = (mongodb, agent, { version, enabled }) => {
if (!enabled) return mongodb;
if (!semver.satisfies(version, '>=3.3 <7.0')) {
agent.logger.debug(
'mongodb version %s not instrumented (mongodb <3.3 is instrumented via mongodb-core)',
version,
);
return mongodb;
}
const ins = agent._instrumentation;
const activeSpans = new Map();
if (mongodb.instrument) {
const listener = mongodb.instrument();
listener.on('started', onStart);
listener.on('succeeded', onEnd);
listener.on('failed', onEnd);
} else if (mongodb.MongoClient) {
// mongodb 4.0+ removed the instrument() method in favor of
// listeners on the instantiated client objects. There are two mechanisms
// to get a client:
// 1. const client = new mongodb.MongoClient(...)
// 2. const client = await MongoClient.connect(...)
class MongoClientTraced extends mongodb.MongoClient {
constructor() {
// The `command*` events are only emitted if `options.monitorCommands: true`.
const args = Array.prototype.slice.call(arguments);
if (!args[1]) {
args[1] = { monitorCommands: true };
} else if (args[1].monitorCommands !== true) {
args[1] = Object.assign({}, args[1], { monitorCommands: true });
}
super(...args);
this.on('commandStarted', onStart);
this.on('commandSucceeded', onEnd);
this.on('commandFailed', onEnd);
this[kListenersAdded] = true;
}
}
Object.defineProperty(mongodb, 'MongoClient', {
enumerable: true,
get: function () {
return MongoClientTraced;
},
});
shimmer.wrap(mongodb.MongoClient, 'connect', wrapConnect);
} else {
agent.logger.warn('could not instrument mongodb@%s', version);
}
return mongodb;
// Wrap the MongoClient.connect(url, options?, callback?) static method.
// It calls back with `function (err, client)` or returns a Promise that
// resolves to the client.
// https://github.com/mongodb/node-mongodb-native/blob/v4.2.1/src/mongo_client.ts#L503-L511
//
// From versions >=4.11.0 the method uses `new this` to create the client instance. Hence
// our `MongoClientTraced`'s constructor is used and the command listeners are already
// registered. We should check if the client has already added the listeners to avoid handling
// the same events twice
// NOTE: prefering to use a Symbol over version check since internal implementation may
// change in future versions
// https://github.com/mongodb/node-mongodb-native/blob/v4.11.0/src/mongo_client.ts#L618
function wrapConnect(origConnect) {
return function wrappedConnect(url, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
if (!options.monitorCommands) {
options.monitorCommands = true;
}
if (typeof callback === 'function') {
return origConnect.call(
this,
url,
options,
function wrappedCallback(err, client) {
if (err) {
callback(err);
} else {
if (!client[kListenersAdded]) {
client.on('commandStarted', onStart);
client.on('commandSucceeded', onEnd);
client.on('commandFailed', onEnd);
client[kListenersAdded] = true;
}
callback(err, client);
}
},
);
} else {
const p = origConnect.call(this, url, options, callback);
p.then((client) => {
if (!client[kListenersAdded]) {
client.on('commandStarted', onStart);
client.on('commandSucceeded', onEnd);
client.on('commandFailed', onEnd);
client[kListenersAdded] = true;
}
});
return p;
}
};
}
function onStart(event) {
// `event` is a `CommandStartedEvent`
// https://github.com/mongodb/specifications/blob/master/source/command-monitoring/command-monitoring.rst#api
// E.g. with [email protected]:
// CommandStartedEvent {
// address: '127.0.0.1:27017',
// connectionId: 1,
// requestId: 1,
// databaseName: 'test',
// commandName: 'insert',
// command:
// { ... } }
const name = [
event.databaseName,
collectionFor(event),
event.commandName,
].join('.');
const span = ins.createSpan(name, 'db', 'mongodb', event.commandName, {
exitSpan: true,
});
if (span) {
activeSpans.set(event.requestId, span);
// Destination context.
// Per the following code it looks like "<hostname>:<port>" should be
// available via the `address` or `connectionId` field.
// https://github.com/mongodb/node-mongodb-native/blob/dd356f0ede/lib/core/connection/apm.js#L155-L169
const address = event.address || event.connectionId;
let match;
if (
address &&
typeof address === 'string' &&
(match = HOSTNAME_PORT_RE.exec(address))
) {
span._setDestinationContext(getDBDestination(match[1], match[2]));
} else {
agent.logger.trace(
'could not set destination context on mongodb span from address=%j',
address,
);
}
const dbContext = { type: 'mongodb', instance: event.databaseName };
span.setDbContext(dbContext);
}
}
function onEnd(event) {
if (!activeSpans.has(event.requestId)) return;
const span = activeSpans.get(event.requestId);
activeSpans.delete(event.requestId);
span.end(span._timer.start / 1000 + event.duration);
}
function collectionFor(event) {
const collection = event.command[event.commandName];
return typeof collection === 'string' ? collection : '$cmd';
}
};