diff --git a/.circleci/config.yml b/.circleci/config.yml
index ab5b0ddceb9..29a4c16592e 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -2,6 +2,7 @@ version: 2
node_test_env: &node_test_env
RUN_POSTGRES_TESTS: 1
+ RUN_MYSQL_TESTS: 1
RUN_MONGODB_TESTS: 1
RUN_REDIS_TESTS: 1
POSTGRES_USER: postgres
@@ -11,8 +12,12 @@ node_test_env: &node_test_env
OPENTELEMETRY_REDIS_HOST: 'localhost'
OPENTELEMETRY_REDIS_PORT: 6379
MONGODB_HOST: localhost
- MONGODB_PORT: 27017
MONGODB_DB: opentelemetry-tests
+ MONGODB_PORT: 27017
+ MYSQL_USER: otel
+ MYSQL_PASSWORD: secret
+ MYSQL_DATABASE: circle_database
+ MYSQL_PORT: 3306
postgres_service: &postgres_service
image: circleci/postgres:9.6-alpine
@@ -25,6 +30,14 @@ redis_service: &redis_service
mongo_service: &mongo_service
image: mongo
+mysql_service: &mysql_service
+ image: circleci/mysql:5.7
+ environment:
+ MYSQL_USER: otel
+ MYSQL_PASSWORD: secret
+ MYSQL_DATABASE: circle_database
+ MYSQL_ROOT_PASSWORD: rootpw
+
cache_1: &cache_1
key: npm-cache-01-{{ .Environment.CIRCLE_JOB }}-{{ checksum "/tmp/checksums.txt" }}-1
paths:
@@ -57,6 +70,7 @@ cache_2: &cache_2
- packages/opentelemetry-plugin-document-load/node_modules
- packages/opentelemetry-plugin-https/node_modules
- packages/opentelemetry-plugin-postgres/opentelemetry-plugin-pg-pool/node_modules
+ - packages/opentelemetry-plugin-mysql/node_modules
- packages/opentelemetry-exporter-prometheus/node_modules
node_unit_tests: &node_unit_tests
@@ -157,6 +171,7 @@ jobs:
- image: node:8
environment: *node_test_env
- *postgres_service
+ - *mysql_service
- *redis_service
- *mongo_service
<<: *node_unit_tests
@@ -165,6 +180,7 @@ jobs:
- image: node:10
environment: *node_test_env
- *postgres_service
+ - *mysql_service
- *redis_service
- *mongo_service
<<: *node_unit_tests
@@ -173,6 +189,7 @@ jobs:
- image: node:12
environment: *node_test_env
- *postgres_service
+ - *mysql_service
- *redis_service
- *mongo_service
<<: *node_unit_tests
diff --git a/README.md b/README.md
index f643f66a005..5ac7558b4e0 100644
--- a/README.md
+++ b/README.md
@@ -109,16 +109,18 @@ OpenTelemetry is vendor-agnostic and can upload data to any backend with various
OpenTelemetry can collect tracing data automatically using plugins. Vendors/Users can also create and use their own. Currently, OpenTelemetry supports automatic tracing for:
#### Node Plugins
-- [@opentelemetry/plugin-http](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-http)
+- [@opentelemetry/plugin-dns](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-dns)
- [@opentelemetry/plugin-grpc](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-grpc)
+- [@opentelemetry/plugin-http](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-http)
- [@opentelemetry/plugin-https](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-https)
-- [@opentelemetry/plugin-dns](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-dns)
- [@opentelemetry/plugin-mongodb-core](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-mongodb-core)
+- [@opentelemetry/plugin-mysql](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-mysql)
- [@opentelemetry/plugin-pg](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-postgres/opentelemetry-plugin-pg)
- [@opentelemetry/plugin-redis](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-redis)
-- [@opentelemetry/plugin-pg-pool](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-postgres/opentelemetry-plugin-pg-pool) - WIP
-- [@opentelemetry/plugin-ioredis](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-ioredis) - WIP
-- [@opentelemetry/plugin-mysql](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-mysql) - WIP
+
+##### WIP Plugins
+- [@opentelemetry/plugin-pg-pool](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-postgres/opentelemetry-plugin-pg-pool)
+- [@opentelemetry/plugin-ioredis](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-ioredis)
#### Web Plugins
- [@opentelemetry/plugin-document-load](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-plugin-document-load)
diff --git a/examples/mysql/README.md b/examples/mysql/README.md
new file mode 100644
index 00000000000..ac25b273991
--- /dev/null
+++ b/examples/mysql/README.md
@@ -0,0 +1,74 @@
+# Overview
+
+OpenTelemetry MySQL 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 modification of the HTTP example that executes multiple parallel requests that interact with a MySQL server backend using the `mysql` npm module. The example displays traces using multiple connection methods.
+- Direct Connection Query
+- Pool Connection Query
+- Cluster Pool Connection Query
+
+
+## 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
+
+ - Run the server
+
+ ```sh
+ $ # from this directory
+ $ npm run server
+ ```
+
+ - Run the client
+
+ ```sh
+ $ # from this directory
+ $ npm run client
+ ```
+
+#### Zipkin UI
+`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
+
+ - Run the server
+
+ ```sh
+ $ # from this directory
+ $ npm run server
+ ```
+
+ - Run the client
+
+ ```sh
+ $ # from this directory
+ $ npm run client
+ ```
+#### Jaeger UI
+
+`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/mysql/client.js b/examples/mysql/client.js
new file mode 100644
index 00000000000..84555112681
--- /dev/null
+++ b/examples/mysql/client.js
@@ -0,0 +1,81 @@
+'use strict';
+
+const opentelemetry = require('@opentelemetry/core');
+const config = require('./setup');
+
+/**
+ * The trace instance needs to be initialized first, if you want to enable
+ * automatic tracing for built-in plugins (HTTP and MySQL in this case).
+ */
+config.setupTracerAndExporters('http-client-service');
+
+const http = require('http');
+const tracer = opentelemetry.getTracer();
+
+/** A function which makes requests and handles response. */
+function makeRequest() {
+ // span corresponds to outgoing requests. Here, we have manually created
+ // the span, which is created to track work that happens outside of the
+ // request lifecycle entirely.
+ const span = tracer.startSpan('makeRequest');
+
+ let queries = 0
+ let responses = 0;
+
+ tracer.withSpan(span, () => {
+ queries += 1;
+ http.get({
+ host: 'localhost',
+ port: 8080,
+ path: '/connection/query'
+ }, (response) => {
+ let body = [];
+ response.on('data', chunk => body.push(chunk));
+ response.on('end', () => {
+ responses += 1;
+ console.log(body.toString());
+ if (responses === queries) span.end();
+ });
+ });
+ });
+ tracer.withSpan(span, () => {
+ queries += 1;
+ http.get({
+ host: 'localhost',
+ port: 8080,
+ path: '/pool/query'
+ }, (response) => {
+ let body = [];
+ response.on('data', chunk => body.push(chunk));
+ response.on('end', () => {
+ responses += 1;
+ console.log(body.toString());
+ if (responses === queries) span.end();
+ });
+ });
+ });
+ tracer.withSpan(span, () => {
+ queries += 1;
+ http.get({
+ host: 'localhost',
+ port: 8080,
+ path: '/cluster/query'
+ }, (response) => {
+ let body = [];
+ response.on('data', chunk => body.push(chunk));
+ response.on('end', () => {
+ responses += 1;
+ console.log(body.toString());
+ if (responses === queries) span.end();
+ });
+ });
+ });
+
+ // The process must live for at least the interval past any traces that
+ // must be exported, or some risk being lost if they are recorded after the
+ // last export.
+ console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.')
+ setTimeout(() => { console.log('Completed.'); }, 5000);
+}
+
+makeRequest();
diff --git a/examples/mysql/images/jaeger-ui.png b/examples/mysql/images/jaeger-ui.png
new file mode 100644
index 00000000000..d584d3b38aa
Binary files /dev/null and b/examples/mysql/images/jaeger-ui.png differ
diff --git a/examples/mysql/images/zipkin-ui.png b/examples/mysql/images/zipkin-ui.png
new file mode 100644
index 00000000000..c013d64c5a0
Binary files /dev/null and b/examples/mysql/images/zipkin-ui.png differ
diff --git a/examples/mysql/package.json b/examples/mysql/package.json
new file mode 100644
index 00000000000..1f35536146b
--- /dev/null
+++ b/examples/mysql/package.json
@@ -0,0 +1,45 @@
+{
+ "name": "mysql-example",
+ "private": true,
+ "version": "0.2.0",
+ "description": "Example of mysql integration with OpenTelemetry",
+ "main": "index.js",
+ "scripts": {
+ "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",
+ "mysql",
+ "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.2.0",
+ "@opentelemetry/exporter-jaeger": "^0.2.0",
+ "@opentelemetry/exporter-zipkin": "^0.2.0",
+ "@opentelemetry/node": "^0.2.0",
+ "@opentelemetry/plugin-http": "^0.2.0",
+ "@opentelemetry/plugin-mysql": "^0.2.0",
+ "@opentelemetry/tracing": "^0.2.0",
+ "mysql": "*"
+ },
+ "homepage": "https://github.com/open-telemetry/opentelemetry-js#readme",
+ "devDependencies": {
+ "@types/mysql": "*",
+ "cross-env": "^6.0.0"
+ }
+}
diff --git a/examples/mysql/server.js b/examples/mysql/server.js
new file mode 100644
index 00000000000..0dc6c10e9c7
--- /dev/null
+++ b/examples/mysql/server.js
@@ -0,0 +1,130 @@
+'use strict';
+
+const opentelemetry = require('@opentelemetry/core');
+const config = require('./setup');
+/**
+ * The trace instance needs to be initialized first, if you want to enable
+ * automatic tracing for built-in plugins (HTTP and MySQL in this case).
+ */
+config.setupTracerAndExporters('http-mysql-server-service');
+
+const mysql = require('mysql');
+const http = require('http');
+
+const tracer = opentelemetry.getTracer();
+
+const pool = mysql.createPool({
+ host : 'localhost',
+ user : 'root',
+ password : 'secret',
+ database : 'my_db',
+});
+
+const connection = mysql.createConnection({
+ host : 'localhost',
+ user : 'root',
+ password : 'secret',
+ database : 'my_db',
+});
+
+const cluster = mysql.createPoolCluster();
+
+cluster.add({
+ host : 'localhost',
+ user : 'root',
+ password : 'secret',
+ database : 'my_db',
+})
+
+/** Starts a HTTP server that receives requests on sample server port. */
+function startServer (port) {
+ // Creates a server
+ const server = http.createServer(handleRequest);
+ // Starts the server
+ server.listen(port, err => {
+ if (err) {
+ throw err;
+ }
+ console.log(`Node HTTP listening on ${port}`);
+ });
+}
+
+/** A function which handles requests and send response. */
+function handleRequest (request, response) {
+ const currentSpan = tracer.getCurrentSpan();
+ // display traceid in the terminal
+ const {traceId} = currentSpan.context();
+ console.log(`traceid: ${traceId}`);
+ console.log(`Jaeger URL: http://localhost:16686/trace/${traceId}`)
+ console.log(`Zipkin URL: http://localhost:9411/zipkin/traces/${traceId}`)
+ try {
+ let body = [];
+ request.on('error', err => console.log(err));
+ request.on('data', chunk => body.push(chunk));
+ request.on('end', () => {
+ if (request.url === "/connection/query") {
+ handleConnectionQuery(response);
+ } else if (request.url === "/pool/query") {
+ handlePoolQuery(response);
+ } else if (request.url === "/cluster/query") {
+ handleClusterQuery(response);
+ } else {
+ handleNotFound(response);
+ }
+ });
+ } catch (err) {
+ console.log(err);
+ }
+}
+
+startServer(8080);
+
+function handlePoolQuery(response) {
+ const query = "SELECT 1 + 1 as pool_solution";
+ pool.getConnection((err, conn) => {
+ conn.query(query, (err, results, fields) => {
+ tracer.getCurrentSpan().addEvent("results");
+ if (err) {
+ console.log("Error code:", err.code);
+ response.end(err.message);
+ }
+ else {
+ response.end(`${query}: ${results[0].pool_solution}`);
+ }
+ });
+ })
+}
+
+function handleConnectionQuery(response) {
+ const query = "SELECT 1 + 1 as solution";
+ connection.query(query, (err, results, fields) => {
+ if (err) {
+ console.log("Error code:", err.code);
+ response.end(err.message);
+ }
+ else {
+ response.end(`${query}: ${results[0].solution}`);
+ }
+ });
+}
+
+function handleClusterQuery(response) {
+ const query = "SELECT 1 + 1 as cluster_solution";
+ cluster.getConnection((err, conn) => {
+ conn.query(query, (err, results, fields) => {
+ tracer.getCurrentSpan().addEvent("results");
+ if (err) {
+ console.log("Error code:", err.code);
+ response.end(err.message);
+ }
+ else {
+ response.end(`${query}: ${results[0].cluster_solution}`);
+ }
+ });
+ })
+}
+
+function handleNotFound(response) {
+ response.end("not found");
+}
+
diff --git a/examples/mysql/setup.js b/examples/mysql/setup.js
new file mode 100644
index 00000000000..d1e0185335e
--- /dev/null
+++ b/examples/mysql/setup.js
@@ -0,0 +1,36 @@
+'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');
+
+function setupTracerAndExporters(service) {
+ const tracer = new NodeTracer({
+ plugins: {
+ mysql: {
+ enabled: true,
+ path: "@opentelemetry/plugin-mysql"
+ },
+ http: {
+ enabled: true,
+ path: "@opentelemetry/plugin-http"
+ }
+ }
+ });
+
+ tracer.addSpanProcessor(new SimpleSpanProcessor(new ZipkinExporter({
+ serviceName: service,
+ })));
+ tracer.addSpanProcessor(new SimpleSpanProcessor(new JaegerExporter({
+ serviceName: service,
+ // The default flush interval is 5 seconds.
+ flushInterval: 2000
+ })));
+
+ // Initialize the OpenTelemetry APIs to use the BasicTracer bindings
+ opentelemetry.initGlobalTracer(tracer);
+}
+
+exports.setupTracerAndExporters = setupTracerAndExporters;
diff --git a/packages/opentelemetry-node/src/config.ts b/packages/opentelemetry-node/src/config.ts
index 3a484930ef4..23fe0ff63e1 100644
--- a/packages/opentelemetry-node/src/config.ts
+++ b/packages/opentelemetry-node/src/config.ts
@@ -32,6 +32,7 @@ export const DEFAULT_INSTRUMENTATION_PLUGINS: Plugins = {
grpc: { enabled: true, path: '@opentelemetry/plugin-grpc' },
http: { enabled: true, path: '@opentelemetry/plugin-http' },
https: { enabled: true, path: '@opentelemetry/plugin-https' },
+ mysql: { enabled: true, path: '@opentelemetry/plugin-mysql' },
pg: { enabled: true, path: '@opentelemetry/plugin-pg' },
redis: { enabled: true, path: '@opentelemetry/plugin-redis' },
};
diff --git a/packages/opentelemetry-plugin-mysql/.npmignore b/packages/opentelemetry-plugin-mysql/.npmignore
new file mode 100644
index 00000000000..9505ba9450f
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/.npmignore
@@ -0,0 +1,4 @@
+/bin
+/coverage
+/doc
+/test
diff --git a/packages/opentelemetry-plugin-mysql/LICENSE b/packages/opentelemetry-plugin-mysql/LICENSE
new file mode 100644
index 00000000000..261eeb9e9f8
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/packages/opentelemetry-plugin-mysql/README.md b/packages/opentelemetry-plugin-mysql/README.md
new file mode 100644
index 00000000000..253c22e0d22
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/README.md
@@ -0,0 +1,45 @@
+# OpenTelemetry mysql Instrumentation for Node.js
+[![Gitter chat][gitter-image]][gitter-url]
+[![dependencies][dependencies-image]][dependencies-url]
+[![devDependencies][devDependencies-image]][devDependencies-url]
+[![Apache License][license-image]][license-image]
+
+This module provides automatic instrumentation for [`mysql`](https://www.npmjs.com/package/mysql).
+
+For automatic instrumentation see the
+[@opentelemetry/node](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-node) package.
+
+## Installation
+
+```bash
+npm install --save @opentelemetry/plugin-mysql
+```
+
+## Supported Versions
+- `~2.0.0`
+
+## Usage
+
+```js
+const opentelemetry = require('@opentelemetry/plugin-mysql');
+
+// TODO: DEMONSTRATE API
+```
+
+## Useful links
+- For more information on OpenTelemetry, visit:
+- For more about OpenTelemetry JavaScript:
+- For help or feedback on this project, join us on [gitter][gitter-url]
+
+## License
+
+Apache 2.0 - See [LICENSE][license-url] for more information.
+
+[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg
+[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
+[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/master/LICENSE
+[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
+[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/status.svg?path=packages/opentelemetry-plugin-mysql
+[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-plugin-mysql
+[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-plugin-mysql
+[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-plugin-mysql&type=dev
diff --git a/packages/opentelemetry-plugin-mysql/package.json b/packages/opentelemetry-plugin-mysql/package.json
new file mode 100644
index 00000000000..642b949b5a0
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/package.json
@@ -0,0 +1,66 @@
+{
+ "name": "@opentelemetry/plugin-mysql",
+ "version": "0.2.0",
+ "description": "OpenTelemetry mysql automatic instrumentation package.",
+ "main": "build/src/index.js",
+ "types": "build/src/index.d.ts",
+ "repository": "open-telemetry/opentelemetry-js",
+ "scripts": {
+ "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.ts'",
+ "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../",
+ "tdd": "yarn test -- --watch-extensions ts --watch",
+ "clean": "rimraf build/*",
+ "check": "gts check",
+ "precompile": "tsc --version",
+ "compile": "tsc -p .",
+ "fix": "gts fix",
+ "prepare": "npm run compile"
+ },
+ "keywords": [
+ "opentelemetry",
+ "mysql",
+ "nodejs",
+ "tracing",
+ "profiling",
+ "plugin"
+ ],
+ "author": "OpenTelemetry Authors",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8.0.0"
+ },
+ "files": [
+ "build/src/**/*.js",
+ "build/src/**/*.d.ts",
+ "doc",
+ "LICENSE",
+ "README.md"
+ ],
+ "publishConfig": {
+ "access": "public"
+ },
+ "devDependencies": {
+ "@opentelemetry/node": "^0.2.0",
+ "@opentelemetry/tracing": "^0.2.0",
+ "@types/mocha": "^5.2.7",
+ "@types/mysql": "^2.15.4",
+ "@types/node": "^12.6.9",
+ "@types/shimmer": "^1.0.1",
+ "codecov": "^3.5.0",
+ "gts": "^1.1.0",
+ "mocha": "^6.2.0",
+ "mysql": "^2.17.1",
+ "nyc": "^14.1.1",
+ "rimraf": "^3.0.0",
+ "ts-mocha": "^6.0.0",
+ "ts-node": "^8.3.0",
+ "tslint-consistent-codestyle": "^1.15.1",
+ "tslint-microsoft-contrib": "^6.2.0",
+ "typescript": "3.7.2"
+ },
+ "dependencies": {
+ "@opentelemetry/core": "^0.2.0",
+ "@opentelemetry/types": "^0.2.0",
+ "shimmer": "^1.2.1"
+ }
+}
diff --git a/packages/opentelemetry-plugin-mysql/src/enums.ts b/packages/opentelemetry-plugin-mysql/src/enums.ts
new file mode 100644
index 00000000000..7f408bb945b
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/src/enums.ts
@@ -0,0 +1,36 @@
+/*!
+ * Copyright 2019, OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export enum AttributeNames {
+ // required by https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-semantic-conventions.md#databases-client-calls
+ COMPONENT = 'component',
+ DB_TYPE = 'db.type',
+ DB_INSTANCE = 'db.instance',
+ DB_STATEMENT = 'db.statement',
+
+ PEER_ADDRESS = 'peer.address',
+ PEER_HOSTNAME = 'peer.hostname',
+
+ // optional
+ DB_USER = 'db.user',
+
+ PEER_PORT = 'peer.port',
+ PEER_IPV4 = 'peer.ipv4',
+ PEER_IPV6 = 'peer.ipv6',
+ PEER_SERVICE = 'peer.service',
+
+ MYSQL_VALUES = 'mysql.values',
+}
diff --git a/packages/opentelemetry-plugin-mysql/src/index.ts b/packages/opentelemetry-plugin-mysql/src/index.ts
new file mode 100644
index 00000000000..69883053c37
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/src/index.ts
@@ -0,0 +1,16 @@
+/*!
+ * Copyright 2019, OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+export * from './mysql';
diff --git a/packages/opentelemetry-plugin-mysql/src/mysql.ts b/packages/opentelemetry-plugin-mysql/src/mysql.ts
new file mode 100644
index 00000000000..3255a57c2bf
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/src/mysql.ts
@@ -0,0 +1,286 @@
+/*!
+ * Copyright 2019, OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { BasePlugin } from '@opentelemetry/core';
+import { CanonicalCode, Span, SpanKind } from '@opentelemetry/types';
+import * as mysqlTypes from 'mysql';
+import * as shimmer from 'shimmer';
+import { AttributeNames } from './enums';
+import { getConnectionAttributes, getSpanName } from './utils';
+
+export class MysqlPlugin extends BasePlugin {
+ readonly moduleName = 'mysql';
+ readonly supportedVersions = ['2.*'];
+
+ static readonly COMPONENT = 'mysql';
+ static readonly DB_TYPE = 'sql';
+
+ static readonly COMMON_ATTRIBUTES = {
+ [AttributeNames.COMPONENT]: MysqlPlugin.COMPONENT,
+ [AttributeNames.DB_TYPE]: MysqlPlugin.DB_TYPE,
+ [AttributeNames.PEER_SERVICE]: MysqlPlugin.COMPONENT,
+ };
+
+ private _enabled = false;
+
+ protected patch(): typeof mysqlTypes {
+ this._enabled = true;
+ shimmer.wrap(
+ this._moduleExports,
+ 'createConnection',
+ this._patchCreateConnection() as any
+ );
+
+ shimmer.wrap(
+ this._moduleExports,
+ 'createPool',
+ this._patchCreatePool() as any
+ );
+
+ shimmer.wrap(
+ this._moduleExports,
+ 'createPoolCluster',
+ this._patchCreatePoolCluster() as any
+ );
+
+ return this._moduleExports;
+ }
+
+ protected unpatch(): void {
+ this._enabled = false;
+ shimmer.unwrap(this._moduleExports, 'createConnection');
+ shimmer.unwrap(this._moduleExports, 'createPool');
+ shimmer.unwrap(this._moduleExports, 'createPoolCluster');
+ }
+
+ // global export function
+ private _patchCreateConnection() {
+ return (originalCreateConnection: Function) => {
+ const thisPlugin = this;
+ thisPlugin._logger.debug(
+ 'MysqlPlugin#patch: patched mysql createConnection'
+ );
+
+ return function createConnection(
+ _connectionUri: string | mysqlTypes.ConnectionConfig
+ ) {
+ const originalResult = originalCreateConnection(...arguments);
+
+ // This is unwrapped on next call after unpatch
+ shimmer.wrap(
+ originalResult,
+ 'query',
+ thisPlugin._patchQuery(originalResult) as any
+ );
+
+ return originalResult;
+ };
+ };
+ }
+
+ // global export function
+ private _patchCreatePool() {
+ return (originalCreatePool: Function) => {
+ const thisPlugin = this;
+ thisPlugin._logger.debug('MysqlPlugin#patch: patched mysql createPool');
+ return function createPool(_config: string | mysqlTypes.PoolConfig) {
+ const pool = originalCreatePool(...arguments);
+
+ shimmer.wrap(pool, 'query', thisPlugin._patchQuery(pool));
+ shimmer.wrap(
+ pool,
+ 'getConnection',
+ thisPlugin._patchGetConnection(pool)
+ );
+
+ return pool;
+ };
+ };
+ }
+
+ // global export function
+ private _patchCreatePoolCluster() {
+ return (originalCreatePoolCluster: Function) => {
+ const thisPlugin = this;
+ thisPlugin._logger.debug(
+ 'MysqlPlugin#patch: patched mysql createPoolCluster'
+ );
+ return function createPool(_config: string | mysqlTypes.PoolConfig) {
+ const cluster = originalCreatePoolCluster(...arguments);
+
+ // This is unwrapped on next call after unpatch
+ shimmer.wrap(
+ cluster,
+ 'getConnection',
+ thisPlugin._patchGetConnection(cluster)
+ );
+
+ return cluster;
+ };
+ };
+ }
+
+ // method on cluster or pool
+ private _patchGetConnection(pool: mysqlTypes.Pool | mysqlTypes.PoolCluster) {
+ return (originalGetConnection: Function) => {
+ const thisPlugin = this;
+ thisPlugin._logger.debug(
+ 'MysqlPlugin#patch: patched mysql pool getConnection'
+ );
+ return function getConnection(
+ arg1?: unknown,
+ arg2?: unknown,
+ arg3?: unknown
+ ) {
+ // Unwrap if unpatch has been called
+ if (!thisPlugin._enabled) {
+ shimmer.unwrap(pool, 'getConnection');
+ return originalGetConnection.apply(pool, arguments);
+ }
+
+ if (arguments.length === 1 && typeof arg1 === 'function') {
+ const patchFn = thisPlugin._getConnectionCallbackPatchFn(arg1);
+ return originalGetConnection.call(pool, patchFn);
+ }
+ if (arguments.length === 2 && typeof arg2 === 'function') {
+ const patchFn = thisPlugin._getConnectionCallbackPatchFn(arg2);
+ return originalGetConnection.call(pool, arg1, patchFn);
+ }
+ if (arguments.length === 3 && typeof arg3 === 'function') {
+ const patchFn = thisPlugin._getConnectionCallbackPatchFn(arg3);
+ return originalGetConnection.call(pool, arg1, arg2, patchFn);
+ }
+
+ return originalGetConnection.apply(pool, arguments);
+ };
+ };
+ }
+
+ private _getConnectionCallbackPatchFn(cb: Function) {
+ const thisPlugin = this;
+ return function() {
+ if (arguments[1]) {
+ // this is the callback passed into a query
+ // no need to unwrap
+ shimmer.wrap(
+ arguments[1],
+ 'query',
+ thisPlugin._patchQuery(arguments[1])
+ );
+ }
+ if (typeof cb === 'function') {
+ cb(...arguments);
+ }
+ };
+ }
+
+ private _patchQuery(connection: mysqlTypes.Connection | mysqlTypes.Pool) {
+ return (originalQuery: Function): mysqlTypes.QueryFunction => {
+ const thisPlugin = this;
+ thisPlugin._logger.debug('MysqlPlugin: patched mysql query');
+
+ return function query(
+ query: string | mysqlTypes.Query | mysqlTypes.QueryOptions,
+ _valuesOrCallback?: unknown[] | mysqlTypes.queryCallback,
+ _callback?: mysqlTypes.queryCallback
+ ) {
+ if (!thisPlugin._enabled) {
+ shimmer.unwrap(connection, 'query');
+ return originalQuery.apply(connection, arguments);
+ }
+
+ const spanName = getSpanName(query);
+
+ const span = thisPlugin._tracer.startSpan(spanName, {
+ parent: thisPlugin._tracer.getCurrentSpan() || undefined,
+ kind: SpanKind.CLIENT,
+ attributes: {
+ ...MysqlPlugin.COMMON_ATTRIBUTES,
+ ...getConnectionAttributes(connection.config),
+ },
+ });
+
+ if (typeof query === 'string') {
+ span.setAttribute(AttributeNames.DB_STATEMENT, query);
+ } else if (typeof query === 'object') {
+ if (query.sql) {
+ span.setAttribute(AttributeNames.DB_STATEMENT, query.sql);
+ }
+
+ if (query.values) {
+ span.setAttribute(AttributeNames.MYSQL_VALUES, query.values);
+ }
+ }
+
+ if (arguments.length === 1) {
+ const streamableQuery: mysqlTypes.Query = originalQuery.apply(
+ connection,
+ arguments
+ );
+
+ return streamableQuery
+ .on('error', err =>
+ span.setStatus({
+ code: CanonicalCode.UNKNOWN,
+ message: err.message,
+ })
+ )
+ .on('end', () => {
+ span.end();
+ });
+ }
+
+ if (typeof arguments[1] === 'function') {
+ shimmer.wrap(arguments, 1, thisPlugin._patchCallbackQuery(span));
+ } else if (typeof arguments[2] === 'function') {
+ if (Array.isArray(_valuesOrCallback)) {
+ span.setAttribute(AttributeNames.MYSQL_VALUES, _valuesOrCallback);
+ } else if (arguments[2]) {
+ span.setAttribute(AttributeNames.MYSQL_VALUES, [_valuesOrCallback]);
+ }
+ shimmer.wrap(arguments, 2, thisPlugin._patchCallbackQuery(span));
+ }
+
+ return originalQuery.apply(connection, arguments);
+ };
+ };
+ }
+
+ private _patchCallbackQuery(span: Span) {
+ return (originalCallback: Function) => {
+ return function(
+ err: mysqlTypes.MysqlError | null,
+ results?: any,
+ fields?: mysqlTypes.FieldInfo[]
+ ) {
+ if (err) {
+ span.setStatus({
+ code: CanonicalCode.UNKNOWN,
+ message: err.message,
+ });
+ } else {
+ span.setStatus({
+ code: CanonicalCode.OK,
+ });
+ }
+ span.end();
+ return originalCallback(...arguments);
+ };
+ };
+ }
+}
+
+export const plugin = new MysqlPlugin();
diff --git a/packages/opentelemetry-plugin-mysql/src/types.ts b/packages/opentelemetry-plugin-mysql/src/types.ts
new file mode 100644
index 00000000000..cec9256bacd
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/src/types.ts
@@ -0,0 +1,26 @@
+/*!
+ * Copyright 2019, OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+export type ConnectionConfig = Partial<{
+ host: string;
+ port: number;
+ database: string;
+ user: string;
+}>;
+
+export type Query = Partial<{
+ sql: string;
+}>;
diff --git a/packages/opentelemetry-plugin-mysql/src/utils.ts b/packages/opentelemetry-plugin-mysql/src/utils.ts
new file mode 100644
index 00000000000..e301d14bf61
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/src/utils.ts
@@ -0,0 +1,86 @@
+/*!
+ * Copyright 2019, OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Attributes } from '@opentelemetry/types';
+import { AttributeNames } from './enums';
+import { ConnectionConfig, Query } from './types';
+
+/**
+ * Get a span name from a mysql query
+ *
+ * @param query mysql Query or string
+ */
+export function getSpanName(query: string | Query) {
+ return `mysql.query:${getCommand(query)}`;
+}
+
+/**
+ * Get the low cardinality command name from a query.
+ *
+ * @param query mysql Query or string
+ */
+function getCommand(query: string | Query) {
+ const queryString = typeof query === 'string' ? query : query.sql;
+
+ if (!queryString) {
+ return 'UNKNOWN_COMMAND';
+ }
+
+ // Command is the first non-whitespace token in the query
+ const match = queryString.match(/^\s*(\w+)/);
+ return (match && match[1]) || 'UNKNOWN_COMMAND';
+}
+
+/**
+ * Get an Attributes map from a mysql connection config object
+ *
+ * @param config ConnectionConfig
+ */
+export function getConnectionAttributes(config: ConnectionConfig): Attributes {
+ const { host, port, database, user } = getConfig(config);
+
+ return {
+ [AttributeNames.PEER_ADDRESS]: getJDBCString(host, port, database),
+ [AttributeNames.DB_INSTANCE]: database,
+ [AttributeNames.PEER_HOSTNAME]: host,
+ [AttributeNames.PEER_PORT]: port,
+ [AttributeNames.DB_USER]: user,
+ };
+}
+
+function getConfig(config: any) {
+ const { host, port, database, user } =
+ (config && config.connectionConfig) || config || {};
+ return { host, port, database, user };
+}
+
+function getJDBCString(
+ host: string | undefined,
+ port: number | undefined,
+ database: string | undefined
+) {
+ let jdbcString = `jdbc:mysql://${host || 'localhost'}`;
+
+ if (typeof port === 'number') {
+ jdbcString += `:${port}`;
+ }
+
+ if (typeof database === 'string') {
+ jdbcString += `/${database}`;
+ }
+
+ return jdbcString;
+}
diff --git a/packages/opentelemetry-plugin-mysql/test/mysql.test.ts b/packages/opentelemetry-plugin-mysql/test/mysql.test.ts
new file mode 100644
index 00000000000..600b3aa9b36
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/test/mysql.test.ts
@@ -0,0 +1,604 @@
+/*!
+ * Copyright 2019, OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { NoopLogger } from '@opentelemetry/core';
+import { NodeTracer } from '@opentelemetry/node';
+import {
+ InMemorySpanExporter,
+ SimpleSpanProcessor,
+ ReadableSpan,
+} from '@opentelemetry/tracing';
+import * as assert from 'assert';
+import * as mysql from 'mysql';
+import { MysqlPlugin, plugin } from '../src';
+import * as testUtils from './testUtils';
+import { AttributeNames } from '../src/enums';
+import { CanonicalCode } from '@opentelemetry/types';
+
+const port = parseInt(process.env.MYSQL_PORT || '33306', 10);
+const database = process.env.MYSQL_DATABASE || 'test_db';
+const host = process.env.MYSQL_HOST || '127.0.0.1';
+const user = process.env.MYSQL_USER || 'otel';
+const password = process.env.MYSQL_PASSWORD || 'secret';
+
+describe('mysql@2.x', () => {
+ let connection: mysql.Connection;
+ let pool: mysql.Pool;
+ let poolCluster: mysql.PoolCluster;
+ const tracer = new NodeTracer({ plugins: {} });
+ const logger = new NoopLogger();
+ const testMysql = process.env.RUN_MYSQL_TESTS; // For CI: assumes local mysql db is already available
+ const testMysqlLocally = process.env.RUN_MYSQL_TESTS_LOCAL; // For local: spins up local mysql db via docker
+ const shouldTest = testMysql || testMysqlLocally; // Skips these tests if false (default)
+ const memoryExporter = new InMemorySpanExporter();
+
+ before(function(done) {
+ if (!shouldTest) {
+ // this.skip() workaround
+ // https://github.com/mochajs/mocha/issues/2683#issuecomment-375629901
+ this.test!.parent!.pending = true;
+ this.skip();
+ }
+ tracer.addSpanProcessor(new SimpleSpanProcessor(memoryExporter));
+ if (testMysqlLocally) {
+ testUtils.startDocker();
+ // wait 15 seconds for docker container to start
+ this.timeout(20000);
+ setTimeout(done, 15000);
+ } else {
+ done();
+ }
+ });
+
+ after(function() {
+ if (testMysqlLocally) {
+ this.timeout(5000);
+ testUtils.cleanUpDocker();
+ }
+ });
+
+ beforeEach(function() {
+ plugin.enable(mysql, tracer, logger);
+ connection = mysql.createConnection({
+ port,
+ user,
+ host,
+ password,
+ database,
+ });
+ pool = mysql.createPool({
+ port,
+ user,
+ host,
+ password,
+ database,
+ });
+ poolCluster = mysql.createPoolCluster();
+ poolCluster.add('name', {
+ port,
+ user,
+ host,
+ password,
+ database,
+ });
+ });
+
+ afterEach(done => {
+ memoryExporter.reset();
+ plugin.disable();
+ connection.end(() => {
+ pool.end(() => {
+ poolCluster.end(() => {
+ done();
+ });
+ });
+ });
+ });
+
+ it('should export a plugin', () => {
+ assert(plugin instanceof MysqlPlugin);
+ });
+
+ it('should have correct moduleName', () => {
+ assert.strictEqual(plugin.moduleName, 'mysql');
+ });
+
+ describe('#Connection', () => {
+ it('should intercept connection.query(text: string)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+1 as solution';
+ const query = connection.query(statement);
+ let rows = 0;
+
+ query.on('result', row => {
+ assert.strictEqual(row.solution, 2);
+ rows += 1;
+ });
+
+ query.on('end', () => {
+ assert.strictEqual(rows, 1);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement);
+ done();
+ });
+ });
+ });
+
+ it('should intercept connection.query(text: string, callback)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+1 as solution';
+ connection.query(statement, (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 2);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement);
+ done();
+ });
+ });
+ });
+
+ it('should intercept connection.query(text: options, callback)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+? as solution';
+ connection.query({ sql: statement, values: [1] }, (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 2);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ });
+ });
+ });
+
+ it('should intercept connection.query(text: options, values: [], callback)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+? as solution';
+ // @ts-ignore this is documented https://github.com/mysqljs/mysql#performing-queries
+ // but does not match the typings
+ connection.query({ sql: statement }, [1], (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 2);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ });
+ });
+ });
+
+ it('should intercept connection.query(text: string, values: [], callback)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT ? as solution';
+ connection.query(statement, [1], (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 1);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ });
+ });
+ });
+
+ it('should intercept connection.query(text: string, value: any, callback)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT ? as solution';
+ connection.query(statement, 1, (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 1);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ });
+ });
+ });
+
+ it('should attach error messages to spans', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT ? as solution';
+ connection.query(statement, (err, res) => {
+ assert.ok(err);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, undefined, err!.message);
+ done();
+ });
+ });
+ });
+ });
+
+ describe('#Pool', () => {
+ it('should intercept pool.query(text: string)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+1 as solution';
+ const query = pool.query(statement);
+ let rows = 0;
+
+ query.on('result', row => {
+ assert.strictEqual(row.solution, 2);
+ rows += 1;
+ });
+
+ query.on('end', () => {
+ assert.strictEqual(rows, 1);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement);
+ done();
+ });
+ });
+ });
+
+ it('should intercept pool.getConnection().query(text: string)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+1 as solution';
+ pool.getConnection((err, conn) => {
+ const query = conn.query(statement);
+ let rows = 0;
+
+ query.on('result', row => {
+ assert.strictEqual(row.solution, 2);
+ rows += 1;
+ });
+
+ query.on('end', () => {
+ assert.strictEqual(rows, 1);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement);
+ done();
+ });
+ });
+ });
+ });
+
+ it('should intercept pool.query(text: string, callback)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+1 as solution';
+ pool.query(statement, (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 2);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement);
+ done();
+ });
+ });
+ });
+
+ it('should intercept pool.getConnection().query(text: string, callback)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+1 as solution';
+ pool.getConnection((err, conn) => {
+ conn.query(statement, (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 2);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement);
+ done();
+ });
+ });
+ });
+ });
+
+ it('should intercept pool.query(text: options, callback)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+? as solution';
+ pool.query({ sql: statement, values: [1] }, (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 2);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ });
+ });
+ });
+
+ it('should intercept pool.query(text: options, values: [], callback)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+? as solution';
+ // @ts-ignore this is documented https://github.com/mysqljs/mysql#performing-queries
+ // but does not match the typings
+ pool.query({ sql: statement }, [1], (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 2);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ });
+ });
+ });
+
+ it('should intercept pool.query(text: string, values: [], callback)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT ? as solution';
+ pool.query(statement, [1], (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 1);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ });
+ });
+ });
+
+ it('should intercept pool.query(text: string, value: any, callback)', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT ? as solution';
+ pool.query(statement, 1, (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 1);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ });
+ });
+ });
+
+ it('should attach error messages to spans', done => {
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT ? as solution';
+ pool.query(statement, (err, res) => {
+ assert.ok(err);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, undefined, err!.message);
+ done();
+ });
+ });
+ });
+ });
+
+ describe('#PoolCluster', () => {
+ it('should intercept poolClusterConnection.query(text: string)', done => {
+ poolCluster.getConnection((err, poolClusterConnection) => {
+ assert.ifError(err);
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+1 as solution';
+ const query = poolClusterConnection.query(statement);
+ let rows = 0;
+
+ query.on('result', row => {
+ assert.strictEqual(row.solution, 2);
+ rows += 1;
+ });
+
+ query.on('end', () => {
+ assert.strictEqual(rows, 1);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement);
+ done();
+ });
+ });
+ });
+ });
+
+ it('should intercept poolClusterConnection.query(text: string, callback)', done => {
+ poolCluster.getConnection((err, poolClusterConnection) => {
+ assert.ifError(err);
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+1 as solution';
+ poolClusterConnection.query(statement, (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 2);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement);
+ done();
+ });
+ });
+ });
+ });
+
+ it('should intercept poolClusterConnection.query(text: options, callback)', done => {
+ poolCluster.getConnection((err, poolClusterConnection) => {
+ assert.ifError(err);
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+? as solution';
+ poolClusterConnection.query(
+ { sql: statement, values: [1] },
+ (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 2);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ }
+ );
+ });
+ });
+ });
+
+ it('should intercept poolClusterConnection.query(text: options, values: [], callback)', done => {
+ poolCluster.getConnection((err, poolClusterConnection) => {
+ assert.ifError(err);
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1+? as solution';
+ // @ts-ignore this is documented https://github.com/mysqljs/mysql#performing-queries
+ // but does not match the typings
+ poolClusterConnection.query({ sql: statement }, [1], (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 2);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ });
+ });
+ });
+ });
+
+ it('should intercept poolClusterConnection.query(text: string, values: [], callback)', done => {
+ poolCluster.getConnection((err, poolClusterConnection) => {
+ assert.ifError(err);
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT ? as solution';
+ poolClusterConnection.query(statement, [1], (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 1);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ });
+ });
+ });
+ });
+
+ it('should intercept poolClusterConnection.query(text: string, value: any, callback)', done => {
+ poolCluster.getConnection((err, poolClusterConnection) => {
+ assert.ifError(err);
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT ? as solution';
+ poolClusterConnection.query(statement, 1, (err, res) => {
+ assert.ifError(err);
+ assert.ok(res);
+ assert.strictEqual(res[0].solution, 1);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, [1]);
+ done();
+ });
+ });
+ });
+ });
+
+ it('should attach error messages to spans', done => {
+ poolCluster.getConnection((err, poolClusterConnection) => {
+ assert.ifError(err);
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT ? as solution';
+ poolClusterConnection.query(statement, (err, res) => {
+ assert.ok(err);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement, undefined, err!.message);
+ done();
+ });
+ });
+ });
+ });
+
+ it('should get connection by name', done => {
+ poolCluster.getConnection('name', (err, poolClusterConnection) => {
+ assert.ifError(err);
+ const span = tracer.startSpan('test span');
+ tracer.withSpan(span, () => {
+ const statement = 'SELECT 1 as solution';
+ poolClusterConnection.query(statement, (err, res) => {
+ assert.ifError(err);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement);
+ done();
+ });
+ });
+ });
+ });
+
+ it('should get connection by name and selector', done => {
+ poolCluster.getConnection(
+ 'name',
+ 'ORDER',
+ (err, poolClusterConnection) => {
+ assert.ifError(err);
+ const statement = 'SELECT 1 as solution';
+ poolClusterConnection.query(statement, (err, res) => {
+ assert.ifError(err);
+ const spans = memoryExporter.getFinishedSpans();
+ assert.strictEqual(spans.length, 1);
+ assertSpan(spans[0], statement);
+ done();
+ });
+ }
+ );
+ });
+ });
+});
+
+function assertSpan(
+ span: ReadableSpan,
+ statement: string,
+ values?: any,
+ errorMessage?: string
+) {
+ assert.equal(span.attributes[AttributeNames.COMPONENT], 'mysql');
+ assert.equal(span.attributes[AttributeNames.DB_TYPE], 'sql');
+ assert.equal(span.attributes[AttributeNames.DB_INSTANCE], database);
+ assert.equal(span.attributes[AttributeNames.PEER_PORT], port);
+ assert.equal(span.attributes[AttributeNames.PEER_HOSTNAME], host);
+ assert.equal(span.attributes[AttributeNames.DB_USER], user);
+ assert.strictEqual(span.attributes[AttributeNames.DB_STATEMENT], statement);
+ if (values) {
+ assert.deepStrictEqual(
+ span.attributes[AttributeNames.MYSQL_VALUES],
+ values
+ );
+ }
+ if (errorMessage) {
+ assert.equal(span.status.message, errorMessage);
+ assert.equal(span.status.code, CanonicalCode.UNKNOWN);
+ }
+}
diff --git a/packages/opentelemetry-plugin-mysql/test/testUtils.ts b/packages/opentelemetry-plugin-mysql/test/testUtils.ts
new file mode 100644
index 00000000000..a569ff57d12
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/test/testUtils.ts
@@ -0,0 +1,55 @@
+/*!
+ * Copyright 2019, OpenTelemetry Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import * as childProcess from 'child_process';
+export function startDocker() {
+ const tasks = [
+ run(
+ 'docker run --rm -d -e MYSQL_ROOT_PASSWORD=rootpw -e MYSQL_DATABASE=test_db -e MYSQL_USER=otel -e MYSQL_PASSWORD=secret -p 33306:3306 --name otmysql circleci/mysql:5.7'
+ ),
+ ];
+
+ for (let i = 0; i < tasks.length; i++) {
+ const task = tasks[i];
+ if (task && task.code !== 0) {
+ console.error('Failed to start container!');
+ console.error(task.output);
+ return false;
+ }
+ }
+ return true;
+}
+
+export function cleanUpDocker() {
+ run('docker stop otmysql');
+}
+
+function run(cmd: string) {
+ try {
+ const proc = childProcess.spawnSync(cmd, {
+ shell: true,
+ });
+ return {
+ code: proc.status,
+ output: proc.output
+ .map(v => String.fromCharCode.apply(null, v as any))
+ .join(''),
+ };
+ } catch (e) {
+ console.log(e);
+ return;
+ }
+}
diff --git a/packages/opentelemetry-plugin-mysql/tsconfig.json b/packages/opentelemetry-plugin-mysql/tsconfig.json
new file mode 100644
index 00000000000..a2042cd68b1
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/tsconfig.json
@@ -0,0 +1,11 @@
+{
+ "extends": "../tsconfig.base",
+ "compilerOptions": {
+ "rootDir": ".",
+ "outDir": "build"
+ },
+ "include": [
+ "src/**/*.ts",
+ "test/**/*.ts"
+ ]
+}
diff --git a/packages/opentelemetry-plugin-mysql/tslint.json b/packages/opentelemetry-plugin-mysql/tslint.json
new file mode 100644
index 00000000000..0710b135d07
--- /dev/null
+++ b/packages/opentelemetry-plugin-mysql/tslint.json
@@ -0,0 +1,4 @@
+{
+ "rulesDirectory": ["node_modules/tslint-microsoft-contrib"],
+ "extends": ["../../tslint.base.js", "./node_modules/tslint-consistent-codestyle"]
+}