forked from elastic/apm-agent-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemcached.js
99 lines (85 loc) · 2.86 KB
/
memcached.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
/*
* 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';
var semver = require('semver');
var shimmer = require('../shimmer');
var { getDBDestination } = require('../context');
module.exports = function (memcached, agent, { version, enabled }) {
if (!enabled) {
return memcached;
}
if (!semver.satisfies(version, '>=2.2.0')) {
agent.logger.debug(
'Memcached version %s not supported - aborting...',
version,
);
return memcached;
}
const ins = agent._instrumentation;
agent.logger.debug('shimming memcached.prototype.command');
shimmer.wrap(memcached.prototype, 'command', wrapCommand);
shimmer.wrap(memcached.prototype, 'connect', wrapConnect);
return memcached;
function wrapConnect(original) {
return function wrappedConnect() {
const currentSpan = ins.currSpan();
const server = arguments[0];
agent.logger.debug('intercepted call to memcached.prototype.connect %o', {
server,
});
if (currentSpan) {
const [host, port = 11211] = server.split(':');
currentSpan._setDestinationContext(getDBDestination(host, port));
}
return original.apply(this, arguments);
};
}
// Wrap the generic command that is used to build touch, get, gets etc
function wrapCommand(original) {
return function wrappedCommand(queryCompiler, _server) {
if (typeof queryCompiler !== 'function') {
return original.apply(this, arguments);
}
var query = queryCompiler();
// Replace the queryCompiler function so it isn't called a second time.
arguments[0] = function prerunQueryCompiler() {
return query;
};
// If the callback is not a function the user doesn't care about result.
if (!query && typeof query.callback !== 'function') {
return original.apply(this, arguments);
}
const span = ins.createSpan(
`memcached.${query.type}`,
'db',
'memcached',
query.type,
{ exitSpan: true },
);
if (!span) {
return original.apply(this, arguments);
}
agent.logger.debug('intercepted call to memcached.prototype.command %o', {
id: span.id,
type: query.type,
});
span.setDbContext({
statement: `${query.type} ${query.key}`,
type: 'memcached',
});
const spanRunContext = ins.currRunContext().enterSpan(span);
const origCallback = query.callback;
query.callback = ins.bindFunctionToRunContext(
spanRunContext,
function tracedCallback() {
span.end();
return origCallback.apply(this, arguments);
},
);
return ins.withRunContext(spanRunContext, original, this, ...arguments);
};
}
};