-
Notifications
You must be signed in to change notification settings - Fork 227
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: rewrite ioredis instrumentation: run-context, add destination co…
…ntext, captureError (#2460) - This fixes run-context handling for proper parent/child relationships. The run-context in code in the same tick and the optional callback are no longer changed. - Add destination context, so ioredis usage shows redis on the Service Map. - Capture an error and set the span outcome to "failure" if the command errors. - No longer double-instrument queued ioredis commands - Limit the number of ioredis versions tested, it is one of the top 5 longest to run. Fixes: #2459 Refs: #2430
- Loading branch information
Showing
6 changed files
with
146 additions
and
73 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
#!/usr/bin/env node --unhandled-rejections=strict | ||
|
||
// A small example showing Elastic APM tracing the 'ioredis' package. | ||
// | ||
// This assumes a Redis server running on localhost. You can use: | ||
// npm run docker:start | ||
// to start an Redis docker container (and other containers used for | ||
// testing of this project). Then `npm run docker:stop` to stop them. | ||
|
||
const apm = require('../').start({ // elastic-apm-node | ||
serviceName: 'example-trace-ioredis' | ||
}) | ||
|
||
const Redis = require('ioredis') | ||
const redis = new Redis() | ||
|
||
// Convenience printer for redis client callbacks. | ||
function printerCb (name) { | ||
return function (err, results) { | ||
console.log('%s: %o', name, err ? `${err.name}: ${err.message}` : results) | ||
} | ||
} | ||
|
||
// For tracing spans to be created, there must be an active transaction. | ||
// Typically, a transaction is automatically started for incoming HTTP | ||
// requests to a Node.js server. However, because this script is not running | ||
// an HTTP server, we manually start a transaction. More details at: | ||
// https://www.elastic.co/guide/en/apm/agent/nodejs/current/custom-transactions.html | ||
const t1 = apm.startTransaction('t1') | ||
|
||
redis.set('foo', 'bar') | ||
redis.get('foo', printerCb('GET foo')) | ||
redis.get('foo').then(function (result) { | ||
console.log('GET foo (with promise):', result) | ||
}) | ||
|
||
// Transactions. | ||
redis | ||
.multi() | ||
.set('foo', 'bar', printerCb('SET in MULTI')) | ||
.get('foo') | ||
.exec(printerCb('EXEC')) | ||
|
||
// Error capture. | ||
redis.hset('a', 'b', 'c') | ||
redis.get('a', printerCb('GET a (wrong type)')) | ||
|
||
t1.end() | ||
redis.quit() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,81 +1,69 @@ | ||
'use strict' | ||
|
||
var semver = require('semver') | ||
// Instrumentation of the 'ioredis' package: | ||
// https://github.com/luin/ioredis | ||
// https://github.com/luin/ioredis/blob/master/API.md | ||
|
||
var shimmer = require('../shimmer') | ||
const semver = require('semver') | ||
|
||
var spanSym = Symbol('elasticAPMSpan') | ||
const constants = require('../../constants') | ||
const { getDBDestination } = require('../context') | ||
const shimmer = require('../shimmer') | ||
|
||
const TYPE = 'cache' | ||
const SUBTYPE = 'redis' | ||
const hasIoredisSpanSym = Symbol('ElasticAPMHasIoredisSpan') | ||
|
||
module.exports = function (ioredis, agent, { version, enabled }) { | ||
if (!enabled) { | ||
return ioredis | ||
} | ||
if (!semver.satisfies(version, '>=2.0.0 <5.0.0')) { | ||
agent.logger.debug('ioredis version %s not supported - aborting...', version) | ||
return ioredis | ||
} | ||
|
||
agent.logger.debug('shimming ioredis.Command.prototype.initPromise') | ||
shimmer.wrap(ioredis.Command && ioredis.Command.prototype, 'initPromise', wrapInitPromise) | ||
|
||
if (!enabled) return ioredis | ||
const ins = agent._instrumentation | ||
|
||
agent.logger.debug('shimming ioredis.prototype.sendCommand') | ||
shimmer.wrap(ioredis.prototype, 'sendCommand', wrapSendCommand) | ||
|
||
return ioredis | ||
|
||
// wrap initPromise to allow us to get notified when the callback to a | ||
// command is called. If we don't do this we will still get notified because | ||
// we register a callback with command.promise.finally the | ||
// wrappedSendCommand, but the finally call will not get fired until the tick | ||
// after the command.callback have fired, so if the transaction is ended in | ||
// the same tick as the call to command.callback, we'll lose the last span | ||
// as it hasn't yet ended. | ||
function wrapInitPromise (original) { | ||
return function wrappedInitPromise () { | ||
var command = this | ||
var cb = this.callback | ||
|
||
if (typeof cb === 'function') { | ||
this.callback = agent._instrumentation.bindFunction(function wrappedCallback () { | ||
var span = command[spanSym] | ||
if (span && !span.ended) span.end() | ||
return cb.apply(this, arguments) | ||
}) | ||
} | ||
|
||
return original.apply(this, arguments) | ||
} | ||
} | ||
|
||
function wrapSendCommand (original) { | ||
function wrapSendCommand (origSendCommand) { | ||
return function wrappedSendCommand (command) { | ||
var span = agent.startSpan(null, 'cache', 'redis') | ||
var id = span && span.transaction.id | ||
|
||
agent.logger.debug('intercepted call to ioredis.prototype.sendCommand %o', { id: id, command: command && command.name }) | ||
if (!command || !command.name || !command.promise) { | ||
// Doesn't look like an ioredis.Command, skip instrumenting. | ||
return origSendCommand.apply(this, arguments) | ||
} | ||
if (command[hasIoredisSpanSym]) { | ||
// Avoid double-instrumenting a command when ioredis *re*-calls | ||
// sendCommand for queued commands when "ready". | ||
return origSendCommand.apply(this, arguments) | ||
} | ||
|
||
if (span && command) { | ||
// store span on command to it can be accessed by callback in initPromise | ||
command[spanSym] = span | ||
agent.logger.debug({ command: command.name }, 'intercepted call to ioredis.prototype.sendCommand') | ||
const span = ins.createSpan(command.name.toUpperCase(), TYPE, SUBTYPE) | ||
if (!span) { | ||
return origSendCommand.apply(this, arguments) | ||
} | ||
|
||
if (typeof command.resolve === 'function') { | ||
command.resolve = agent._instrumentation.bindFunction(command.resolve) | ||
} | ||
if (typeof command.reject === 'function') { | ||
command.reject = agent._instrumentation.bindFunction(command.reject) | ||
} | ||
if (command.promise) { | ||
const endSpan = function () { | ||
if (!span.ended) span.end() | ||
} | ||
if (typeof command.promise.then === 'function') { | ||
command.promise.then(endSpan).catch(endSpan) | ||
} | ||
} | ||
command[hasIoredisSpanSym] = true | ||
|
||
span.name = String(command.name).toUpperCase() | ||
} | ||
const options = this.options || {} // `this` is the `Redis` client. | ||
span.setDestinationContext(getDBDestination(span, options.host, options.port)) | ||
|
||
return original.apply(this, arguments) | ||
const spanRunContext = ins.currRunContext().enterSpan(span) | ||
command.promise.then( | ||
() => { | ||
span.end() | ||
}, | ||
ins.bindFunctionToRunContext(spanRunContext, (err) => { | ||
span._setOutcomeFromErrorCapture(constants.OUTCOME_FAILURE) | ||
agent.captureError(err, { skipOutcome: true }) | ||
span.end() | ||
}) | ||
) | ||
return ins.withRunContext(spanRunContext, origSendCommand, this, ...arguments) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters