From d7f4fe29db6c5fb431fa26816541eb46fb1567d9 Mon Sep 17 00:00:00 2001 From: Naseem Date: Fri, 24 Jan 2020 08:03:04 -0500 Subject: [PATCH] feat: lint examples (#649) * refactor: use a single eslintrc for all examples folders furthermore, override the strict rule that ships with airbnb * fix: turn off no-use-before-define * fix: install eslint in ci container Co-Authored-By: Daniel Dyla * fix: ignore uninstalled packages lint errors We will not want to install all examples in CI Co-authored-by: Daniel Dyla Co-authored-by: Mayur Kale --- .circleci/config.yml | 6 + examples/.eslintrc | 16 +++ examples/basic-tracer-node/index.js | 22 ++-- examples/basic-tracer-node/multi_exporter.js | 31 +++-- examples/dns/client.js | 56 ++++---- examples/dns/setup.js | 39 ------ examples/dns/tracer.js | 40 ++++++ examples/grpc/client.js | 21 +-- examples/grpc/helloworld_grpc_pb.js | 25 +++- examples/grpc/helloworld_pb.js | 121 +++++++++-------- examples/grpc/server.js | 19 +-- examples/grpc/{setup.js => tracer.js} | 18 +-- .../grpc_dynamic_codegen/capitalize_client.js | 21 +-- .../grpc_dynamic_codegen/capitalize_server.js | 23 ++-- .../{setup.js => tracer.js} | 17 +-- examples/http/client.js | 58 ++++---- examples/http/server.js | 27 ++-- examples/{redis/setup.js => http/tracer.js} | 11 +- examples/https/client.js | 55 ++++---- examples/https/server.js | 27 ++-- examples/https/{setup.js => tracer.js} | 12 +- examples/mysql/client.js | 124 ++++++++---------- examples/mysql/server.js | 104 +++++++-------- examples/mysql/{setup.js => tracer.js} | 18 +-- examples/opentracing-shim/client.js | 34 ++--- examples/opentracing-shim/package.json | 1 + examples/opentracing-shim/server.js | 34 ++--- examples/opentracing-shim/shim.js | 18 +-- examples/opentracing-shim/utils.js | 4 +- examples/postgres/client.js | 45 +++---- examples/postgres/server.js | 20 +-- examples/postgres/setupPsql.js | 37 +++--- examples/postgres/{setup.js => tracer.js} | 28 ++-- examples/prometheus/index.js | 32 ++--- examples/redis/client.js | 40 +++--- examples/redis/express-tracer-handlers.js | 26 ++-- examples/redis/server.js | 23 ++-- examples/redis/setup-redis.js | 6 +- examples/{http/setup.js => redis/tracer.js} | 12 +- examples/stackdriver-trace/index.js | 20 +-- examples/tracer-web/.eslintrc | 16 +++ .../examples/document-load/index.js | 55 ++++---- .../examples/xml-http-request/index.js | 42 +++--- examples/tracer-web/webpack.config.js | 31 ++--- package.json | 7 +- 45 files changed, 727 insertions(+), 715 deletions(-) create mode 100644 examples/.eslintrc delete mode 100644 examples/dns/setup.js create mode 100644 examples/dns/tracer.js rename examples/grpc/{setup.js => tracer.js} (72%) rename examples/grpc_dynamic_codegen/{setup.js => tracer.js} (82%) rename examples/{redis/setup.js => http/tracer.js} (83%) rename examples/https/{setup.js => tracer.js} (84%) rename examples/mysql/{setup.js => tracer.js} (75%) rename examples/postgres/{setup.js => tracer.js} (68%) rename examples/{http/setup.js => redis/tracer.js} (83%) create mode 100644 examples/tracer-web/.eslintrc diff --git a/.circleci/config.yml b/.circleci/config.yml index 2f7a3a4598..c9017c895a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -172,6 +172,12 @@ jobs: root: packages/opentelemetry-types/docs paths: - out + - run: + name: Install minimal modules to lint examples + command: npm i -D eslint eslint-plugin-import eslint-config-airbnb-base + - run: + name: Lint examples + command: npm run lint-examples docs-deploy: docker: - image: node:12 diff --git a/examples/.eslintrc b/examples/.eslintrc new file mode 100644 index 0000000000..5feabb97f5 --- /dev/null +++ b/examples/.eslintrc @@ -0,0 +1,16 @@ +{ + "env": { + "node": true + }, + "extends": "airbnb-base", + "parserOptions": { + "sourceType": "script" + }, + "rules": { + "strict": ["error", "global"], + "no-use-before-define": ["error", "nofunc"], + "no-console": "off", + "import/no-unresolved": "off", + "no-unused-vars": ["error", { "argsIgnorePattern": "^_" }] + } +} diff --git a/examples/basic-tracer-node/index.js b/examples/basic-tracer-node/index.js index 086d1fe158..e16b95b898 100644 --- a/examples/basic-tracer-node/index.js +++ b/examples/basic-tracer-node/index.js @@ -1,11 +1,13 @@ +'use strict'; + const opentelemetry = require('@opentelemetry/core'); const { BasicTracerRegistry, SimpleSpanProcessor } = require('@opentelemetry/tracing'); const { JaegerExporter } = require('@opentelemetry/exporter-jaeger'); const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin'); -const { CollectorExporter } = require('@opentelemetry/exporter-collector'); +const { CollectorExporter } = require('@opentelemetry/exporter-collector'); const options = { - serviceName: 'basic-service' + serviceName: 'basic-service', }; // Initialize an exporter depending on how we were started @@ -27,15 +29,15 @@ registry.addSpanProcessor(new SimpleSpanProcessor(exporter)); // Initialize the OpenTelemetry APIs to use the BasicTracerRegistry bindings opentelemetry.initGlobalTracerRegistry(registry); -const tracer = opentelemetry.getTracer('example-basic-tracer-node') +const tracer = opentelemetry.getTracer('example-basic-tracer-node'); // Create a span. A span must be closed. -const span = tracer.startSpan('main'); -for (let i = 0; i < 10; i++) { - doWork(span); +const parentSpan = tracer.startSpan('main'); +for (let i = 0; i < 10; i += 1) { + doWork(parentSpan); } // Be sure to end the span. -span.end(); +parentSpan.end(); // flush and close the connection. exporter.shutdown(); @@ -44,11 +46,13 @@ function doWork(parent) { // Start another span. In this example, the main method already started a // span, so that'll be the parent span, and this will be a child span. const span = tracer.startSpan('doWork', { - parent: parent + parent, }); // simulate some random work. - for (let i = 0; i <= Math.floor(Math.random() * 40000000); i++) { } + for (let i = 0; i <= Math.floor(Math.random() * 40000000); i += 1) { + // empty + } // Set attributes to the span. span.setAttribute('key', 'value'); diff --git a/examples/basic-tracer-node/multi_exporter.js b/examples/basic-tracer-node/multi_exporter.js index 309daf4311..aa8478dfa2 100644 --- a/examples/basic-tracer-node/multi_exporter.js +++ b/examples/basic-tracer-node/multi_exporter.js @@ -1,39 +1,44 @@ +'use strict'; + const opentelemetry = require('@opentelemetry/core'); const { BasicTracerRegistry, BatchSpanProcessor, SimpleSpanProcessor } = require('@opentelemetry/tracing'); const { JaegerExporter } = require('@opentelemetry/exporter-jaeger'); const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin'); -const { CollectorExporter } = require('@opentelemetry/exporter-collector'); +const { CollectorExporter } = require('@opentelemetry/exporter-collector'); const registry = new BasicTracerRegistry(); -const zipkinExporter = new ZipkinExporter({serviceName: 'basic-service'}); +const zipkinExporter = new ZipkinExporter({ serviceName: 'basic-service' }); const jaegerExporter = new JaegerExporter({ serviceName: 'basic-service', }); -const collectorExporter = new CollectorExporter({serviceName: 'basic-service'}); +const collectorExporter = new CollectorExporter({ serviceName: 'basic-service' }); // It is recommended to use this BatchSpanProcessor for better performance // and optimization, especially in production. registry.addSpanProcessor(new BatchSpanProcessor(zipkinExporter, { - bufferSize: 10 // This is added for example, default size is 100. + // This is added for example, default size is 100. + bufferSize: 10, })); + +const tracer = opentelemetry.getTracer('default'); + tracer.addSpanProcessor(new BatchSpanProcessor(jaegerExporter), { - bufferSize: 10 + bufferSize: 10, }); registry.addSpanProcessor(new SimpleSpanProcessor(collectorExporter)); // Initialize the OpenTelemetry APIs to use the BasicTracerRegistry bindings opentelemetry.initGlobalTracerRegistry(registry); -const tracer = opentelemetry.getTracer('default'); // Create a span. A span must be closed. -const span = tracer.startSpan('main'); -for (let i = 0; i < 10; i++) { - doWork(span); +const parentSpan = tracer.startSpan('main'); +for (let i = 0; i < 10; i += 1) { + doWork(parentSpan); } // Be sure to end the span. -span.end(); +parentSpan.end(); // flush and close the connection. zipkinExporter.shutdown(); @@ -44,11 +49,13 @@ function doWork(parent) { // Start another span. In this example, the main method already started a // span, so that'll be the parent span, and this will be a child span. const span = tracer.startSpan('doWork', { - parent: parent + parent, }); // simulate some random work. - for (let i = 0; i <= Math.floor(Math.random() * 40000000); i++) { } + for (let i = 0; i <= Math.floor(Math.random() * 40000000); i += 1) { + // empty + } // Set attributes to the span. span.setAttribute('key', 'value'); diff --git a/examples/dns/client.js b/examples/dns/client.js index 317b5b9e46..1ea52d6ce0 100644 --- a/examples/dns/client.js +++ b/examples/dns/client.js @@ -1,42 +1,34 @@ '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 (DNS in this case). - */ -config.setupTracerAndExporters('dns-client-service'); - +const tracer = require('./tracer')('example-dns'); +// eslint-disable-next-line import/order const dns = require('dns').promises; -const tracer = opentelemetry.getTracer('example-dns'); /** A function which makes a dns lookup and handles response. */ function makeLookup() { - // span corresponds to dns lookup. Here, we have manually created - // the span, which is created to track work that happens outside of the - // dns lookup query. - const span = tracer.startSpan('dnsLookup'); - tracer.withSpan(span, async () => { - try { - await dns.lookup('montreal.ca'); - } catch (error) { - span.setAttributes({ - 'error.name': error.name, - 'error.message': error.message - }); - }finally{ - console.log(`traceid: ${span.context().traceId}`); - span.end(); - } - }); + // span corresponds to dns lookup. Here, we have manually created + // the span, which is created to track work that happens outside of the + // dns lookup query. + const span = tracer.startSpan('dnsLookup'); + tracer.withSpan(span, async () => { + try { + await dns.lookup('montreal.ca'); + } catch (error) { + span.setAttributes({ + 'error.name': error.name, + 'error.message': error.message, + }); + } finally { + console.log(`traceid: ${span.context().traceId}`); + 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); + // 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); } makeLookup(); diff --git a/examples/dns/setup.js b/examples/dns/setup.js deleted file mode 100644 index f5ef407f2a..0000000000 --- a/examples/dns/setup.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const opentelemetry = require('@opentelemetry/core'); -const { NodeTracerRegistry } = 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 || ''; - -function setupTracerAndExporters(service) { - const registry = new NodeTracerRegistry({ -      plugins: { -          dns: { -            enabled: true, -            path: '@opentelemetry/plugin-dns', - // Avoid dns lookup loop with http zipkin calls - ignoreHostnames: ['localhost'] -        } -      } -  }); - - let exporter; - if (EXPORTER.toLowerCase().startsWith('z')) { - exporter = new ZipkinExporter({ - serviceName: service, - }); - } else { - exporter = new JaegerExporter({ - serviceName: service, - }); - } - - registry.addSpanProcessor(new SimpleSpanProcessor(exporter)); - - // Initialize the OpenTelemetry APIs to use the BasicTracerRegistry bindings - opentelemetry.initGlobalTracerRegistry(registry); -} - -exports.setupTracerAndExporters = setupTracerAndExporters; diff --git a/examples/dns/tracer.js b/examples/dns/tracer.js new file mode 100644 index 0000000000..7a918ec33d --- /dev/null +++ b/examples/dns/tracer.js @@ -0,0 +1,40 @@ +'use strict'; + +const opentelemetry = require('@opentelemetry/core'); +const { NodeTracerRegistry } = 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 registry = new NodeTracerRegistry({ + plugins: { + dns: { + enabled: true, + path: '@opentelemetry/plugin-dns', + // Avoid dns lookup loop with http zipkin calls + ignoreHostnames: ['localhost'], + }, + }, + }); + + let exporter; + if (EXPORTER.toLowerCase().startsWith('z')) { + exporter = new ZipkinExporter({ + serviceName, + }); + } else { + exporter = new JaegerExporter({ + serviceName, + }); + } + + registry.addSpanProcessor(new SimpleSpanProcessor(exporter)); + + // Initialize the OpenTelemetry APIs to use the BasicTracerRegistry bindings + opentelemetry.initGlobalTracerRegistry(registry); + + return opentelemetry.getTracer(); +}; diff --git a/examples/grpc/client.js b/examples/grpc/client.js index 4bc65bc976..5541113af7 100644 --- a/examples/grpc/client.js +++ b/examples/grpc/client.js @@ -1,20 +1,12 @@ '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 (gRPC in this case). - */ -config.setupTracerAndExporters('grpc-client-service'); - +const tracer = require('./tracer')('example-grpc-client'); +// eslint-disable-next-line import/order const grpc = require('grpc'); - const messages = require('./helloworld_pb'); const services = require('./helloworld_grpc_pb'); + const PORT = 50051; -const tracer = opentelemetry.getTracer('example-grpc-client'); /** A function which makes requests and handles response. */ function main() { @@ -26,17 +18,18 @@ function main() { console.log('Client traceId ', span.context().traceId); const client = new services.GreeterClient( `localhost:${PORT}`, - grpc.credentials.createInsecure() + grpc.credentials.createInsecure(), ); const request = new messages.HelloRequest(); let user; if (process.argv.length >= 3) { + // eslint-disable-next-line prefer-destructuring user = process.argv[2]; } else { user = 'world'; } request.setName(user); - client.sayHello(request, function(err, response) { + client.sayHello(request, (err, response) => { span.end(); if (err) throw err; console.log('Greeting:', response.getMessage()); @@ -46,7 +39,7 @@ function main() { // 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.') + console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.'); setTimeout(() => { console.log('Completed.'); }, 5000); } diff --git a/examples/grpc/helloworld_grpc_pb.js b/examples/grpc/helloworld_grpc_pb.js index e0eed2ea25..c32727f8da 100644 --- a/examples/grpc/helloworld_grpc_pb.js +++ b/examples/grpc/helloworld_grpc_pb.js @@ -1,3 +1,14 @@ +/* eslint-disable no-multi-assign */ +/* eslint-disable prefer-const */ +/* eslint-disable no-var */ +/* eslint-disable vars-on-top */ +/* eslint-disable no-unused-vars */ +/* eslint-disable func-names */ +/* eslint-disable camelcase */ +/* eslint-disable no-undef */ +/* eslint-disable no-new-func */ +/* eslint-disable strict */ + // GENERATED CODE -- DO NOT EDIT! // Original file comments: @@ -15,9 +26,11 @@ // See the License for the specific language governing permissions and // limitations under the License. // + 'use strict'; -var grpc = require('grpc'); -var helloworld_pb = require('./helloworld_pb.js'); + +const grpc = require('grpc'); +const helloworld_pb = require('./helloworld_pb.js'); function serialize_HelloReply(arg) { if (!(arg instanceof helloworld_pb.HelloReply)) { @@ -39,12 +52,12 @@ function serialize_HelloRequest(arg) { function deserialize_HelloRequest(buffer_arg) { return helloworld_pb.HelloRequest.deserializeBinary( - new Uint8Array(buffer_arg) + new Uint8Array(buffer_arg), ); } // The greeting service definition. -var GreeterService = (exports.GreeterService = { +const GreeterService = (exports.GreeterService = { // Sends a greeting sayHello: { path: '/helloworld.Greeter/SayHello', @@ -55,8 +68,8 @@ var GreeterService = (exports.GreeterService = { requestSerialize: serialize_HelloRequest, requestDeserialize: deserialize_HelloRequest, responseSerialize: serialize_HelloReply, - responseDeserialize: deserialize_HelloReply - } + responseDeserialize: deserialize_HelloReply, + }, }); exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService); diff --git a/examples/grpc/helloworld_pb.js b/examples/grpc/helloworld_pb.js index 1f69378fac..48656aef94 100644 --- a/examples/grpc/helloworld_pb.js +++ b/examples/grpc/helloworld_pb.js @@ -1,3 +1,13 @@ +/* eslint-disable prefer-const */ +/* eslint-disable no-var */ +/* eslint-disable vars-on-top */ +/* eslint-disable no-unused-vars */ +/* eslint-disable func-names */ +/* eslint-disable camelcase */ +/* eslint-disable no-undef */ +/* eslint-disable no-new-func */ +/* eslint-disable strict */ + /** * @fileoverview * @enhanceable @@ -5,9 +15,10 @@ */ // GENERATED CODE -- DO NOT EDIT! -var jspb = require('google-protobuf'); -var goog = jspb; -var global = Function('return this')(); +const jspb = require('google-protobuf'); + +const goog = jspb; +const global = Function('return this')(); goog.exportSymbol('proto.helloworld.HelloReply', null, global); goog.exportSymbol('proto.helloworld.HelloRequest', null, global); @@ -22,7 +33,7 @@ goog.exportSymbol('proto.helloworld.HelloRequest', null, global); * @extends {jspb.Message} * @constructor */ -proto.helloworld.HelloRequest = function(opt_data) { +proto.helloworld.HelloRequest = function (opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.helloworld.HelloRequest, jspb.Message); @@ -41,8 +52,8 @@ if (jspb.Message.GENERATE_TO_OBJECT) { * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ - proto.helloworld.HelloRequest.prototype.toObject = function( - opt_includeInstance + proto.helloworld.HelloRequest.prototype.toObject = function ( + opt_includeInstance, ) { return proto.helloworld.HelloRequest.toObject(opt_includeInstance, this); }; @@ -55,11 +66,13 @@ if (jspb.Message.GENERATE_TO_OBJECT) { * @param {!proto.helloworld.HelloRequest} msg The msg instance to transform. * @return {!Object} */ - proto.helloworld.HelloRequest.toObject = function(includeInstance, msg) { - var f, - obj = { - name: msg.getName() - }; + proto.helloworld.HelloRequest.toObject = function (includeInstance, msg) { + let f; + + + const obj = { + name: msg.getName(), + }; if (includeInstance) { obj.$jspbMessageInstance = msg; @@ -73,9 +86,9 @@ if (jspb.Message.GENERATE_TO_OBJECT) { * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.helloworld.HelloRequest} */ -proto.helloworld.HelloRequest.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.helloworld.HelloRequest(); +proto.helloworld.HelloRequest.deserializeBinary = function (bytes) { + const reader = new jspb.BinaryReader(bytes); + const msg = new proto.helloworld.HelloRequest(); return proto.helloworld.HelloRequest.deserializeBinaryFromReader(msg, reader); }; @@ -86,15 +99,15 @@ proto.helloworld.HelloRequest.deserializeBinary = function(bytes) { * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.helloworld.HelloRequest} */ -proto.helloworld.HelloRequest.deserializeBinaryFromReader = function( +proto.helloworld.HelloRequest.deserializeBinaryFromReader = function ( msg, - reader + reader, ) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } - var field = reader.getFieldNumber(); + const field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); @@ -114,9 +127,9 @@ proto.helloworld.HelloRequest.deserializeBinaryFromReader = function( * @param {!proto.helloworld.HelloRequest} message * @param {!jspb.BinaryWriter} writer */ -proto.helloworld.HelloRequest.serializeBinaryToWriter = function( +proto.helloworld.HelloRequest.serializeBinaryToWriter = function ( message, - writer + writer, ) { message.serializeBinaryToWriter(writer); }; @@ -125,8 +138,8 @@ proto.helloworld.HelloRequest.serializeBinaryToWriter = function( * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ -proto.helloworld.HelloRequest.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); +proto.helloworld.HelloRequest.prototype.serializeBinary = function () { + const writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; @@ -136,10 +149,10 @@ proto.helloworld.HelloRequest.prototype.serializeBinary = function() { * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ -proto.helloworld.HelloRequest.prototype.serializeBinaryToWriter = function( - writer +proto.helloworld.HelloRequest.prototype.serializeBinaryToWriter = function ( + writer, ) { - var f = undefined; + let f; f = this.getName(); if (f.length > 0) { writer.writeString(1, f); @@ -150,9 +163,9 @@ proto.helloworld.HelloRequest.prototype.serializeBinaryToWriter = function( * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.helloworld.HelloRequest} The clone. */ -proto.helloworld.HelloRequest.prototype.cloneMessage = function() { +proto.helloworld.HelloRequest.prototype.cloneMessage = function () { return /** @type {!proto.helloworld.HelloRequest} */ (jspb.Message.cloneMessage( - this + this, )); }; @@ -160,12 +173,12 @@ proto.helloworld.HelloRequest.prototype.cloneMessage = function() { * optional string name = 1; * @return {string} */ -proto.helloworld.HelloRequest.prototype.getName = function() { +proto.helloworld.HelloRequest.prototype.getName = function () { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 1, '')); }; /** @param {string} value */ -proto.helloworld.HelloRequest.prototype.setName = function(value) { +proto.helloworld.HelloRequest.prototype.setName = function (value) { jspb.Message.setField(this, 1, value); }; @@ -179,7 +192,7 @@ proto.helloworld.HelloRequest.prototype.setName = function(value) { * @extends {jspb.Message} * @constructor */ -proto.helloworld.HelloReply = function(opt_data) { +proto.helloworld.HelloReply = function (opt_data) { jspb.Message.initialize(this, opt_data, 0, -1, null, null); }; goog.inherits(proto.helloworld.HelloReply, jspb.Message); @@ -198,8 +211,8 @@ if (jspb.Message.GENERATE_TO_OBJECT) { * for transitional soy proto support: http://goto/soy-param-migration * @return {!Object} */ - proto.helloworld.HelloReply.prototype.toObject = function( - opt_includeInstance + proto.helloworld.HelloReply.prototype.toObject = function ( + opt_includeInstance, ) { return proto.helloworld.HelloReply.toObject(opt_includeInstance, this); }; @@ -212,11 +225,13 @@ if (jspb.Message.GENERATE_TO_OBJECT) { * @param {!proto.helloworld.HelloReply} msg The msg instance to transform. * @return {!Object} */ - proto.helloworld.HelloReply.toObject = function(includeInstance, msg) { - var f, - obj = { - message: msg.getMessage() - }; + proto.helloworld.HelloReply.toObject = function (includeInstance, msg) { + let f; + + + const obj = { + message: msg.getMessage(), + }; if (includeInstance) { obj.$jspbMessageInstance = msg; @@ -230,9 +245,9 @@ if (jspb.Message.GENERATE_TO_OBJECT) { * @param {jspb.ByteSource} bytes The bytes to deserialize. * @return {!proto.helloworld.HelloReply} */ -proto.helloworld.HelloReply.deserializeBinary = function(bytes) { - var reader = new jspb.BinaryReader(bytes); - var msg = new proto.helloworld.HelloReply(); +proto.helloworld.HelloReply.deserializeBinary = function (bytes) { + const reader = new jspb.BinaryReader(bytes); + const msg = new proto.helloworld.HelloReply(); return proto.helloworld.HelloReply.deserializeBinaryFromReader(msg, reader); }; @@ -243,15 +258,15 @@ proto.helloworld.HelloReply.deserializeBinary = function(bytes) { * @param {!jspb.BinaryReader} reader The BinaryReader to use. * @return {!proto.helloworld.HelloReply} */ -proto.helloworld.HelloReply.deserializeBinaryFromReader = function( +proto.helloworld.HelloReply.deserializeBinaryFromReader = function ( msg, - reader + reader, ) { while (reader.nextField()) { if (reader.isEndGroup()) { break; } - var field = reader.getFieldNumber(); + const field = reader.getFieldNumber(); switch (field) { case 1: var value = /** @type {string} */ (reader.readString()); @@ -271,9 +286,9 @@ proto.helloworld.HelloReply.deserializeBinaryFromReader = function( * @param {!proto.helloworld.HelloReply} message * @param {!jspb.BinaryWriter} writer */ -proto.helloworld.HelloReply.serializeBinaryToWriter = function( +proto.helloworld.HelloReply.serializeBinaryToWriter = function ( message, - writer + writer, ) { message.serializeBinaryToWriter(writer); }; @@ -282,8 +297,8 @@ proto.helloworld.HelloReply.serializeBinaryToWriter = function( * Serializes the message to binary data (in protobuf wire format). * @return {!Uint8Array} */ -proto.helloworld.HelloReply.prototype.serializeBinary = function() { - var writer = new jspb.BinaryWriter(); +proto.helloworld.HelloReply.prototype.serializeBinary = function () { + const writer = new jspb.BinaryWriter(); this.serializeBinaryToWriter(writer); return writer.getResultBuffer(); }; @@ -293,10 +308,10 @@ proto.helloworld.HelloReply.prototype.serializeBinary = function() { * writing to the given BinaryWriter. * @param {!jspb.BinaryWriter} writer */ -proto.helloworld.HelloReply.prototype.serializeBinaryToWriter = function( - writer +proto.helloworld.HelloReply.prototype.serializeBinaryToWriter = function ( + writer, ) { - var f = undefined; + let f; f = this.getMessage(); if (f.length > 0) { writer.writeString(1, f); @@ -307,9 +322,9 @@ proto.helloworld.HelloReply.prototype.serializeBinaryToWriter = function( * Creates a deep clone of this proto. No data is shared with the original. * @return {!proto.helloworld.HelloReply} The clone. */ -proto.helloworld.HelloReply.prototype.cloneMessage = function() { +proto.helloworld.HelloReply.prototype.cloneMessage = function () { return /** @type {!proto.helloworld.HelloReply} */ (jspb.Message.cloneMessage( - this + this, )); }; @@ -317,12 +332,12 @@ proto.helloworld.HelloReply.prototype.cloneMessage = function() { * optional string message = 1; * @return {string} */ -proto.helloworld.HelloReply.prototype.getMessage = function() { +proto.helloworld.HelloReply.prototype.getMessage = function () { return /** @type {string} */ (jspb.Message.getFieldProto3(this, 1, '')); }; /** @param {string} value */ -proto.helloworld.HelloReply.prototype.setMessage = function(value) { +proto.helloworld.HelloReply.prototype.setMessage = function (value) { jspb.Message.setField(this, 1, value); }; diff --git a/examples/grpc/server.js b/examples/grpc/server.js index 2a411ba40b..1b9d533172 100644 --- a/examples/grpc/server.js +++ b/examples/grpc/server.js @@ -1,26 +1,19 @@ 'use strict'; -const opentelemetry = require('@opentelemetry/core'); - -/** - * The trace instance needs to be initialized first, if you want to enable - * automatic tracing for built-in plugins (gRPC in this case). - */ -const config = require('./setup'); -config.setupTracerAndExporters('grpc-server-service'); - +const tracer = require('./tracer')(('example-grpc-server')); +// eslint-disable-next-line import/order const grpc = require('grpc'); -const tracer = opentelemetry.getTracer('example-grpc-server'); const messages = require('./helloworld_pb'); const services = require('./helloworld_grpc_pb'); + const PORT = 50051; /** Starts a gRPC server that receives requests on sample server port. */ function startServer() { // Creates a server const server = new grpc.Server(); - server.addService(services.GreeterService, { sayHello: sayHello }); + server.addService(services.GreeterService, { sayHello }); server.bind(`0.0.0.0:${PORT}`, grpc.ServerCredentials.createInsecure()); console.log(`binding server on 0.0.0.0:${PORT}`); server.start(); @@ -33,11 +26,11 @@ function sayHello(call, callback) { const span = tracer.startSpan('server.js:sayHello()', { parent: currentSpan, kind: 1, // server - attributes: { key: 'value' } + attributes: { key: 'value' }, }); span.addEvent(`invoking sayHello() to ${call.request.getName()}`); const reply = new messages.HelloReply(); - reply.setMessage('Hello ' + call.request.getName()); + reply.setMessage(`Hello ${call.request.getName()}`); callback(null, reply); span.end(); } diff --git a/examples/grpc/setup.js b/examples/grpc/tracer.js similarity index 72% rename from examples/grpc/setup.js rename to examples/grpc/tracer.js index 7a7fc3eafe..ad881334c9 100644 --- a/examples/grpc/setup.js +++ b/examples/grpc/tracer.js @@ -5,27 +5,27 @@ const { NodeTracerRegistry } = 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 || ''; -function setupTracerAndExporters(service) { +module.exports = (serviceName) => { const registry = new NodeTracerRegistry({ plugins: { grpc: { enabled: true, - // if it can't find the module, put the absolute path since the packages are not published yet - path: '@opentelemetry/plugin-grpc' - } - } + path: '@opentelemetry/plugin-grpc', + }, + }, }); let exporter; if (EXPORTER.toLowerCase().startsWith('z')) { exporter = new ZipkinExporter({ - serviceName: service, + serviceName, }); } else { exporter = new JaegerExporter({ - serviceName: service, + serviceName, }); } @@ -33,6 +33,6 @@ function setupTracerAndExporters(service) { // Initialize the OpenTelemetry APIs to use the BasicTracerRegistry bindings opentelemetry.initGlobalTracerRegistry(registry); -} -exports.setupTracerAndExporters = setupTracerAndExporters; + return opentelemetry.getTracer(); +}; diff --git a/examples/grpc_dynamic_codegen/capitalize_client.js b/examples/grpc_dynamic_codegen/capitalize_client.js index a994307854..0791686567 100644 --- a/examples/grpc_dynamic_codegen/capitalize_client.js +++ b/examples/grpc_dynamic_codegen/capitalize_client.js @@ -1,22 +1,15 @@ '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 (gRPC in this case). - */ -config.setupTracerAndExporters('grpc-client-service'); - +// eslint-disable-next-line import/order +const tracer = require('./tracer')('example-grpc-capitalize-client'); const path = require('path'); const grpc = require('grpc'); const protoLoader = require('@grpc/proto-loader'); -const tracer = opentelemetry.getTracer('example-grpc-capitalize-client'); - const PROTO_PATH = path.join(__dirname, 'protos/defs.proto'); -const PROTO_OPTIONS = { keepCase: true, enums: String, defaults: true, oneofs: true }; +const PROTO_OPTIONS = { + keepCase: true, enums: String, defaults: true, oneofs: true, +}; const definition = protoLoader.loadSync(PROTO_PATH, PROTO_OPTIONS); const rpcProto = grpc.loadPackageDefinition(definition).rpc; @@ -28,7 +21,7 @@ function main() { const span = tracer.startSpan('tutorialsClient.capitalize'); tracer.withSpan(span, () => { - client.capitalize({ data: Buffer.from(data) }, function (err, response) { + client.capitalize({ data: Buffer.from(data) }, (err, response) => { if (err) { console.log('could not get grpc response'); return; @@ -43,7 +36,7 @@ function main() { // 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.') + console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.'); setTimeout(() => { console.log('Completed.'); }, 5000); } diff --git a/examples/grpc_dynamic_codegen/capitalize_server.js b/examples/grpc_dynamic_codegen/capitalize_server.js index 79dcd3c0fe..3755e4ea56 100644 --- a/examples/grpc_dynamic_codegen/capitalize_server.js +++ b/examples/grpc_dynamic_codegen/capitalize_server.js @@ -1,26 +1,19 @@ 'use strict'; +// eslint-disable-next-line import/order +const tracer = require('./tracer')('example-grpc-capitalize-server'); const { SpanKind } = require('@opentelemetry/types'); -const opentelemetry = require('@opentelemetry/core'); - -/** - * The trace instance needs to be initialized first, if you want to enable - * automatic tracing for built-in plugins (gRPC in this case). - */ -const config = require('./setup'); -config.setupTracerAndExporters('grpc-server-service'); - const path = require('path'); const grpc = require('grpc'); const protoLoader = require('@grpc/proto-loader'); const PROTO_PATH = path.join(__dirname, 'protos/defs.proto'); -const PROTO_OPTIONS = { keepCase: true, enums: String, defaults: true, oneofs: true }; +const PROTO_OPTIONS = { + keepCase: true, enums: String, defaults: true, oneofs: true, +}; const definition = protoLoader.loadSync(PROTO_PATH, PROTO_OPTIONS); const rpcProto = grpc.loadPackageDefinition(definition).rpc; -const tracer = opentelemetry.getTracer('example-grpc-capitalize-server'); - /** Implements the Capitalize RPC method. */ function capitalize(call, callback) { const currentSpan = tracer.getCurrentSpan(); @@ -34,7 +27,9 @@ function capitalize(call, callback) { const data = call.request.data.toString('utf8'); const capitalized = data.toUpperCase(); - for (let i = 0; i < 100000000; i++) {} + for (let i = 0; i < 100000000; i += 1) { + // empty + } span.end(); callback(null, { data: Buffer.from(capitalized) }); } @@ -45,7 +40,7 @@ function capitalize(call, callback) { */ function main() { const server = new grpc.Server(); - server.addService(rpcProto.Fetch.service, { capitalize: capitalize }); + server.addService(rpcProto.Fetch.service, { capitalize }); server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure()); server.start(); } diff --git a/examples/grpc_dynamic_codegen/setup.js b/examples/grpc_dynamic_codegen/tracer.js similarity index 82% rename from examples/grpc_dynamic_codegen/setup.js rename to examples/grpc_dynamic_codegen/tracer.js index 4fd8b0a8b6..23d6e25f01 100644 --- a/examples/grpc_dynamic_codegen/setup.js +++ b/examples/grpc_dynamic_codegen/tracer.js @@ -5,27 +5,28 @@ const { NodeTracerRegistry } = 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 || ''; -function setupTracerAndExporters(service) { +module.exports = (serviceName) => { const registry = new NodeTracerRegistry({ plugins: { grpc: { enabled: true, // You may use a package name or absolute path to the file. - path: '@opentelemetry/plugin-grpc' - } - } + path: '@opentelemetry/plugin-grpc', + }, + }, }); let exporter; if (EXPORTER.toLowerCase().startsWith('z')) { exporter = new ZipkinExporter({ - serviceName: service, + serviceName, }); } else { exporter = new JaegerExporter({ - serviceName: service, + serviceName, }); } @@ -35,6 +36,6 @@ function setupTracerAndExporters(service) { // Initialize the OpenTelemetry APIs to use the BasicTracerRegistry bindings opentelemetry.initGlobalTracerRegistry(registry); -} -exports.setupTracerAndExporters = setupTracerAndExporters; + return opentelemetry.getTracer(); +}; diff --git a/examples/http/client.js b/examples/http/client.js index 8b299b98ff..5a88497f66 100644 --- a/examples/http/client.js +++ b/examples/http/client.js @@ -1,43 +1,35 @@ '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 in this case). - */ -config.setupTracerAndExporters('http-client-service'); - +const tracer = require('./tracer')('example-http-client'); +// eslint-disable-next-line import/order const http = require('http'); -const tracer = opentelemetry.getTracer('example-http-client'); /** 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'); - tracer.withSpan(span, () => { - http.get({ - host: 'localhost', - port: 8080, - path: '/helloworld' - }, (response) => { - let body = []; - response.on('data', chunk => body.push(chunk)); - response.on('end', () => { - console.log(body.toString()); - span.end(); - }); - }); - }) + // 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'); + tracer.withSpan(span, () => { + http.get({ + host: 'localhost', + port: 8080, + path: '/helloworld', + }, (response) => { + const body = []; + response.on('data', (chunk) => body.push(chunk)); + response.on('end', () => { + console.log(body.toString()); + 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); + // 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/http/server.js b/examples/http/server.js index d3c0046bf9..d142badf83 100644 --- a/examples/http/server.js +++ b/examples/http/server.js @@ -1,22 +1,15 @@ '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 in this case). - */ -config.setupTracerAndExporters('http-server-service'); - +const tracer = require('./tracer')('example-http-server'); +// eslint-disable-next-line import/order const http = require('http'); -const tracer = opentelemetry.getTracer('example-http-server'); /** Starts a HTTP server that receives requests on sample server port. */ -function startServer (port) { +function startServer(port) { // Creates a server const server = http.createServer(handleRequest); // Starts the server - server.listen(port, err => { + server.listen(port, (err) => { if (err) { throw err; } @@ -25,21 +18,21 @@ function startServer (port) { } /** A function which handles requests and send response. */ -function handleRequest (request, response) { +function handleRequest(request, response) { const currentSpan = tracer.getCurrentSpan(); // display traceid in the terminal console.log(`traceid: ${currentSpan.context().traceId}`); const span = tracer.startSpan('handleRequest', { parent: currentSpan, kind: 1, // server - attributes: { key:'value' } + attributes: { key: 'value' }, }); // Annotate our span to capture metadata about the operation span.addEvent('invoking handleRequest'); try { - let body = []; - request.on('error', err => console.log(err)); - request.on('data', chunk => body.push(chunk)); + const body = []; + request.on('error', (err) => console.log(err)); + request.on('data', (chunk) => body.push(chunk)); request.on('end', () => { // deliberately sleeping to mock some action. setTimeout(() => { @@ -48,7 +41,7 @@ function handleRequest (request, response) { }, 2000); }); } catch (err) { - console.log(err); + console.error(err); span.end(); } } diff --git a/examples/redis/setup.js b/examples/http/tracer.js similarity index 83% rename from examples/redis/setup.js rename to examples/http/tracer.js index 770cdd5dfd..29a21f4f0d 100644 --- a/examples/redis/setup.js +++ b/examples/http/tracer.js @@ -5,19 +5,20 @@ const { NodeTracerRegistry } = 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 || ''; -function setupTracerAndExporters(service) { +module.exports = (serviceName) => { const registry = new NodeTracerRegistry(); let exporter; if (EXPORTER.toLowerCase().startsWith('z')) { exporter = new ZipkinExporter({ - serviceName: service, + serviceName, }); } else { exporter = new JaegerExporter({ - serviceName: service, + serviceName, }); } @@ -25,6 +26,6 @@ function setupTracerAndExporters(service) { // Initialize the OpenTelemetry APIs to use the BasicTracerRegistry bindings opentelemetry.initGlobalTracerRegistry(registry); -} -exports.setupTracerAndExporters = setupTracerAndExporters; + return opentelemetry.getTracer(); +}; diff --git a/examples/https/client.js b/examples/https/client.js index 40ebc94d3f..e5b1825163 100644 --- a/examples/https/client.js +++ b/examples/https/client.js @@ -1,42 +1,35 @@ '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 (HTTPs in this case). - */ -config.setupTracerAndExporters('https-client-service'); - +const tracer = require('./tracer')('example-https-client'); +// eslint-disable-next-line import/order const https = require('https'); -const tracer = opentelemetry.getTracer('example-https-client'); /** 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'); - tracer.withSpan(span, () => { - https.get({ - host: 'localhost', - port: 443, - path: '/helloworld' - }, (response) => { - let body = []; - response.on('data', chunk => body.push(chunk)); - response.on('end', () => { - console.log(body.toString()); - span.end(); - }); - }); + // 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'); + tracer.withSpan(span, () => { + https.get({ + host: 'localhost', + port: 443, + path: '/helloworld', + }, (response) => { + const body = []; + response.on('data', (chunk) => body.push(chunk)); + response.on('end', () => { + console.log(body.toString()); + 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); + // 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/https/server.js b/examples/https/server.js index 7280c8f61f..105005fea8 100644 --- a/examples/https/server.js +++ b/examples/https/server.js @@ -1,27 +1,20 @@ 'use strict'; +// eslint-disable-next-line import/order +const tracer = require('./tracer')('example-https-server'); const fs = require('fs'); -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 (HTTPs in this case). - */ -config.setupTracerAndExporters('https-server-service'); - const https = require('https'); -const tracer = opentelemetry.getTracer('example-https-server'); /** Starts a HTTPs server that receives requests on sample server port. */ -function startServer (port) { +function startServer(port) { const options = { key: fs.readFileSync('./server-key.pem'), - cert: fs.readFileSync('./server-cert.pem') + cert: fs.readFileSync('./server-cert.pem'), }; // Creates a server const server = https.createServer(options, handleRequest); // Starts the server - server.listen(port, err => { + server.listen(port, (err) => { if (err) { throw err; } @@ -30,21 +23,21 @@ function startServer (port) { } /** A function which handles requests and send response. */ -function handleRequest (request, response) { +function handleRequest(request, response) { const currentSpan = tracer.getCurrentSpan(); // display traceid in the terminal console.log(`traceid: ${currentSpan.context().traceId}`); const span = tracer.startSpan('handleRequest', { parent: currentSpan, kind: 1, // server - attributes: { key:'value' } + attributes: { key: 'value' }, }); // Annotate our span to capture metadata about the operation span.addEvent('invoking handleRequest'); try { - let body = []; - request.on('error', err => console.log(err)); - request.on('data', chunk => body.push(chunk)); + const body = []; + request.on('error', (err) => console.log(err)); + request.on('data', (chunk) => body.push(chunk)); request.on('end', () => { // deliberately sleeping to mock some action. setTimeout(() => { diff --git a/examples/https/setup.js b/examples/https/tracer.js similarity index 84% rename from examples/https/setup.js rename to examples/https/tracer.js index ef426a90b5..eaec28f376 100644 --- a/examples/https/setup.js +++ b/examples/https/tracer.js @@ -5,19 +5,21 @@ const { NodeTracerRegistry } = 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 || ''; process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; -function setupTracerAndExporters(service) { + +module.exports = (serviceName) => { let exporter; const registry = new NodeTracerRegistry(); if (EXPORTER.toLowerCase().startsWith('z')) { exporter = new ZipkinExporter({ - serviceName: service + serviceName, }); } else { exporter = new JaegerExporter({ - serviceName: service, + serviceName, }); } @@ -25,6 +27,6 @@ function setupTracerAndExporters(service) { // Initialize the OpenTelemetry APIs to use the BasicTracerRegistry bindings opentelemetry.initGlobalTracerRegistry(registry); -} -exports.setupTracerAndExporters = setupTracerAndExporters; + return opentelemetry.getTracer(); +}; diff --git a/examples/mysql/client.js b/examples/mysql/client.js index e080ab994a..6e8bc0c51a 100644 --- a/examples/mysql/client.js +++ b/examples/mysql/client.js @@ -1,81 +1,73 @@ '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 tracer = require('./tracer')('example-mysql-http-client'); +// eslint-disable-next-line import/order const http = require('http'); -const tracer = opentelemetry.getTracer('example-mysql-http-client'); /** 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'); + // 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; + 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: '/connection/query', + }, (response) => { + const 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: '/pool/query', + }, (response) => { + const 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(); - }); - }); + }); + tracer.withSpan(span, () => { + queries += 1; + http.get({ + host: 'localhost', + port: 8080, + path: '/cluster/query', + }, (response) => { + const 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); + // 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/server.js b/examples/mysql/server.js index 1ba4eb7258..748ef339d1 100644 --- a/examples/mysql/server.js +++ b/examples/mysql/server.js @@ -1,47 +1,39 @@ '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'); - +// eslint-disable-next-line import/order +const tracer = require('./tracer')('example-mysql-http-server'); const mysql = require('mysql'); const http = require('http'); -const tracer = opentelemetry.getTracer('example-mysql-http-server'); - const pool = mysql.createPool({ - host : 'localhost', - user : 'root', - password : 'secret', - database : 'my_db', + host: 'localhost', + user: 'root', + password: 'secret', + database: 'my_db', }); const connection = mysql.createConnection({ - host : 'localhost', - user : 'root', - password : 'secret', - database : 'my_db', + host: 'localhost', + user: 'root', + password: 'secret', + database: 'my_db', }); const cluster = mysql.createPoolCluster(); cluster.add({ - host : 'localhost', - user : 'root', - password : 'secret', - database : 'my_db', -}) + host: 'localhost', + user: 'root', + password: 'secret', + database: 'my_db', +}); /** Starts a HTTP server that receives requests on sample server port. */ -function startServer (port) { +function startServer(port) { // Creates a server const server = http.createServer(handleRequest); // Starts the server - server.listen(port, err => { + server.listen(port, (err) => { if (err) { throw err; } @@ -50,23 +42,23 @@ function startServer (port) { } /** A function which handles requests and send response. */ -function handleRequest (request, response) { +function handleRequest(request, response) { const currentSpan = tracer.getCurrentSpan(); // display traceid in the terminal - const {traceId} = currentSpan.context(); + 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}`) + 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)); + const body = []; + request.on('error', (err) => console.log(err)); + request.on('data', (chunk) => body.push(chunk)); request.on('end', () => { - if (request.url === "/connection/query") { + if (request.url === '/connection/query') { handleConnectionQuery(response); - } else if (request.url === "/pool/query") { + } else if (request.url === '/pool/query') { handlePoolQuery(response); - } else if (request.url === "/cluster/query") { + } else if (request.url === '/cluster/query') { handleClusterQuery(response); } else { handleNotFound(response); @@ -80,51 +72,47 @@ function handleRequest (request, response) { 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"); + const query = 'SELECT 1 + 1 as pool_solution'; + pool.getConnection((connErr, conn, _fields) => { + conn.query(query, (err, results) => { + tracer.getCurrentSpan().addEvent('results'); if (err) { - console.log("Error code:", err.code); + console.log('Error code:', err.code); response.end(err.message); - } - else { + } else { response.end(`${query}: ${results[0].pool_solution}`); } }); - }) + }); } function handleConnectionQuery(response) { - const query = "SELECT 1 + 1 as solution"; - connection.query(query, (err, results, fields) => { + const query = 'SELECT 1 + 1 as solution'; + connection.query(query, (err, results, _fields) => { if (err) { - console.log("Error code:", err.code); + console.log('Error code:', err.code); response.end(err.message); - } - else { + } 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"); + const query = 'SELECT 1 + 1 as cluster_solution'; + cluster.getConnection((connErr, conn) => { + conn.query(query, (err, results, _fields) => { + tracer.getCurrentSpan().addEvent('results'); if (err) { - console.log("Error code:", err.code); + console.log('Error code:', err.code); response.end(err.message); - } - else { + } else { response.end(`${query}: ${results[0].cluster_solution}`); } }); - }) + }); } function handleNotFound(response) { - response.end("not found"); + response.end('not found'); } - diff --git a/examples/mysql/setup.js b/examples/mysql/tracer.js similarity index 75% rename from examples/mysql/setup.js rename to examples/mysql/tracer.js index e3f9ce3f41..e3e93e4d79 100644 --- a/examples/mysql/setup.js +++ b/examples/mysql/tracer.js @@ -6,29 +6,29 @@ const { SimpleSpanProcessor } = require('@opentelemetry/tracing'); const { JaegerExporter } = require('@opentelemetry/exporter-jaeger'); const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin'); -function setupTracerAndExporters(service) { +module.exports = (serviceName) => { const registry = new NodeTracerRegistry({ plugins: { mysql: { enabled: true, - path: "@opentelemetry/plugin-mysql" + path: '@opentelemetry/plugin-mysql', }, http: { enabled: true, - path: "@opentelemetry/plugin-http" - } - } + path: '@opentelemetry/plugin-http', + }, + }, }); registry.addSpanProcessor(new SimpleSpanProcessor(new ZipkinExporter({ - serviceName: service, + serviceName, }))); registry.addSpanProcessor(new SimpleSpanProcessor(new JaegerExporter({ - serviceName: service, + serviceName, }))); // Initialize the OpenTelemetry APIs to use the BasicTracerRegistry bindings opentelemetry.initGlobalTracerRegistry(registry); -} -exports.setupTracerAndExporters = setupTracerAndExporters; + return opentelemetry.getTracer(); +}; diff --git a/examples/opentracing-shim/client.js b/examples/opentracing-shim/client.js index 916b1c65f0..451467e3ef 100644 --- a/examples/opentracing-shim/client.js +++ b/examples/opentracing-shim/client.js @@ -1,8 +1,8 @@ -"use strict"; +'use strict'; -const http = require("http"); -const opentracing = require("opentracing"); -const shim = require("./shim").shim("http_client_service"); +const http = require('http'); +const opentracing = require('opentracing'); +const shim = require('./shim').shim('http_client_service'); opentracing.initGlobalTracer(shim); const tracer = opentracing.globalTracer(); @@ -10,7 +10,7 @@ const tracer = opentracing.globalTracer(); makeRequest(); async function makeRequest() { - const span = tracer.startSpan("make_request"); + const span = tracer.startSpan('make_request'); const headers = {}; tracer.inject(span, opentracing.FORMAT_HTTP_HEADERS, headers); @@ -18,28 +18,28 @@ async function makeRequest() { http .get( { - host: "localhost", + host: 'localhost', port: 3000, - path: "/", - headers + path: '/', + headers, }, - resp => { - let data = ""; + (resp) => { + let data = ''; - resp.on("data", chunk => { + resp.on('data', (chunk) => { data += chunk; }); - resp.on("end", async () => { + resp.on('end', async () => { console.log(JSON.parse(data)); span.finish(); - console.log("Sleeping 5 seconds before shutdown to ensure all records are flushed."); - setTimeout(() => { console.log("Completed."); }, 5000); + console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.'); + setTimeout(() => { console.log('Completed.'); }, 5000); }); - } + }, ) - .on("error", err => { - console.log("Error: " + err.message); + .on('error', (err) => { + console.log(`Error: ${err.message}`); }); } diff --git a/examples/opentracing-shim/package.json b/examples/opentracing-shim/package.json index 3762aca0c7..46d065f9fe 100644 --- a/examples/opentracing-shim/package.json +++ b/examples/opentracing-shim/package.json @@ -33,6 +33,7 @@ "@opentelemetry/exporter-zipkin": "^0.3.3", "@opentelemetry/node": "^0.3.3", "@opentelemetry/shim-opentracing": "^0.3.3", + "@opentelemetry/tracing": "^0.3.3", "opentracing": "^0.14.4" }, "homepage": "https://github.com/open-telemetry/opentelemetry-js#readme", diff --git a/examples/opentracing-shim/server.js b/examples/opentracing-shim/server.js index f10ffdfc5d..66c0803ccd 100644 --- a/examples/opentracing-shim/server.js +++ b/examples/opentracing-shim/server.js @@ -1,9 +1,9 @@ -"use strict"; +'use strict'; -const http = require("http"); -const opentracing = require("opentracing"); -const utils = require("./utils"); -const shim = require("./shim").shim("http_server_service"); +const http = require('http'); +const opentracing = require('opentracing'); +const utils = require('./utils'); +const shim = require('./shim').shim('http_server_service'); opentracing.initGlobalTracer(shim); const tracer = opentracing.globalTracer(); @@ -13,7 +13,7 @@ startServer(3000); function startServer(port) { const server = http.createServer(handleRequest); - server.listen(port, err => { + server.listen(port, (err) => { if (err) throw err; console.log(`Server is listening on ${port}`); @@ -23,21 +23,21 @@ function startServer(port) { async function handleRequest(req, res) { const parentSpan = tracer.extract( opentracing.FORMAT_HTTP_HEADERS, - req.headers + req.headers, ); - const span = tracer.startSpan("handle_request", { - childOf: parentSpan + const span = tracer.startSpan('handle_request', { + childOf: parentSpan, }); - span.setTag("custom", "tag value"); - span.setTag("alpha", "1000"); + span.setTag('custom', 'tag value'); + span.setTag('alpha', '1000'); await doSomething(span); - res.writeHead(200, { "Content-Type": "application/json" }); + res.writeHead(200, { 'Content-Type': 'application/json' }); res.write( - JSON.stringify({ status: "OK", traceId: span.context().toTraceId() }) + JSON.stringify({ status: 'OK', traceId: span.context().toTraceId() }), ); res.end(); @@ -45,11 +45,11 @@ async function handleRequest(req, res) { } async function doSomething(parentSpan) { - const span = tracer.startSpan("do_something", { childOf: parentSpan }); + const span = tracer.startSpan('do_something', { childOf: parentSpan }); - span.setTag("alpha", "200"); - span.setTag("beta", "50"); - span.log({ state: "waiting" }); + span.setTag('alpha', '200'); + span.setTag('beta', '50'); + span.log({ state: 'waiting' }); // deliberately sleeping to mock some action. await utils.sleep(1000); diff --git a/examples/opentracing-shim/shim.js b/examples/opentracing-shim/shim.js index 8efb1c2a8b..4730f9e258 100644 --- a/examples/opentracing-shim/shim.js +++ b/examples/opentracing-shim/shim.js @@ -1,23 +1,23 @@ -"use strict"; +'use strict'; -const { NodeTracerRegistry } = require("@opentelemetry/node"); -const { SimpleSpanProcessor } = require("@opentelemetry/tracing"); -const { JaegerExporter } = require("@opentelemetry/exporter-jaeger"); -const { ZipkinExporter } = require("@opentelemetry/exporter-zipkin"); -const { TracerShim } = require("@opentelemetry/shim-opentracing"); +const { NodeTracerRegistry } = require('@opentelemetry/node'); +const { SimpleSpanProcessor } = require('@opentelemetry/tracing'); +const { JaegerExporter } = require('@opentelemetry/exporter-jaeger'); +const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin'); +const { TracerShim } = require('@opentelemetry/shim-opentracing'); function shim(serviceName) { const registry = new NodeTracerRegistry(); registry.addSpanProcessor(new SimpleSpanProcessor(getExporter(serviceName))); - return new TracerShim(registry.getTracer("opentracing-shim")); + return new TracerShim(registry.getTracer('opentracing-shim')); } function getExporter(serviceName) { - const type = process.env.EXPORTER.toLowerCase() || "jaeger"; + const type = process.env.EXPORTER.toLowerCase() || 'jaeger'; - if (type.startsWith("z")) { + if (type.startsWith('z')) { return new ZipkinExporter({ serviceName }); } diff --git a/examples/opentracing-shim/utils.js b/examples/opentracing-shim/utils.js index 813dc35dcd..a913e95acd 100644 --- a/examples/opentracing-shim/utils.js +++ b/examples/opentracing-shim/utils.js @@ -1,7 +1,7 @@ -"use strict"; +'use strict'; async function sleep(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); + return new Promise((resolve) => setTimeout(resolve, ms)); } exports.sleep = sleep; diff --git a/examples/postgres/client.js b/examples/postgres/client.js index 1c31f5c1d3..1df7bdf9f6 100644 --- a/examples/postgres/client.js +++ b/examples/postgres/client.js @@ -1,35 +1,32 @@ 'use strict'; -// set up ot -const opentelemetry = require('@opentelemetry/core'); -const config = require('./setup'); -config.setupTracerAndExporters('postgres-client-service'); +const tracer = require('./tracer')('postgres-client-service'); +// eslint-disable-next-line import/order const http = require('http'); -const tracer = opentelemetry.getTracer(); function makeRequest() { - const span = tracer.startSpan('makeRequest'); - const randomId = Math.floor(Math.random() * 10); - tracer.withSpan(span, () => { - console.log('Client traceId ', span.context().traceId); - http.get({ - host: 'localhost', - port: 3000, - path: `/insert?id=${randomId}&text=randomstring` - }); + const span = tracer.startSpan('makeRequest'); + const randomId = Math.floor(Math.random() * 10); + tracer.withSpan(span, () => { + console.log('Client traceId ', span.context().traceId); + http.get({ + host: 'localhost', + port: 3000, + path: `/insert?id=${randomId}&text=randomstring`, + }); - http.get({ - host: 'localhost', - port: 3000, - path: `/get?id=${randomId}` - }); + http.get({ + host: 'localhost', + port: 3000, + path: `/get?id=${randomId}`, }); + }); - // 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); + // 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/postgres/server.js b/examples/postgres/server.js index 9f67ed4a56..8486add4a3 100644 --- a/examples/postgres/server.js +++ b/examples/postgres/server.js @@ -1,18 +1,13 @@ 'use strict'; -// set up ot -const opentelemetry = require('@opentelemetry/core'); +// eslint-disable-next-line import/order +const tracer = require('./tracer')('postgres-server-service'); const { SpanKind, CanonicalCode } = require('@opentelemetry/types'); -const config = require('./setup'); -config.setupTracerAndExporters('postgres-server-service'); -const tracer = opentelemetry.getTracer(); +const express = require('express'); +const setupPg = require('./setupPsql'); -// set up pg -const setupPg = require('./setupPsql'); const pool = setupPg.startPsql(); -// set up express -const express = require('express'); const app = express(); app.get('/:cmd', (req, res) => { @@ -28,7 +23,7 @@ app.get('/:cmd', (req, res) => { return; } queryText = { - text: `INSERT INTO test (id, text) VALUES($1, $2) ON CONFLICT(id) DO UPDATE SET text=$2`, + text: 'INSERT INTO test (id, text) VALUES($1, $2) ON CONFLICT(id) DO UPDATE SET text=$2', values: [req.query.id, req.query.text], }; } @@ -45,7 +40,7 @@ app.get('/:cmd', (req, res) => { res.send(ret.rows); }); } catch (e) { - res.status(400).send({message: e.message}); + res.status(400).send({ message: e.message }); span.setStatus(CanonicalCode.UNKNOWN); } span.end(); @@ -54,7 +49,6 @@ app.get('/:cmd', (req, res) => { // start server const port = 3000; -app.listen(port, function() { +app.listen(port, () => { console.log(`Node HTTP listening on ${port}`); }); - diff --git a/examples/postgres/setupPsql.js b/examples/postgres/setupPsql.js index 988e23a467..d6722b840e 100644 --- a/examples/postgres/setupPsql.js +++ b/examples/postgres/setupPsql.js @@ -1,28 +1,31 @@ +'use strict'; + const { Pool } = require('pg'); // create new pool for psql const CONFIG = { - user: process.env.POSTGRES_USER || 'postgres', - database: process.env.POSTGRES_DB || 'postgres', - host: process.env.POSTGRES_HOST || 'localhost', - port: process.env.POSTGRES_PORT - ? parseInt(process.env.POSTGRES_PORT, 10) - : 54320, - }; - + user: process.env.POSTGRES_USER || 'postgres', + database: process.env.POSTGRES_DB || 'postgres', + host: process.env.POSTGRES_HOST || 'localhost', + port: process.env.POSTGRES_PORT + ? parseInt(process.env.POSTGRES_PORT, 10) + : 54320, +}; + function startPsql() { - let pool = new Pool(CONFIG); + const pool = new Pool(CONFIG); - pool.connect(function(err, client, release) { - if (err) throw err; - release(); - const queryText = 'CREATE TABLE IF NOT EXISTS test(id SERIAL PRIMARY KEY, text VARCHAR(40) not null)'; - client.query(queryText, (err, res) => { - if (err) throw err; - }); + pool.connect((connectErr, client, release) => { + if (connectErr) throw connectErr; + release(); + const queryText = 'CREATE TABLE IF NOT EXISTS test(id SERIAL PRIMARY KEY, text VARCHAR(40) not null)'; + client.query(queryText, (err, res) => { + if (err) throw err; + console.log(res.rows[0]); }); + }); - return pool; + return pool; } exports.startPsql = startPsql; diff --git a/examples/postgres/setup.js b/examples/postgres/tracer.js similarity index 68% rename from examples/postgres/setup.js rename to examples/postgres/tracer.js index 1c369a0f48..ab1d34ddc1 100644 --- a/examples/postgres/setup.js +++ b/examples/postgres/tracer.js @@ -5,37 +5,41 @@ 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 || ''; -function setupTracerAndExporters(service) { +module.exports = (serviceName) => { const tracer = new NodeTracer({ plugins: { pg: { enabled: true, - // if it can't find the module, put the absolute path since the packages are not published yet - path: '@opentelemetry/plugin-pg' + /* + if it can't find the module, + put the absolute path since the packages are not published yet + */ + path: '@opentelemetry/plugin-pg', }, 'pg-pool': { enabled: true, - path: '@opentelemetry/plugin-pg-pool' + path: '@opentelemetry/plugin-pg-pool', }, http: { enabled: true, - path: '@opentelemetry/plugin-http' - } - } + path: '@opentelemetry/plugin-http', + }, + }, }); let exporter; if (EXPORTER.toLowerCase().startsWith('z')) { exporter = new ZipkinExporter({ - serviceName: service, + serviceName, }); } else { exporter = new JaegerExporter({ - serviceName: service, + serviceName, // The default flush interval is 5 seconds. - flushInterval: 2000 + flushInterval: 2000, }); } @@ -43,6 +47,6 @@ function setupTracerAndExporters(service) { // Initialize the OpenTelemetry APIs to use the BasicTracer bindings opentelemetry.initGlobalTracer(tracer); -} -exports.setupTracerAndExporters = setupTracerAndExporters; + return opentelemetry.getTracer(); +}; diff --git a/examples/prometheus/index.js b/examples/prometheus/index.js index fea1d1c9d8..7e6a85dee9 100644 --- a/examples/prometheus/index.js +++ b/examples/prometheus/index.js @@ -1,4 +1,4 @@ -"use strict"; +'use strict'; const { MeterRegistry } = require('@opentelemetry/metrics'); const { PrometheusExporter } = require('@opentelemetry/exporter-prometheus'); @@ -7,37 +7,37 @@ const meter = new MeterRegistry().getMeter('example-prometheus'); const exporter = new PrometheusExporter( { - startServer: true + startServer: true, }, () => { - console.log("prometheus scrape endpoint: http://localhost:9464/metrics"); - } + console.log('prometheus scrape endpoint: http://localhost:9464/metrics'); + }, ); meter.addExporter(exporter); // Monotonic counters and gauges can only be increased. -const monotonicCounter = meter.createCounter("monotonic_counter", { +const monotonicCounter = meter.createCounter('monotonic_counter', { monotonic: true, - labelKeys: ["pid"], - description: "Example of a monotonic counter" + labelKeys: ['pid'], + description: 'Example of a monotonic counter', }); -const monotonicGauge = meter.createGauge("monotonic_gauge", { +const monotonicGauge = meter.createGauge('monotonic_gauge', { monotonic: true, - labelKeys: ["pid"], - description: "Example of a monotonic gauge" + labelKeys: ['pid'], + description: 'Example of a monotonic gauge', }); // Non-monotonic counters and gauges can be increased or decreased. -const nonMonotonicCounter = meter.createCounter("non_monotonic_counter", { +const nonMonotonicCounter = meter.createCounter('non_monotonic_counter', { monotonic: false, - labelKeys: ["pid"], - description: "Example of a non-monotonic counter" + labelKeys: ['pid'], + description: 'Example of a non-monotonic counter', }); -const nonMonotonicGauge = meter.createGauge("non_monotonic_gauge", { +const nonMonotonicGauge = meter.createGauge('non_monotonic_gauge', { monotonic: false, - labelKeys: ["pid"], - description: "Example of a non-monotonic gauge" + labelKeys: ['pid'], + description: 'Example of a non-monotonic gauge', }); let currentMonotonicGaugeValue = 0; diff --git a/examples/redis/client.js b/examples/redis/client.js index 191effe612..30fd9b65ca 100644 --- a/examples/redis/client.js +++ b/examples/redis/client.js @@ -1,30 +1,28 @@ -'use strict' +'use strict'; -const opentelemetry = require('@opentelemetry/core'); +// eslint-disable-next-line import/order +const tracer = require('./tracer')('example-redis-client'); const types = require('@opentelemetry/types'); -const config = require('./setup'); -config.setupTracerAndExporters('redis-client-service'); -const tracer = opentelemetry.getTracer('example-redis-client'); const axios = require('axios').default; function makeRequest() { - const span = tracer.startSpan('client.makeRequest()', { - parent: tracer.getCurrentSpan(), - kind: types.SpanKind.CLIENT - }); + 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); - }); + 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/redis/express-tracer-handlers.js b/examples/redis/express-tracer-handlers.js index 25918318a1..1e15608ab5 100644 --- a/examples/redis/express-tracer-handlers.js +++ b/examples/redis/express-tracer-handlers.js @@ -1,36 +1,36 @@ -'use strict' +'use strict'; const types = require('@opentelemetry/types'); function getMiddlewareTracer(tracer) { - return function(req, res, next) { + return (req, res, next) => { const span = tracer.startSpan(`express.middleware.tracer(${req.method} ${req.path})`, { parent: tracer.getCurrentSpan(), kind: types.SpanKind.SERVER, }); - + // End this span before sending out the response const originalSend = res.send; - res.send = function send() { + res.send = function send(...args) { span.end(); - originalSend.apply(res, arguments); - } - + originalSend.apply(res, args); + }; + tracer.withSpan(span, next); - } + }; } function getErrorTracer(tracer) { - return function(err, _req, res, _next) { - console.log('Caught error', err.message); + return (err, _req, res, _next) => { + console.error('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 -} + getMiddlewareTracer, getErrorTracer, +}; diff --git a/examples/redis/server.js b/examples/redis/server.js index 33744b2f74..f293084e2d 100644 --- a/examples/redis/server.js +++ b/examples/redis/server.js @@ -1,15 +1,13 @@ 'use strict'; -// Setup opentelemetry tracer first so that built-in plugins can hook onto their corresponding modules -const opentelemetry = require('@opentelemetry/core'); -const config = require('./setup'); -config.setupTracerAndExporters('redis-server-service'); -const tracer = opentelemetry.getTracer('example-redis-server'); +// eslint-disable-next-line import/order +const tracer = require('./tracer')('example-redis-server'); // Require in rest of modules const express = require('express'); const axios = require('axios').default; const tracerHandlers = require('./express-tracer-handlers'); +const redisPromise = require('./setup-redis').redis; // Setup express const app = express(); @@ -19,10 +17,15 @@ const PORT = 8080; * Redis Routes are set up async since we resolve the client once it is successfully connected */ async function setupRoutes() { - const redis = await require('./setup-redis').redis; + const redis = await redisPromise; app.get('/run_test', async (req, res) => { - const uuid = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); + 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`); @@ -39,12 +42,12 @@ async function setupRoutes() { return; } - const cmd = req.params.cmd; + 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) { + } else if (result) { res.status(200).send(result); } else { throw new Error('Empty redis response'); @@ -58,5 +61,5 @@ app.use(tracerHandlers.getMiddlewareTracer(tracer)); setupRoutes().then(() => { app.use(tracerHandlers.getErrorTracer(tracer)); app.listen(PORT); - console.log(`Listening on http://localhost:${PORT}`) + console.log(`Listening on http://localhost:${PORT}`); }); diff --git a/examples/redis/setup-redis.js b/examples/redis/setup-redis.js index dba4f0ebad..59b2e189b5 100644 --- a/examples/redis/setup-redis.js +++ b/examples/redis/setup-redis.js @@ -1,13 +1,15 @@ +'use strict'; + const redis = require('redis'); const client = redis.createClient('redis://localhost:6379'); -const redisPromise = new Promise(function(resolve, reject) { +const redisPromise = new Promise(((resolve, reject) => { client.once('ready', () => { resolve(client); }); client.once('error', (error) => { reject(error); }); -}); +})); exports.redis = redisPromise; diff --git a/examples/http/setup.js b/examples/redis/tracer.js similarity index 83% rename from examples/http/setup.js rename to examples/redis/tracer.js index 770cdd5dfd..fa2680830a 100644 --- a/examples/http/setup.js +++ b/examples/redis/tracer.js @@ -5,19 +5,21 @@ const { NodeTracerRegistry } = 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 || ''; -function setupTracerAndExporters(service) { + +module.exports = (serviceName) => { const registry = new NodeTracerRegistry(); let exporter; if (EXPORTER.toLowerCase().startsWith('z')) { exporter = new ZipkinExporter({ - serviceName: service, + serviceName, }); } else { exporter = new JaegerExporter({ - serviceName: service, + serviceName, }); } @@ -25,6 +27,6 @@ function setupTracerAndExporters(service) { // Initialize the OpenTelemetry APIs to use the BasicTracerRegistry bindings opentelemetry.initGlobalTracerRegistry(registry); -} -exports.setupTracerAndExporters = setupTracerAndExporters; + return opentelemetry.getTracer(); +}; diff --git a/examples/stackdriver-trace/index.js b/examples/stackdriver-trace/index.js index 809fc4e8f0..277ddba431 100644 --- a/examples/stackdriver-trace/index.js +++ b/examples/stackdriver-trace/index.js @@ -8,7 +8,7 @@ const { StackdriverTraceExporter } = require('@opentelemetry/exporter-stackdrive // Initialize an exporter const exporter = new StackdriverTraceExporter({ serviceName: 'basic-service', - logger: new opentelemetry.ConsoleLogger() + logger: new opentelemetry.ConsoleLogger(), }); const tracer = new BasicTracer(); @@ -22,17 +22,17 @@ opentelemetry.initGlobalTracer(tracer); // Create a span. A span must be closed. const root = opentelemetry.getTracer().startSpan('main'); const related = opentelemetry.getTracer().startSpan('related', { - links: [{ spanContext: root.context() }] + links: [{ spanContext: root.context() }], }); -for (let i = 0; i < 10; i++) { +for (let i = 0; i < 10; i += 1) { doWork(root); doWork(related); } // Be sure to end the span. root.setStatus({ - code: CanonicalCode.UNKNOWN -}) + code: CanonicalCode.UNKNOWN, +}); root.end(); related.end(); @@ -43,17 +43,19 @@ function doWork(parent) { // Start another span. In this example, the main method already started a // span, so that'll be the parent span, and this will be a child span. const span = opentelemetry.getTracer().startSpan('doWork', { - parent: parent + parent, }); // simulate some random work. const work = Math.floor(Math.random() * 40000000); - for (let i = 0; i <= work; i++) { } + for (let i = 0; i <= work; i += 1) { + // empty + } if (work % 2 === 1) { span.setStatus({ - code: CanonicalCode.UNKNOWN - }) + code: CanonicalCode.UNKNOWN, + }); } // Set attributes to the span. diff --git a/examples/tracer-web/.eslintrc b/examples/tracer-web/.eslintrc new file mode 100644 index 0000000000..e2338e5e0b --- /dev/null +++ b/examples/tracer-web/.eslintrc @@ -0,0 +1,16 @@ +{ + "env": { + "node": true + }, + "extends": "airbnb-base", + "parserOptions": { + "sourceType": "module" + }, + "rules": { + "strict": ["error", "global"], + "no-use-before-define": ["error", "nofunc"], + "no-console": "off", + "import/no-unresolved": "off", + "no-unused-vars": ["error", { "argsIgnorePattern": "^_" }] + } +} diff --git a/examples/tracer-web/examples/document-load/index.js b/examples/tracer-web/examples/document-load/index.js index bd42b14797..77b7248825 100644 --- a/examples/tracer-web/examples/document-load/index.js +++ b/examples/tracer-web/examples/document-load/index.js @@ -2,43 +2,61 @@ import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/tracing import { WebTracerRegistry } from '@opentelemetry/web'; import { DocumentLoad } from '@opentelemetry/plugin-document-load'; import { ZoneScopeManager } from '@opentelemetry/scope-zone'; -import { CollectorExporter } from '@opentelemetry/exporter-collector' +import { CollectorExporter } from '@opentelemetry/exporter-collector'; const registry = new WebTracerRegistry({ plugins: [ - new DocumentLoad() - ] + new DocumentLoad(), + ], }); registry.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); const registryWithZone = new WebTracerRegistry({ scopeManager: new ZoneScopeManager(), plugins: [ - new DocumentLoad() - ] + new DocumentLoad(), + ], }); registryWithZone.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); registryWithZone.addSpanProcessor(new SimpleSpanProcessor(new CollectorExporter())); const tracerWithZone = registryWithZone.getTracer('example-tracer-web'); +let window; console.log('Current span is window', tracerWithZone.getCurrentSpan() === window); +const getData = (url) => new Promise((resolve, reject) => { + // eslint-disable-next-line no-undef + const req = new XMLHttpRequest(); + req.open('GET', url, true); + req.send(); + req.onload = () => { + let json; + try { + json = JSON.parse(req.responseText); + } catch (e) { + reject(e); + } + resolve(json); + }; +}); + // example of keeping track of scope between async operations const prepareClickEvent = () => { const url1 = 'https://raw.githubusercontent.com/open-telemetry/opentelemetry-js/master/package.json'; const url2 = 'https://raw.githubusercontent.com/open-telemetry/opentelemetry-js/master/packages/opentelemetry-web/package.json'; + let document; const element = document.getElementById('button1'); - let mainSpan = tracerWithZone.startSpan('main-span'); + const mainSpan = tracerWithZone.startSpan('main-span'); tracerWithZone.bind(element, mainSpan); const onClick = () => { - const span1 = tracerWithZone.startSpan(`files-series-info-1`, { - parent: tracerWithZone.getCurrentSpan() + const span1 = tracerWithZone.startSpan('files-series-info-1', { + parent: tracerWithZone.getCurrentSpan(), }); - const span2 = tracerWithZone.startSpan(`files-series-info-2`, { - parent: tracerWithZone.getCurrentSpan() + const span2 = tracerWithZone.startSpan('files-series-info-2', { + parent: tracerWithZone.getCurrentSpan(), }); tracerWithZone.withSpan(span1, () => { @@ -64,21 +82,4 @@ const prepareClickEvent = () => { element.addEventListener('click', onClick); }; -const getData = (url) => { - return new Promise(async (resolve, reject) => { - const req = new XMLHttpRequest(); - req.open('GET', url, true); - req.send(); - req.onload = function () { - let json; - try { - json = JSON.parse(req.responseText); - } catch (e) { - reject(e); - } - resolve(json); - }; - }); -}; - window.addEventListener('load', prepareClickEvent); diff --git a/examples/tracer-web/examples/xml-http-request/index.js b/examples/tracer-web/examples/xml-http-request/index.js index 9e5ff9d2e3..d6698223d6 100644 --- a/examples/tracer-web/examples/xml-http-request/index.js +++ b/examples/tracer-web/examples/xml-http-request/index.js @@ -1,4 +1,3 @@ -'use strict'; import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/tracing'; import { WebTracer } from '@opentelemetry/web'; @@ -14,28 +13,41 @@ const webTracerWithZone = new WebTracer({ new XMLHttpRequestPlugin({ ignoreUrls: [/localhost:8090\/sockjs-node/], propagateTraceHeaderCorsUrls: [ - 'https://httpbin.org/get' - ] - }) - ] + 'https://httpbin.org/get', + ], + }), + ], }); webTracerWithZone.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); webTracerWithZone.addSpanProcessor(new SimpleSpanProcessor(new CollectorExporter())); +const getData = (url) => new Promise((resolve, _reject) => { + // eslint-disable-next-line no-undef + const req = new XMLHttpRequest(); + req.open('GET', url, true); + req.setRequestHeader('Content-Type', 'application/json'); + req.setRequestHeader('Accept', 'application/json'); + req.send(); + req.onload = () => { + resolve(); + }; +}); + // example of keeping track of scope between async operations const prepareClickEvent = () => { const url1 = 'https://httpbin.org/get'; + let document; const element = document.getElementById('button1'); const onClick = () => { - for (let i = 0, j = 5; i < j; i++) { + for (let i = 0, j = 5; i < j; i += 1) { const span1 = webTracerWithZone.startSpan(`files-series-info-${i}`, { - parent: webTracerWithZone.getCurrentSpan() + parent: webTracerWithZone.getCurrentSpan(), }); webTracerWithZone.withSpan(span1, () => { - getData(url1).then((data) => { + getData(url1).then((_data) => { webTracerWithZone.getCurrentSpan().addEvent('fetching-span1-completed'); span1.end(); }); @@ -45,17 +57,5 @@ const prepareClickEvent = () => { element.addEventListener('click', onClick); }; -const getData = (url) => { - return new Promise(async (resolve, reject) => { - const req = new XMLHttpRequest(); - req.open('GET', url, true); - req.setRequestHeader('Content-Type', 'application/json'); - req.setRequestHeader('Accept', 'application/json'); - req.send(); - req.onload = function () { - resolve(); - }; - }); -}; - +let window; window.addEventListener('load', prepareClickEvent); diff --git a/examples/tracer-web/webpack.config.js b/examples/tracer-web/webpack.config.js index a73bffb8e6..8f7fed9410 100644 --- a/examples/tracer-web/webpack.config.js +++ b/examples/tracer-web/webpack.config.js @@ -1,18 +1,19 @@ const webpack = require('webpack'); const webpackMerge = require('webpack-merge'); const path = require('path'); + const directory = path.resolve(__dirname); const common = { mode: 'development', entry: { 'document-load': 'examples/document-load/index.js', - 'xml-http-request': 'examples/xml-http-request/index.js' + 'xml-http-request': 'examples/xml-http-request/index.js', }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].js', - sourceMapFilename: '[file].map' + sourceMapFilename: '[file].map', }, target: 'web', module: { @@ -21,35 +22,35 @@ const common = { test: /\.js[x]?$/, exclude: /(node_modules)/, use: { - loader: 'babel-loader' - } + loader: 'babel-loader', + }, }, { test: /\.ts$/, exclude: /(node_modules)/, use: { - loader: 'ts-loader' - } - } - ] + loader: 'ts-loader', + }, + }, + ], }, resolve: { modules: [ path.resolve(directory), - 'node_modules' + 'node_modules', ], - extensions: ['.ts', '.js', '.jsx', '.json'] - } + extensions: ['.ts', '.js', '.jsx', '.json'], + }, }; module.exports = webpackMerge(common, { devtool: 'eval-source-map', devServer: { - contentBase: path.resolve(__dirname) + contentBase: path.resolve(__dirname), }, plugins: [ new webpack.DefinePlugin({ - 'process.env.NODE_ENV': JSON.stringify('development') - }) - ] + 'process.env.NODE_ENV': JSON.stringify('development'), + }), + ], }); diff --git a/package.json b/package.json index f2c261d056..8f7b383bd1 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,9 @@ "predocs-test": "yarn docs", "docs-test": "lerna run docs-test", "docs": "lerna run docs", - "docs-deploy": "gh-pages --dist packages/opentelemetry-types/docs/out" + "docs-deploy": "gh-pages --dist packages/opentelemetry-types/docs/out", + "lint-examples": "eslint ./examples/**/*.js", + "fix-examples": "eslint ./examples/**/*.js --fix" }, "repository": "open-telemetry/opentelemetry-js", "keywords": [ @@ -40,6 +42,9 @@ "@commitlint/config-conventional": "^8.2.0", "beautify-benchmark": "^0.2.4", "benchmark": "^2.1.4", + "eslint": "^6.8.0", + "eslint-config-airbnb-base": "^14.0.0", + "eslint-plugin-import": "^2.19.1", "gh-pages": "^2.1.1", "gts": "^1.1.0", "husky": "^3.0.9",