Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support koa #23

Open
wants to merge 30 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,6 @@ Start your application with the `DEBUG=opentracing-auto*` environment variable.

- More database instrumentation: Redis etc.
- More messaging layer instrumentation: HTTP/2, GRPC, RabbitMQ, Kafka etc.

## 3.x
- support koa 1.x
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@risingstack/opentracing-auto",
"version": "1.5.2",
"name": "@guanghe/primary-opentracing-auto",
"version": "4.0.4",
"description": "Out of the box OpenTracing instrumentation for Node.js",
"main": "src/index.js",
"scripts": {
Expand Down
4 changes: 4 additions & 0 deletions src/constant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/* eslint-disable strict */
const MIN_ERROR_CODE = 500

module.exports = { MIN_ERROR_CODE }
21 changes: 14 additions & 7 deletions src/instrumentation/express.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const { Tags, FORMAT_HTTP_HEADERS } = require('opentracing')
const shimmer = require('shimmer')
const METHODS = require('methods').concat('use', 'route', 'param', 'all')
const cls = require('../cls')
const { MIN_ERROR_CODE } = require('../constant')

const OPERATION_NAME = 'http_server'
const TAG_REQUEST_PATH = 'request_path'
Expand All @@ -25,16 +26,22 @@ function patch (express, tracers) {
// start
const url = `${req.protocol}://${req.get('host')}${req.originalUrl}`
const parentSpanContexts = tracers.map((tracer) => tracer.extract(FORMAT_HTTP_HEADERS, req.headers))
const spans = parentSpanContexts.map((parentSpanContext, key) =>
cls.startRootSpan(tracers[key], OPERATION_NAME, {
const SPAN_NAME = req.route ? req.route.path : OPERATION_NAME
const spans = parentSpanContexts.map((parentSpanContext, key) => {
if (req.method === 'OPTIONS') {
debug(`OPTIONS skiped ${SPAN_NAME}`)
return null
}
return cls.startRootSpan(tracers[key], SPAN_NAME, {
childOf: parentSpanContext,
tags: {
[Tags.SPAN_KIND]: Tags.SPAN_KIND_RPC_SERVER,
[Tags.HTTP_URL]: url,
[Tags.HTTP_METHOD]: req.method
}
}))
debug(`Operation started ${OPERATION_NAME}`, {
})
}).filter((span) => !!span)
debug(`Operation started ${SPAN_NAME}`, {
[Tags.HTTP_URL]: url,
[Tags.HTTP_METHOD]: req.method
})
Expand All @@ -56,18 +63,18 @@ function patch (express, tracers) {

spans.forEach((span) => span.setTag(Tags.HTTP_STATUS_CODE, res.statusCode))

if (res.statusCode >= 400) {
if (res.statusCode >= MIN_ERROR_CODE) {
spans.forEach((span) => span.setTag(Tags.ERROR, true))

debug(`Operation error captured ${OPERATION_NAME}`, {
debug(`Operation error captured ${SPAN_NAME}`, {
reason: 'Bad status code',
statusCode: res.statusCode
})
}

spans.forEach((span) => span.finish())

debug(`Operation finished ${OPERATION_NAME}`, {
debug(`Operation finished ${SPAN_NAME}`, {
[Tags.HTTP_STATUS_CODE]: res.statusCode
})

Expand Down
14 changes: 8 additions & 6 deletions src/instrumentation/expressError.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const shimmer = require('shimmer')
const { Tags } = require('opentracing')
const cls = require('../cls')


const OPERATION_NAME = 'express_error_handler'
const wrappedLayers = new Set()

Expand All @@ -29,20 +30,21 @@ function patch (express, tracers) {

shimmer.wrap(lastLayer, 'handle_error', (originalHandleError) =>
function (err, req, res, next) {
const rootSpans = tracers.map((tracer) => cls.getRootSpan(tracer))

const SPAN_NAME = req.route ? req.route.path : OPERATION_NAME
let rootSpans = tracers.map((tracer) => cls.getRootSpan(tracer))
rootSpans = rootSpans.filter((rootSpan) => rootSpan)
if (rootSpans.length) {
rootSpans.forEach((rootSpan) => rootSpan.setTag(Tags.ERROR, true))
}

// error span
const spans = tracers.map((tracer) => cls.startChildSpan(tracer, OPERATION_NAME, {
const spans = tracers.map((tracer) => cls.startChildSpan(tracer, SPAN_NAME, {
tags: {
[Tags.ERROR]: true
}
}))

debug(`Operation started ${OPERATION_NAME}`)
debug(`Operation started ${SPAN_NAME}`)

spans.forEach((span) => span.log({
event: 'error',
Expand All @@ -51,13 +53,13 @@ function patch (express, tracers) {
stack: err.stack
}))

debug(`Operation error captured ${OPERATION_NAME}`, {
debug(`Operation error captured ${SPAN_NAME}`, {
reason: 'Error handler'
})

spans.forEach((span) => span.finish())

debug(`Operation finished ${OPERATION_NAME}`)
debug(`Operation finished ${SPAN_NAME}`)

return originalHandleError.call(this, err, req, res, next)
})
Expand Down
49 changes: 49 additions & 0 deletions src/instrumentation/grpc-caller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
'use strict'

const debug = require('debug')('opentracing-auto:instrumentation:httpClient')
const { FORMAT_HTTP_HEADERS } = require('opentracing')
const shimmer = require('shimmer')
const cls = require('../cls')

function patch (grpcCaller, tracers) {
const original = grpcCaller.wrap
grpcCaller.wrap = _wrap(original)
function _wrap (original) {
return function (...args) {
const instance = original(...args)
const proto = Object.getPrototypeOf(instance)
const keys = Object.keys(proto)
keys.forEach((fnName) => {
if (fnName === 'constructor') {
return
}
if (fnName === 'exec') {
return
}
const oldFn = proto[fnName]
proto[fnName] = (arg, metadata, options, fn) => {
const spans = tracers.map((tracer) => cls.getRootSpan(tracer))
if (!metadata) {
metadata = {}
}
tracers.forEach((tracer, key) => tracer.inject(spans[key], FORMAT_HTTP_HEADERS, metadata))
return oldFn.bind(instance)(arg, metadata, options, fn)
}
})
return instance
}
}
debug('Patched')
}

function unpatch (grpcCaller) {
shimmer.unwrap(grpcCaller, 'wrap')
debug('Unpatched')
}

module.exports = {
name: '@guanghe/grpc-caller',
module: '@guanghe/grpc-caller',
patch,
unpatch
}
29 changes: 19 additions & 10 deletions src/instrumentation/httpClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ const _ = require('lodash')
const httpAgent = require('_http_agent')
const semver = require('semver')
const cls = require('../cls')
const { getOriginUrlWithoutQs } = require('./utils')


const OPERATION_NAME = 'http_request'
const OPERATION_NAME_DNS_LOOKUP = `${OPERATION_NAME}_dns_lookup`
Expand Down Expand Up @@ -99,14 +101,21 @@ function patch (http, tracers, { httpTimings } = {}) {
}

const uri = extractUrl(options)
const SPAN_NAME = getOriginUrlWithoutQs(options.path || options.pathName) || OPERATION_NAME
const method = options.method || 'GET'
const spans = tracers.map((tracer) => cls.startChildSpan(tracer, OPERATION_NAME, {
tags: {
[Tags.SPAN_KIND]: Tags.SPAN_KIND_RPC_CLIENT,
[Tags.HTTP_URL]: uri,
[Tags.HTTP_METHOD]: method
const spans = tracers.map((tracer) => {
if (uri.indexOf('/api/traces') >= 0) {
debug(`match /api/traces skip span ${uri}`)
return null
}
}))
return cls.startChildSpan(tracer, SPAN_NAME, {
tags: {
[Tags.SPAN_KIND]: Tags.SPAN_KIND_RPC_CLIENT,
[Tags.HTTP_URL]: uri,
[Tags.HTTP_METHOD]: method
}
})
}).filter((span) => !!span)

const timings = {
begin: undefined,
Expand All @@ -118,7 +127,7 @@ function patch (http, tracers, { httpTimings } = {}) {
}
let isFinish = false

debug(`Operation started ${OPERATION_NAME}`, {
debug(`Operation started ${SPAN_NAME}`, {
[Tags.HTTP_URL]: uri,
[Tags.HTTP_METHOD]: method
})
Expand All @@ -144,7 +153,7 @@ function patch (http, tracers, { httpTimings } = {}) {
if (res.statusCode > 399) {
spans.forEach((span) => span.setTag(Tags.ERROR, true))

debug(`Operation error captured ${OPERATION_NAME}`, {
debug(`Operation error captured ${SPAN_NAME}`, {
reason: 'Bad status code',
statusCode: res.statusCode
})
Expand All @@ -168,7 +177,7 @@ function patch (http, tracers, { httpTimings } = {}) {
finish(res)
})

debug(`Operation finished ${OPERATION_NAME}`, {
debug(`Operation finished ${SPAN_NAME}`, {
[Tags.HTTP_STATUS_CODE]: res.statusCode
})

Expand Down Expand Up @@ -207,7 +216,7 @@ function patch (http, tracers, { httpTimings } = {}) {
stack: err.stack
}))

debug(`Operation error captured ${OPERATION_NAME}`, {
debug(`Operation error captured ${SPAN_NAME}`, {
reason: 'Error event',
errorMessage: err.message
})
Expand Down
Loading