diff --git a/examples/ioredis/README.md b/examples/ioredis/README.md new file mode 100644 index 0000000000..86614c4055 --- /dev/null +++ b/examples/ioredis/README.md @@ -0,0 +1,106 @@ +# Overview + +OpenTelemetry IORedis Instrumentation allows the user to automatically collect trace data and export them to the backend of choice (we can use Zipkin or Jaeger for this example), to give observability to distributed systems. + +This is a simple example that demonstrates tracing calls to a Redis cache via an Express API. The example +shows key aspects of tracing such as +- Root Span (on Client) +- Child Span (on Client) +- Child Span from a Remote Parent (on Server) +- SpanContext Propagation (from Client to Server) +- Span Events +- Span Attributes + +## Installation + +```sh +$ # from this directory +$ npm install +``` + +Setup [Zipkin Tracing](https://zipkin.io/pages/quickstart.html) +or +Setup [Jaeger Tracing](https://www.jaegertracing.io/docs/latest/getting-started/#all-in-one) + +## Run the Application + +### Zipkin + + - Start redis via docker + + ```sh + # from this directory + npm run docker:start + ``` + + - Run the server + + ```sh + # from this directory + $ npm run zipkin:server + ``` + + - Run the client + + ```sh + # from this directory + npm run zipkin:client + ``` + + - Cleanup docker + + ```sh + # from this directory + npm run docker:stop + ``` + +#### Zipkin UI +`zipkin:server` script should output the `traceid` in the terminal (e.g `traceid: 4815c3d576d930189725f1f1d1bdfcc6`). +Go to Zipkin with your browser [http://localhost:9411/zipkin/traces/(your-trace-id)]() (e.g http://localhost:9411/zipkin/traces/4815c3d576d930189725f1f1d1bdfcc6) + +

+ +### Jaeger + + - Start redis via docker + + ```sh + # from this directory + npm run docker:start + ``` + + - Run the server + + ```sh + # from this directory + $ npm run jaeger:server + ``` + + - Run the client + + ```sh + # from this directory + npm run jaeger:client + ``` + + - Cleanup docker + + ```sh + # from this directory + npm run docker:stop + ``` + +#### Jaeger UI + +`jaeger:server` script should output the `traceid` in the terminal (e.g `traceid: 4815c3d576d930189725f1f1d1bdfcc6`). +Go to Jaeger with your browser [http://localhost:16686/trace/(your-trace-id)]() (e.g http://localhost:16686/trace/4815c3d576d930189725f1f1d1bdfcc6) + +

+ +## Useful links +- For more information on OpenTelemetry, visit: +- For more information on OpenTelemetry for Node.js, visit: + +## LICENSE + +Apache License 2.0 diff --git a/examples/ioredis/client.js b/examples/ioredis/client.js new file mode 100644 index 0000000000..d68e23a2c7 --- /dev/null +++ b/examples/ioredis/client.js @@ -0,0 +1,29 @@ +'use strict'; + +// Require tracer before any other modules +const tracer = require('./tracer')('ioredis-client-service'); + +const types = require('@opentelemetry/types'); +const axios = require('axios').default; + +function makeRequest() { + const span = tracer.startSpan('client.makeRequest()', { + parent: tracer.getCurrentSpan(), + kind: types.SpanKind.CLIENT, + }); + + tracer.withSpan(span, async () => { + try { + const res = await axios.get('http://localhost:8080/run_test'); + span.setStatus({ code: types.CanonicalCode.OK }); + console.log(res.statusText); + } catch (e) { + span.setStatus({ code: types.CanonicalCode.UNKNOWN, message: e.message }); + } + span.end(); + console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.'); + setTimeout(() => { console.log('Completed.'); }, 5000); + }); +} + +makeRequest(); diff --git a/examples/ioredis/express-tracer-handlers.js b/examples/ioredis/express-tracer-handlers.js new file mode 100644 index 0000000000..7a570128d2 --- /dev/null +++ b/examples/ioredis/express-tracer-handlers.js @@ -0,0 +1,36 @@ +'use strict'; + +const types = require('@opentelemetry/types'); + +function getMiddlewareTracer(tracer) { + return (req, res, next) => { + const span = tracer.startSpan(`express.middleware.tracer(${req.method} ${req.path})`, { + parent: tracer.getCurrentSpan(), + kind: types.SpanKind.SERVER, + }); + + console.log(`traceid: ${span.context().traceId}`); + + // End this span before sending out the response + const originalSend = res.send; + res.send = function send(...args) { + span.end(); + originalSend.apply(res, args); + }; + + tracer.withSpan(span, next); + }; +} + +function getErrorTracer(tracer) { + return (err, _req, res, _next) => { + console.log('Caught error', err.message); + const span = tracer.getCurrentSpan(); + if (span) { + span.setStatus({ code: types.CanonicalCode.INTERNAL, message: err.message }); + } + res.status(500).send(err.message); + }; +} + +module.exports = { getMiddlewareTracer, getErrorTracer }; diff --git a/examples/ioredis/images/jaeger.png b/examples/ioredis/images/jaeger.png new file mode 100644 index 0000000000..b4cbb2a7e7 Binary files /dev/null and b/examples/ioredis/images/jaeger.png differ diff --git a/examples/ioredis/images/zipkin.png b/examples/ioredis/images/zipkin.png new file mode 100644 index 0000000000..95529a777c Binary files /dev/null and b/examples/ioredis/images/zipkin.png differ diff --git a/examples/ioredis/package.json b/examples/ioredis/package.json new file mode 100644 index 0000000000..35c504733c --- /dev/null +++ b/examples/ioredis/package.json @@ -0,0 +1,50 @@ +{ + "name": "ioredis-example", + "private": true, + "version": "0.3.2", + "description": "Example of HTTP integration with OpenTelemetry", + "main": "index.js", + "scripts": { + "docker:start": "docker run -d -p 6379:6379 --name otjsredis redis:alpine", + "docker:stop": "docker stop otjsredis && docker rm otjsredis", + "zipkin:server": "cross-env EXPORTER=zipkin node ./server.js", + "zipkin:client": "cross-env EXPORTER=zipkin node ./client.js", + "jaeger:server": "cross-env EXPORTER=jaeger node ./server.js", + "jaeger:client": "cross-env EXPORTER=jaeger node ./client.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/open-telemetry/opentelemetry-js.git" + }, + "keywords": [ + "opentelemetry", + "redis", + "ioredis", + "tracing" + ], + "engines": { + "node": ">=8" + }, + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/open-telemetry/opentelemetry-js/issues" + }, + "dependencies": { + "@opentelemetry/core": "^0.3.2", + "@opentelemetry/exporter-jaeger": "^0.3.2", + "@opentelemetry/exporter-zipkin": "^0.3.2", + "@opentelemetry/node": "^0.3.2", + "@opentelemetry/plugin-http": "^0.3.2", + "@opentelemetry/plugin-ioredis": "^0.3.2", + "@opentelemetry/tracing": "^0.3.2", + "@opentelemetry/types": "^0.3.2", + "axios": "^0.19.0", + "express": "^4.17.1", + "ioredis": "^4.14.1" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js#readme", + "devDependencies": { + "cross-env": "^6.0.0" + } +} diff --git a/examples/ioredis/redis.js b/examples/ioredis/redis.js new file mode 100644 index 0000000000..4dd655d915 --- /dev/null +++ b/examples/ioredis/redis.js @@ -0,0 +1,7 @@ +'use strict'; + +const Redis = require('ioredis'); + +const redis = new Redis('redis://localhost:6379'); + +module.exports = redis; diff --git a/examples/ioredis/server.js b/examples/ioredis/server.js new file mode 100644 index 0000000000..bf4d297abc --- /dev/null +++ b/examples/ioredis/server.js @@ -0,0 +1,61 @@ +'use strict'; + +// Require tracer before any other modules +const tracer = require('./tracer')('ioredis-server-service'); + +const express = require('express'); +const axios = require('axios').default; +const tracerHandlers = require('./express-tracer-handlers'); +const redis = require('./redis'); + +const app = express(); +const port = process.env.PORT || 8080; + +/** + * Redis Routes are set up async since we resolve the client once it is successfully connected + */ +async function setupRoutes() { + app.get('/run_test', async (req, res) => { + const uuid = Math.random() + .toString(36) + .substring(2, 15) + + Math.random() + .toString(36) + .substring(2, 15); + await axios.get(`http://localhost:${port}/set?args=uuid,${uuid}`); + const body = await axios.get(`http://localhost:${port}/get?args=uuid`); + + if (body.data !== uuid) { + throw new Error('UUID did not match!'); + } else { + res.sendStatus(200); + } + }); + + app.get('/:cmd', (req, res) => { + if (!req.query.args) { + res.status(400).send('No args provided'); + return; + } + + const { cmd } = req.params; + const args = req.query.args.split(','); + redis[cmd].call(redis, ...args, (err, result) => { + if (err) { + res.sendStatus(400); + } else if (result) { + res.status(200).send(result); + } else { + throw new Error('Empty redis response'); + } + }); + }); +} + +// Setup express routes & middleware +app.use(tracerHandlers.getMiddlewareTracer(tracer)); +setupRoutes().then(() => { + app.use(tracerHandlers.getErrorTracer(tracer)); + app.listen(port); + console.log(`Listening on http://localhost:${port}`); +}); diff --git a/examples/ioredis/tracer.js b/examples/ioredis/tracer.js new file mode 100644 index 0000000000..fce8920a57 --- /dev/null +++ b/examples/ioredis/tracer.js @@ -0,0 +1,31 @@ +'use strict'; + +const opentelemetry = require('@opentelemetry/core'); +const { NodeTracer } = require('@opentelemetry/node'); +const { SimpleSpanProcessor } = require('@opentelemetry/tracing'); +const { JaegerExporter } = require('@opentelemetry/exporter-jaeger'); +const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin'); + +const EXPORTER = process.env.EXPORTER || ''; + +module.exports = (serviceName) => { + const tracer = new NodeTracer(); + + let exporter; + if (EXPORTER.toLowerCase().startsWith('z')) { + exporter = new ZipkinExporter({ + serviceName, + }); + } else { + exporter = new JaegerExporter({ + serviceName, + }); + } + + tracer.addSpanProcessor(new SimpleSpanProcessor(exporter)); + + // Initialize the OpenTelemetry APIs to use the BasicTracer bindings + opentelemetry.initGlobalTracer(tracer); + + return opentelemetry.getTracer(); +};