all files / src/ tracer.js

97.1% Statements 134/138
85.9% Branches 67/78
100% Functions 12/12
97.04% Lines 131/135
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349                                                                                132× 132× 132×   132× 132× 132× 132×   132×   132× 132× 132× 132× 132×       132× 132× 132×   132×           132× 132× 132×   132×   132× 132× 132×   132× 132× 132×   132× 132× 132×         132×   132×                         115× 115×   115× 115×     115× 108× 108× 74× 34× 17×           115×       56× 56×       405×       405×                                                         114× 114×   114× 114×       114× 114×   114×                     114× 114×   114× 114× 114× 80× 80× 80× 73×     80×         80× 80× 80× 80×   34× 34× 34× 34×     34×   34× 34×     114×                                               13×       13× 13×     12×     12× 12×                           21× 21×     20×   20× 17×   20×                 47× 47× 47× 47×   47×                     204×            
// @flow
// Copyright (c) 2016 Uber Technologies, Inc.
//
// 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.
 
import BinaryCodec from './propagators/binary_codec';
import ConstSampler from './samplers/const_sampler';
import * as constants from './constants';
import * as opentracing from 'opentracing';
import pjson from '../package.json';
import { Tags as opentracing_tags } from 'opentracing';
import NoopReporter from './reporters/noop_reporter';
import Span from './span';
import SpanContext from './span_context';
import TextMapCodec from './propagators/text_map_codec';
import NullLogger from './logger';
import Utils from './util';
import Metrics from './metrics/metrics';
import NoopMetricFactory from './metrics/noop/metric_factory';
import DefaultBaggageRestrictionManager from './baggage/default_baggage_restriction_manager';
import os from 'os';
import BaggageSetter from './baggage/baggage_setter';
import DefaultThrottler from './throttler/default_throttler';
import uuidv4 from 'uuid/v4';
 
export default class Tracer {
  _serviceName: string;
  _reporter: Reporter;
  _sampler: Sampler;
  _logger: NullLogger;
  _tags: any;
  _injectors: any;
  _extractors: any;
  _metrics: any;
  _baggageSetter: BaggageSetter;
  _debugThrottler: Throttler & ProcessSetter;
  _process: Process;
 
  /**
   * @param {String} [serviceName] - name of the current service or application.
   * @param {Object} [reporter] - reporter used to submit finished spans to Jaeger backend.
   * @param {Object} [sampler] - sampler used to decide if trace should be sampled when starting a new one.
   * @param {Object} [options] - the fields to set on the newly created span.
   * @param {Object} [options.tags] - set of key-value pairs which will be set
   *        as process-level tags on the Tracer itself.
   * @param {Object} [options.metrics] - instance of the Metrics class from ./metrics/metrics.js.
   * @param {Object} [options.logger] - a logger matching NullLogger API from ./logger.js.
   * @param {Object} [options.baggageRestrictionManager] - a baggageRestrictionManager matching
   * BaggageRestrictionManager API from ./baggage.js.
   */
  constructor(
    serviceName: string,
    reporter: Reporter = new NoopReporter(),
    sampler: Sampler = new ConstSampler(false),
    options: any = {}
  ) {
    this._tags = options.tags || {};
    this._tags[constants.JAEGER_CLIENT_VERSION_TAG_KEY] = `Node-${pjson.version}`;
    this._tags[constants.TRACER_HOSTNAME_TAG_KEY] = os.hostname();
    this._tags[constants.PROCESS_IP] = Utils.ipToInt(Utils.myIp());
 
    this._metrics = options.metrics || new Metrics(new NoopMetricFactory());
 
    this._serviceName = serviceName;
    this._reporter = reporter;
    this._sampler = sampler;
    this._logger = options.logger || new NullLogger();
    this._baggageSetter = new BaggageSetter(
      options.baggageRestrictionManager || new DefaultBaggageRestrictionManager(),
      this._metrics
    );
    this._debugThrottler = options.debugThrottler || new DefaultThrottler(false);
    this._injectors = {};
    this._extractors = {};
 
    let codecOptions = {
      contextKey: options.contextKey || null,
      urlEncoding: false,
      metrics: this._metrics,
    };
 
    let textCodec = new TextMapCodec(codecOptions);
    this.registerInjector(opentracing.FORMAT_TEXT_MAP, textCodec);
    this.registerExtractor(opentracing.FORMAT_TEXT_MAP, textCodec);
 
    codecOptions.urlEncoding = true;
 
    let httpCodec = new TextMapCodec(codecOptions);
    this.registerInjector(opentracing.FORMAT_HTTP_HEADERS, httpCodec);
    this.registerExtractor(opentracing.FORMAT_HTTP_HEADERS, httpCodec);
 
    let binaryCodec = new BinaryCodec();
    this.registerInjector(opentracing.FORMAT_BINARY, binaryCodec);
    this.registerExtractor(opentracing.FORMAT_BINARY, binaryCodec);
 
    const uuid = uuidv4();
    this._tags[constants.TRACER_CLIENT_ID_TAG_KEY] = uuid;
    this._process = {
      serviceName: serviceName,
      tags: Utils.convertObjectToTags(this._tags),
      uuid: uuid,
    };
    this._debugThrottler.setProcess(this._process);
    // TODO update reporter to implement ProcessSetter
    this._reporter.setProcess(this._process.serviceName, this._process.tags);
  }
 
  _startInternalSpan(
    spanContext: SpanContext,
    operationName: string,
    startTime: number,
    userTags: any,
    internalTags: any,
    parentContext: ?SpanContext,
    rpcServer: boolean,
    references: Array<Reference>
  ): Span {
    let hadParent = parentContext && !parentContext.isDebugIDContainerOnly();
    let span = new Span(this, operationName, spanContext, startTime, references);
 
    span.addTags(userTags);
    span.addTags(internalTags);
 
    // emit metrics
    if (span.context().isSampled()) {
      this._metrics.spansStartedSampled.increment(1);
      if (!hadParent) {
        this._metrics.tracesStartedSampled.increment(1);
      } else if (rpcServer) {
        this._metrics.tracesJoinedSampled.increment(1);
      }
    } else {
      this._metrics.spansStartedNotSampled.increment(1);
      if (!hadParent) {
        this._metrics.tracesStartedNotSampled.increment(1);
      } else Eif (rpcServer) {
        this._metrics.tracesJoinedNotSampled.increment(1);
      }
    }
 
    return span;
  }
 
  _report(span: Span): void {
    this._metrics.spansFinished.increment(1);
    this._reporter.report(span);
  }
 
  registerInjector(format: string, injector: Injector): void {
    this._injectors[format] = injector;
  }
 
  registerExtractor(format: string, extractor: Extractor): void {
    this._extractors[format] = extractor;
  }
 
  /**
   * The method for creating a root or child span.
   *
   * @param {string} operationName - the name of the operation.
   * @param {object} [options] - the fields to set on the newly created span.
   * @param {string} options.operationName - the name to use for the newly
   *        created span. Required if called with a single argument.
   * @param {SpanContext} [options.childOf] - a parent SpanContext (or Span,
   *        for convenience) that the newly-started span will be the child of
   *        (per REFERENCE_CHILD_OF). If specified, `fields.references` must
   *        be unspecified.
   * @param {array} [options.references] - an array of Reference instances,
   *        each pointing to a causal parent SpanContext. If specified,
   *        `fields.childOf` must be unspecified.
   * @param {object} [options.tags] - set of key-value pairs which will be set
   *        as tags on the newly created Span. Ownership of the object is
   *        passed to the created span for efficiency reasons (the caller
   *        should not modify this object after calling startSpan).
   * @param {number} [options.startTime] - a manually specified start time for
   *        the created Span object. The time should be specified in
   *        milliseconds as Unix timestamp. Decimal value are supported
   *        to represent time values with sub-millisecond accuracy.
   * @return {Span} - a new Span object.
   **/
  startSpan(operationName: string, options: ?startSpanOptions): Span {
    // Convert options.childOf to options.references as needed.
    options = options || {};
    let references = options.references || [];
 
    let userTags = options.tags || {};
    let startTime = options.startTime || this.now();
 
    // This flag is used to ensure that CHILD_OF reference is preferred
    // as a parent even if it comes after FOLLOWS_FROM reference.
    let followsFromIsParent = false;
    let parent: ?SpanContext = options.childOf instanceof Span ? options.childOf.context() : options.childOf;
    // If there is no childOf in options, then search list of references
    for (let i = 0; i < references.length; i++) {
      let ref: Reference = references[i];
      if (Eref.type() === opentracing.REFERENCE_CHILD_OF) {
        if (E!parent || followsFromIsParent) {
          parent = ref.referencedContext();
          break;
        }
      } else if (ref.type() === opentracing.REFERENCE_FOLLOWS_FROM) {
        if (!parent) {
          parent = ref.referencedContext();
          followsFromIsParent = true;
        }
      }
    }
 
    let spanKindValue = userTags[opentracing_tags.SPAN_KIND];
    let rpcServer = spanKindValue === opentracing_tags.SPAN_KIND_RPC_SERVER;
 
    let ctx: SpanContext = new SpanContext();
    let internalTags: any = {};
    if (!parent || !parent.isValid) {
      let randomId = Utils.getRandom64();
      let flags = 0;
      if (this._sampler.isSampled(operationName, internalTags)) {
        flags |= constants.SAMPLED_MASK;
      }
 
      if (parent) {
        if (parent.isDebugIDContainerOnly() && this._isDebugAllowed(operationName)) {
          flags |= constants.SAMPLED_MASK | constants.DEBUG_MASK;
          internalTags[constants.JAEGER_DEBUG_HEADER] = parent.debugId;
        }
        // baggage that could have been passed via `jaeger-baggage` header
        ctx.baggage = parent.baggage;
      }
 
      ctx.traceId = randomId;
      ctx.spanId = randomId;
      ctx.parentId = null;
      ctx.flags = flags;
    } else {
      ctx.traceId = parent.traceId;
      ctx.spanId = Utils.getRandom64();
      ctx.parentId = parent.spanId;
      ctx.flags = parent.flags;
 
      // reuse parent's baggage as we'll never change it
      ctx.baggage = parent.baggage;
 
      parent.finalizeSampling();
      ctx.finalizeSampling();
    }
 
    return this._startInternalSpan(
      ctx,
      operationName,
      startTime,
      userTags,
      internalTags,
      parent,
      rpcServer,
      references
    );
  }
 
  /**
   * Saves the span context into the carrier object for various formats, and encoders.
   *
   * @param  {SpanContext} spanContext - the SpanContext to inject into the
   *         carrier object. As a convenience, a Span instance may be passed
   *         in instead (in which case its .context() is used for the
   *         inject()).
   * @param  {string} format - the format of the carrier.
   * @param  {any} carrier - see the documentation for the chosen `format`
   *         for a description of the carrier object.
   **/
  inject(spanContext: SpanContext | Span, format: string, carrier: any): void {
    if (I!spanContext) {
      return;
    }
 
    let injector = this._injectors[format];
    if (!injector) {
      throw new Error(`Unsupported format: ${format}`);
    }
 
    if (spanContext instanceof Span) {
      spanContext = spanContext.context();
    }
 
    spanContext.finalizeSampling();
    injector.inject(spanContext, carrier);
  }
 
  /**
   * Responsible for extracting a span context from various serialized formats.
   *
   * @param  {string} format - the format of the carrier.
   * @param  {any} carrier - the type of the carrier object is determined by
   *         the format.
   * @return {SpanContext}
   *         The extracted SpanContext, or null if no such SpanContext could
   *         be found in `carrier`
   */
  extract(format: string, carrier: any): SpanContext {
    let extractor = this._extractors[format];
    if (!extractor) {
      throw new Error(`Unsupported format: ${format}`);
    }
 
    let spanContext = extractor.extract(carrier);
 
    if (spanContext) {
      spanContext.finalizeSampling();
    }
    return spanContext;
  }
 
  /**
   * Closes the tracer, flushes spans, and executes any callbacks if necessary.
   *
   * @param {Function} [callback] - a callback that runs after the tracer has been closed.
   **/
  close(callback: Function): void {
    let reporter = this._reporter;
    this._reporter = new NoopReporter();
    reporter.close(() => {
      this._sampler.close(callback);
    });
    this._debugThrottler.close();
  }
 
  /**
   * Returns the current timestamp in milliseconds since the Unix epoch.
   * Fractional values are allowed so that timestamps with sub-millisecond
   * accuracy can be represented.
   */
  now(): number {
    // TODO investigate process.hrtime; verify it is available in all Node versions.
    // http://stackoverflow.com/questions/11725691/how-to-get-a-microtime-in-node-js
    return Date.now();
  }
 
  _isDebugAllowed(operation: string): boolean {
    return this._debugThrottler.isAllowed(operation);
  }
}