io.opencensus.tags.TagValue Java Examples

The following examples show how to use io.opencensus.tags.TagValue. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RpczZPageHandler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private void getStatsSnapshots(Map<String, StatsSnapshot> map, List<View> views) {
  for (View view : views) {
    ViewData viewData = viewManager.getView(view.getName());
    if (viewData == null) {
      continue;
    }
    for (Entry<List</*@Nullable*/ TagValue>, AggregationData> entry :
        viewData.getAggregationMap().entrySet()) {
      TagValue tagValue;
      List</*@Nullable*/ TagValue> tagValues = entry.getKey();
      if (tagValues.size() == 1) {
        tagValue = tagValues.get(0);
      } else { // Error count views have two tag key: status and method.
        tagValue = tagValues.get(1);
      }
      String method = tagValue == null ? "" : tagValue.asString();
      StatsSnapshot snapshot = map.get(method);
      if (snapshot == null) {
        snapshot = new StatsSnapshot();
        map.put(method, snapshot);
      }

      getStats(snapshot, entry.getValue(), view, viewData.getWindowData());
    }
  }
}
 
Example #2
Source File: GoogleDtpInternalMetricRecorder.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Override
public void importPageAttemptFinished(
    String dataType,
    String service,
    boolean success,
    Duration duration) {
  TagContext tctx = tagger.emptyBuilder()
      .put(KEY_DATA_TYPE, TagValue.create(dataType), TAG_METADATA)
      .put(KEY_IMPORT_SERVICE, TagValue.create(service), TAG_METADATA)
      .put(KEY_SUCCESS, TagValue.create(Boolean.toString(success)), TAG_METADATA)
      .build();
  try (Scope ss = tagger.withTagContext(tctx)) {
    STATS_RECORDER.newMeasureMap()
        .put(IMPORT_PAGE_ATTEMPT, 1)
        .put(IMPORT_PAGE_ATTEMPT_DURATION, duration.toMillis())
        .record();
  }
}
 
Example #3
Source File: TagContextSerializationTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializeTooLargeTagContext() throws TagContextSerializationException {
  TagContextBuilder builder = tagger.emptyBuilder();
  for (int i = 0; i < BinarySerializationUtils.TAGCONTEXT_SERIALIZED_SIZE_LIMIT / 8 - 1; i++) {
    // Each tag will be with format {key : "0123", value : "0123"}, so the length of it is 8.
    String str;
    if (i < 10) {
      str = "000" + i;
    } else if (i < 100) {
      str = "00" + i;
    } else if (i < 1000) {
      str = "0" + i;
    } else {
      str = String.valueOf(i);
    }
    builder.put(TagKey.create(str), TagValue.create(str));
  }
  // The last tag will be of size 9, so the total size of the TagContext (8193) will be one byte
  // more than limit.
  builder.put(TagKey.create("last"), TagValue.create("last1"));

  TagContext tagContext = builder.build();
  thrown.expect(TagContextSerializationException.class);
  thrown.expectMessage("Size of TagContext exceeds the maximum serialized size ");
  serializer.toByteArray(tagContext);
}
 
Example #4
Source File: GoogleDtpInternalMetricRecorder.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Override
public void exportPageAttemptFinished(
    String dataType,
    String service,
    boolean success,
    Duration duration) {
  TagContext tctx = tagger.emptyBuilder()
      .put(KEY_DATA_TYPE, TagValue.create(dataType), TAG_METADATA)
      .put(KEY_EXPORT_SERVICE, TagValue.create(service), TAG_METADATA)
      .put(KEY_SUCCESS, TagValue.create(Boolean.toString(success)), TAG_METADATA)
      .build();
  try (Scope ss = tagger.withTagContext(tctx)) {
    STATS_RECORDER.newMeasureMap()
        .put(EXPORT_PAGE_ATTEMPT, 1)
        .put(EXPORT_PAGE_ATTEMPT_DURATION, duration.toMillis())
        .record();
  }
}
 
Example #5
Source File: GoogleDtpInternalMetricRecorder.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Override
public void finishedJob(
    String dataType,
    String exportService,
    String importService,
    boolean success,
    Duration duration) {
  TagContext tctx = tagger.emptyBuilder()
      .put(KEY_DATA_TYPE, TagValue.create(dataType), TAG_METADATA)
      .put(KEY_EXPORT_SERVICE, TagValue.create(exportService), TAG_METADATA)
      .put(KEY_IMPORT_SERVICE, TagValue.create(importService), TAG_METADATA)
      .put(KEY_SUCCESS, TagValue.create(Boolean.toString(success)), TAG_METADATA)
      .build();
  try (Scope ss = tagger.withTagContext(tctx)) {
    STATS_RECORDER.newMeasureMap()
        .put(JOB_FINISHED, 1)
        .put(JOB_FINISHED_DURATION, duration.toMillis())
        .record();
  }
}
 
Example #6
Source File: OpenCensusMetricExporterSpi.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void spiStart(@Nullable String igniteInstanceName) throws IgniteSpiException {
    super.spiStart(igniteInstanceName);

    if (sendInstanceName) {
        tags.add(INSTANCE_NAME_TAG);

        instanceNameValue = TagValue.create(igniteInstanceName);
    }

    if (sendNodeId) {
        tags.add(NODE_ID_TAG);

        nodeIdValue = TagValue.create(((IgniteEx)ignite()).context().localNodeId().toString());
    }

    if (sendConsistentId) {
        tags.add(CONSISTENT_ID_TAG);

        //Node consistent id will be known in #onContextInitialized0(IgniteSpiContext), after DiscoMgr started.
        consistenIdValue = TagValue.create("unknown");
    }

    mreg.addMetricRegistryRemoveListener(mreg -> mreg.forEach(metric -> histogramNames.remove(metric.name())));
}
 
Example #7
Source File: TagContextDeserializationTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeserializeNonConsecutiveDuplicateTags()
    throws TagContextDeserializationException {
  ByteArrayDataOutput output = ByteStreams.newDataOutput();
  output.write(BinarySerializationUtils.VERSION_ID);
  encodeTagToOutput("Key1", "Value1", output);
  encodeTagToOutput("Key2", "Value2", output);
  encodeTagToOutput("Key3", "Value3", output);
  encodeTagToOutput("Key1", "Value1", output);
  encodeTagToOutput("Key2", "Value2", output);
  TagContext expected =
      tagger
          .emptyBuilder()
          .put(TagKey.create("Key1"), TagValue.create("Value1"))
          .put(TagKey.create("Key2"), TagValue.create("Value2"))
          .put(TagKey.create("Key3"), TagValue.create("Value3"))
          .build();
  assertThat(serializer.fromByteArray(output.toByteArray())).isEqualTo(expected);
}
 
Example #8
Source File: TagContextDeserializationTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeserializeNonConsecutiveDuplicateKeys()
    throws TagContextDeserializationException {
  ByteArrayDataOutput output = ByteStreams.newDataOutput();
  output.write(BinarySerializationUtils.VERSION_ID);
  encodeTagToOutput("Key1", "Value1", output);
  encodeTagToOutput("Key2", "Value2", output);
  encodeTagToOutput("Key3", "Value3", output);
  encodeTagToOutput("Key1", "Value4", output);
  encodeTagToOutput("Key2", "Value5", output);
  TagContext expected =
      tagger
          .emptyBuilder()
          .put(TagKey.create("Key1"), TagValue.create("Value4"))
          .put(TagKey.create("Key2"), TagValue.create("Value5"))
          .put(TagKey.create("Key3"), TagValue.create("Value3"))
          .build();
  assertThat(serializer.fromByteArray(output.toByteArray())).isEqualTo(expected);
}
 
Example #9
Source File: CensusStatsModule.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Override
public ServerStreamTracer newServerStreamTracer(String fullMethodName, Metadata headers) {
  TagContext parentCtx = headers.get(statsHeader);
  if (parentCtx == null) {
    parentCtx = tagger.empty();
  }
  TagValue methodTag = TagValue.create(fullMethodName);
  parentCtx =
      tagger
          .toBuilder(parentCtx)
          .put(DeprecatedCensusConstants.RPC_METHOD, methodTag)
          .build();
  return new ServerTracer(
      CensusStatsModule.this,
      parentCtx,
      stopwatchSupplier,
      tagger,
      recordStartedRpcs,
      recordFinishedRpcs);
}
 
Example #10
Source File: CensusStatsModule.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
ClientCallTracer(
    CensusStatsModule module,
    TagContext parentCtx,
    String fullMethodName,
    boolean recordStartedRpcs,
    boolean recordFinishedRpcs) {
  this.module = module;
  this.parentCtx = checkNotNull(parentCtx);
  TagValue methodTag = TagValue.create(fullMethodName);
  this.startCtx =
      module.tagger.toBuilder(parentCtx)
      .put(DeprecatedCensusConstants.RPC_METHOD, methodTag)
      .build();
  this.stopwatch = module.stopwatchSupplier.get().start();
  this.recordFinishedRpcs = recordFinishedRpcs;
  if (recordStartedRpcs) {
    module.statsRecorder.newMeasureMap()
        .put(DeprecatedCensusConstants.RPC_CLIENT_STARTED_COUNT, 1)
        .record(startCtx);
  }
}
 
Example #11
Source File: ViewData.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a new {@link ViewData}.
 *
 * @param view the {@link View} associated with this {@link ViewData}.
 * @param map the mapping from {@link TagValue} list to {@link AggregationData}.
 * @param start the start {@link Timestamp} for this {@link ViewData}.
 * @param end the end {@link Timestamp} for this {@link ViewData}.
 * @return a {@code ViewData}.
 * @throws IllegalArgumentException if the types of {@code Aggregation} and {@code
 *     AggregationData} don't match.
 * @since 0.13
 */
public static ViewData create(
    View view,
    Map<? extends List</*@Nullable*/ TagValue>, ? extends AggregationData> map,
    Timestamp start,
    Timestamp end) {
  Map<List</*@Nullable*/ TagValue>, AggregationData> deepCopy =
      new HashMap<List</*@Nullable*/ TagValue>, AggregationData>();
  for (Entry<? extends List</*@Nullable*/ TagValue>, ? extends AggregationData> entry :
      map.entrySet()) {
    checkAggregation(view.getAggregation(), entry.getValue(), view.getMeasure());
    deepCopy.put(
        Collections.unmodifiableList(new ArrayList</*@Nullable*/ TagValue>(entry.getKey())),
        entry.getValue());
  }
  return createInternal(
      view,
      Collections.unmodifiableMap(deepCopy),
      AggregationWindowData.CumulativeData.create(start, end),
      start,
      end);
}
 
Example #12
Source File: MutableViewData.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
ViewData toViewData(Timestamp now, State state) {
  refreshBucketList(now);
  if (state == State.ENABLED) {
    return ViewData.create(
        super.view,
        combineBucketsAndGetAggregationMap(now),
        ViewData.AggregationWindowData.IntervalData.create(now));
  } else {
    // If Stats state is DISABLED, return an empty ViewData.
    return ViewData.create(
        super.view,
        Collections.<List</*@Nullable*/ TagValue>, AggregationData>emptyMap(),
        ViewData.AggregationWindowData.IntervalData.create(ZERO_TIMESTAMP));
  }
}
 
Example #13
Source File: NoopStats.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
@javax.annotation.Nullable
@SuppressWarnings("deprecation")
public ViewData getView(View.Name name) {
  Utils.checkNotNull(name, "name");
  synchronized (registeredViews) {
    View view = registeredViews.get(name);
    if (view == null) {
      return null;
    } else {
      return ViewData.create(
          view,
          Collections.<List</*@Nullable*/ TagValue>, AggregationData>emptyMap(),
          view.getWindow()
              .match(
                  Functions.<ViewData.AggregationWindowData>returnConstant(
                      ViewData.AggregationWindowData.CumulativeData.create(
                          ZERO_TIMESTAMP, ZERO_TIMESTAMP)),
                  Functions.<ViewData.AggregationWindowData>returnConstant(
                      ViewData.AggregationWindowData.IntervalData.create(ZERO_TIMESTAMP)),
                  Functions.<ViewData.AggregationWindowData>throwAssertionError()));
    }
  }
}
 
Example #14
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private static void checkEndTags(
    MetricsRecord record, String methodName, Status.Code status, boolean clientSide) {
  assertNotNull("record is not null", record);

  TagKey methodNameTagKey = clientSide
      ? RpcMeasureConstants.GRPC_CLIENT_METHOD
      : RpcMeasureConstants.GRPC_SERVER_METHOD;
  TagValue methodNameTag = record.tags.get(methodNameTagKey);
  assertNotNull("method name tagged", methodNameTag);
  assertEquals("method names match", methodName, methodNameTag.asString());

  TagKey statusTagKey = clientSide
      ? RpcMeasureConstants.GRPC_CLIENT_STATUS
      : RpcMeasureConstants.GRPC_SERVER_STATUS;
  TagValue statusTag = record.tags.get(statusTagKey);
  assertNotNull("status tagged", statusTag);
  assertEquals(status.toString(), statusTag.asString());
}
 
Example #15
Source File: BinarySerializationUtils.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static Map<TagKey, TagValueWithMetadata> parseTags(ByteBuffer buffer)
    throws TagContextDeserializationException {
  Map<TagKey, TagValueWithMetadata> tags = new HashMap<TagKey, TagValueWithMetadata>();
  int limit = buffer.limit();
  int totalChars = 0; // Here chars are equivalent to bytes, since we're using ascii chars.
  while (buffer.position() < limit) {
    int type = buffer.get();
    if (type == TAG_FIELD_ID) {
      TagKey key = createTagKey(decodeString(buffer));
      TagValue val = createTagValue(key, decodeString(buffer));
      totalChars += key.getName().length();
      totalChars += val.asString().length();
      tags.put(key, TagValueWithMetadata.create(val, METADATA_UNLIMITED_PROPAGATION));
    } else {
      // Stop parsing at the first unknown field ID, since there is no way to know its length.
      // TODO(sebright): Consider storing the rest of the byte array in the TagContext.
      break;
    }
  }
  if (totalChars > TAGCONTEXT_SERIALIZED_SIZE_LIMIT) {
    throw new TagContextDeserializationException(
        "Size of TagContext exceeds the maximum serialized size "
            + TAGCONTEXT_SERIALIZED_SIZE_LIMIT);
  }
  return tags;
}
 
Example #16
Source File: StatszZPageHandler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static void emitViewData(
    /*@Nullable*/ ViewData viewData, View.Name viewName, PrintWriter out, Formatter formatter) {
  if (viewData == null) {
    formatter.format("<p class=\"view\">No Stats found for View %s.</p>", viewName.asString());
    return;
  }
  View view = viewData.getView();
  emitViewInfo(view, viewData.getWindowData(), out, formatter);
  formatter.format("<p class=\"view\">Stats for View: %s</p>", view.getName().asString());

  formatter.format("<table cellspacing=0 cellpadding=0>");
  emitViewDataTableHeader(view, out, formatter);
  for (Entry<List</*@Nullable*/ TagValue>, AggregationData> entry :
      viewData.getAggregationMap().entrySet()) {
    emitViewDataRow(view, entry, out, formatter);
  }
  out.write("</table>");
  out.write("<p></p>");
}
 
Example #17
Source File: IntervalBucketTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRecord() {
  IntervalBucket bucket = new IntervalBucket(START, MINUTE, MEAN, MEASURE_DOUBLE);
  List<TagValue> tagValues1 = Arrays.<TagValue>asList(TagValue.create("VALUE1"));
  List<TagValue> tagValues2 = Arrays.<TagValue>asList(TagValue.create("VALUE2"));
  bucket.record(tagValues1, 5.0, Collections.<String, AttachmentValue>emptyMap(), START);
  bucket.record(tagValues1, 15.0, Collections.<String, AttachmentValue>emptyMap(), START);
  bucket.record(tagValues2, 10.0, Collections.<String, AttachmentValue>emptyMap(), START);
  assertThat(bucket.getTagValueAggregationMap().keySet()).containsExactly(tagValues1, tagValues2);
  MutableMean mutableMean1 = (MutableMean) bucket.getTagValueAggregationMap().get(tagValues1);
  MutableMean mutableMean2 = (MutableMean) bucket.getTagValueAggregationMap().get(tagValues2);
  assertThat(mutableMean1.getSum()).isWithin(TOLERANCE).of(20);
  assertThat(mutableMean2.getSum()).isWithin(TOLERANCE).of(10);
  assertThat(mutableMean1.getCount()).isEqualTo(2);
  assertThat(mutableMean2.getCount()).isEqualTo(1);
}
 
Example #18
Source File: CorrelationContextFormatTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void roundTrip()
    throws TagContextSerializationException, TagContextDeserializationException {
  Tag[] tags = new Tag[40];
  for (int i = 0; i < tags.length; i++) {
    tags[i] =
        Tag.create(
            TagKey.create(generateRandom(10)),
            TagValue.create(generateRandom(10)),
            METADATA_UNLIMITED_PROPAGATION);
  }
  TagContext tagContext = makeTagContext(tags);
  Map<String, String> carrier = new HashMap<String, String>();
  textFormat.inject(tagContext, carrier, setter);
  TagContext actual = textFormat.extract(carrier, getter);
  assertThat(TagsTestUtil.tagContextToList(actual))
      .containsExactlyElementsIn(TagsTestUtil.tagContextToList(tagContext));
}
 
Example #19
Source File: MutableViewData.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static void putBucketsIntoMultiMap(
    ArrayDeque<IntervalBucket> buckets,
    Multimap<List</*@Nullable*/ TagValue>, MutableAggregation> multimap,
    Aggregation aggregation,
    Measure measure,
    Timestamp now) {
  // Put fractional stats of the head (oldest) bucket.
  IntervalBucket head = CheckerFrameworkUtils.castNonNull(buckets.peekFirst());
  IntervalBucket tail = CheckerFrameworkUtils.castNonNull(buckets.peekLast());
  double fractionTail = tail.getFraction(now);
  // TODO(songya): decide what to do when time goes backwards
  checkArgument(
      0.0 <= fractionTail && fractionTail <= 1.0,
      "Fraction " + fractionTail + " should be within [0.0, 1.0].");
  double fractionHead = 1.0 - fractionTail;
  putFractionalMutableAggregationsToMultiMap(
      head.getTagValueAggregationMap(), multimap, aggregation, measure, fractionHead);

  // Put whole data of other buckets.
  boolean shouldSkipFirst = true;
  for (IntervalBucket bucket : buckets) {
    if (shouldSkipFirst) {
      shouldSkipFirst = false;
      continue; // skip the first bucket
    }
    for (Entry<List</*@Nullable*/ TagValue>, MutableAggregation> entry :
        bucket.getTagValueAggregationMap().entrySet()) {
      multimap.put(entry.getKey(), entry.getValue());
    }
  }
}
 
Example #20
Source File: HttpClientHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private void recordStats(HttpRequestContext context, @Nullable Q request, int httpCode) {
  double requestLatency = NANOSECONDS.toMillis(System.nanoTime() - context.requestStartTime);

  String methodStr = request == null ? "" : extractor.getMethod(request);
  String host = request == null ? "null_request" : extractor.getHost(request);

  TagContext startCtx =
      tagger
          .toBuilder(context.tagContext)
          .put(
              HTTP_CLIENT_HOST,
              TagValue.create(host == null ? "null_host" : host),
              METADATA_NO_PROPAGATION)
          .put(
              HTTP_CLIENT_METHOD,
              TagValue.create(methodStr == null ? "" : methodStr),
              METADATA_NO_PROPAGATION)
          .put(
              HTTP_CLIENT_STATUS,
              TagValue.create(httpCode == 0 ? "error" : Integer.toString(httpCode)),
              METADATA_NO_PROPAGATION)
          .build();

  statsRecorder
      .newMeasureMap()
      .put(HTTP_CLIENT_ROUNDTRIP_LATENCY, requestLatency)
      .put(HTTP_CLIENT_SENT_BYTES, context.sentMessageSize.get())
      .put(HTTP_CLIENT_RECEIVED_BYTES, context.receiveMessageSize.get())
      .record(startCtx);
}
 
Example #21
Source File: StatsTestUtils.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public TagContext fromByteArray(byte[] bytes) throws TagContextDeserializationException {
  String serializedString = new String(bytes, UTF_8);
  if (serializedString.startsWith(EXTRA_TAG_HEADER_VALUE_PREFIX)) {
    return tagger.emptyBuilder()
        .putLocal(EXTRA_TAG,
            TagValue.create(serializedString.substring(EXTRA_TAG_HEADER_VALUE_PREFIX.length())))
        .build();
  } else {
    throw new TagContextDeserializationException("Malformed value");
  }
}
 
Example #22
Source File: TagContextDeserializationTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializeMultipleTags() throws TagContextDeserializationException {
  ByteArrayDataOutput output = ByteStreams.newDataOutput();
  output.write(BinarySerializationUtils.VERSION_ID);
  encodeTagToOutput("Key1", "Value1", output);
  encodeTagToOutput("Key2", "Value2", output);
  TagContext expected =
      tagger
          .emptyBuilder()
          .put(TagKey.create("Key1"), TagValue.create("Value1"))
          .put(TagKey.create("Key2"), TagValue.create("Value2"))
          .build();
  assertThat(serializer.fromByteArray(output.toByteArray())).isEqualTo(expected);
}
 
Example #23
Source File: CorrelationContextFormatTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void inject_TooManyTags() throws TagContextSerializationException {
  Tag[] tags = new Tag[CorrelationContextFormat.MAX_NUMBER_OF_TAGS + 1];
  for (int i = 0; i < tags.length; i++) {
    tags[i] =
        Tag.create(
            TagKey.create("k" + i), TagValue.create("v" + i), METADATA_UNLIMITED_PROPAGATION);
  }
  TagContext tagContext = makeTagContext(tags);
  Map<String, String> carrier = new HashMap<String, String>();
  thrown.expect(TagContextSerializationException.class);
  textFormat.inject(tagContext, carrier, setter);
}
 
Example #24
Source File: QuickStart.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** Main launcher for the QuickStart example. */
public static void main(String[] args) throws InterruptedException {
  TagContextBuilder tagContextBuilder =
      tagger.currentBuilder().put(FRONTEND_KEY, TagValue.create("mobile-ios9.3.5"));
  SpanBuilder spanBuilder =
      tracer
          .spanBuilder("my.org/ProcessVideo")
          .setRecordEvents(true)
          .setSampler(Samplers.alwaysSample());
  viewManager.registerView(VIDEO_SIZE_VIEW);
  LoggingTraceExporter.register();

  // Process video.
  // Record the processed video size.
  try (Scope scopedTags = tagContextBuilder.buildScoped();
      Scope scopedSpan = spanBuilder.startScopedSpan()) {
    tracer.getCurrentSpan().addAnnotation("Start processing video.");
    // Sleep for [0,10] milliseconds to fake work.
    Thread.sleep(new Random().nextInt(10) + 1);
    statsRecorder.newMeasureMap().put(VIDEO_SIZE, 25 * MiB).record();
    tracer.getCurrentSpan().addAnnotation("Finished processing video.");
  } catch (Exception e) {
    tracer.getCurrentSpan().addAnnotation("Exception thrown when processing video.");
    tracer.getCurrentSpan().setStatus(Status.UNKNOWN);
    logger.severe(e.getMessage());
  }

  logger.info("Wait longer than the reporting duration...");
  // Wait for a duration longer than reporting duration (5s) to ensure spans are exported.
  // TODO(songya): remove the gap once we add a shutdown hook for exporting unflushed spans.
  Thread.sleep(5100);
  ViewData viewData = viewManager.getView(VIDEO_SIZE_VIEW_NAME);
  logger.info(
      String.format("Recorded stats for %s:\n %s", VIDEO_SIZE_VIEW_NAME.asString(), viewData));
}
 
Example #25
Source File: ViewDataTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void preventAggregationAndAggregationDataMismatch_LastValueDouble_LastValueLong() {
  aggregationAndAggregationDataMismatch(
      createView(LastValue.create(), MEASURE_DOUBLE),
      ImmutableMap.<List<TagValue>, AggregationData>of(
          Arrays.asList(V1, V2), LastValueDataLong.create(100)));
}
 
Example #26
Source File: ViewDataTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void preventAggregationAndAggregationDataMismatch_SumLong_SumDouble() {
  aggregationAndAggregationDataMismatch(
      createView(Sum.create(), MEASURE_LONG),
      ImmutableMap.<List<TagValue>, AggregationData>of(
          Arrays.asList(V1, V2), SumDataDouble.create(100)));
}
 
Example #27
Source File: OpenCensusTest.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess() throws Exception {
  server.enqueue(mockResponse(500, "OK", 100)); // retry 1
  server.enqueue(mockResponse(500, "OK", 100)); // retry 2
  server.enqueue(mockResponse(200, "OK", 300)); // succeed

  GeocodingResult[] result =
      context.get(new ApiConfig("/path"), GeocodingApi.Response.class, "k", "v").await();
  assertEquals(1, result.length);

  List<TagValue> tags =
      Arrays.asList(TagValue.create(""), TagValue.create("200"), TagValue.create("/path"));

  Map.Entry<List<TagValue>, AggregationData> latencyMetric =
      getMetric("maps.googleapis.com/client/request_latency");
  assertNotNull(latencyMetric);
  assertEquals(tags, latencyMetric.getKey());
  AggregationData.DistributionData latencyDist =
      (AggregationData.DistributionData) latencyMetric.getValue();
  assertEquals(1, latencyDist.getCount());
  assertTrue(latencyDist.getMean() > 500);

  Map.Entry<List<TagValue>, AggregationData> retryMetric =
      getMetric("maps.googleapis.com/client/retry_count");
  assertNotNull(retryMetric);
  assertEquals(tags, retryMetric.getKey());
  AggregationData.DistributionData retryDist =
      (AggregationData.DistributionData) retryMetric.getValue();
  assertEquals(1, retryDist.getCount());
  assertEquals(2.0, retryDist.getMean(), 0.1);

  Map.Entry<List<TagValue>, AggregationData> countMetric =
      getMetric("maps.googleapis.com/client/request_count");
  assertNotNull(countMetric);
  assertEquals(tags, countMetric.getKey());
  AggregationData.CountData count = (AggregationData.CountData) countMetric.getValue();
  assertEquals(1, count.getCount());
}
 
Example #28
Source File: ViewData.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static ViewData createInternal(
    View view,
    Map<List</*@Nullable*/ TagValue>, AggregationData> aggregationMap,
    AggregationWindowData window,
    Timestamp start,
    Timestamp end) {
  @SuppressWarnings("nullness")
  Map<List<TagValue>, AggregationData> map = aggregationMap;
  return new AutoValue_ViewData(view, map, window, start, end);
}
 
Example #29
Source File: AbstractInteropTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000)
public void censusContextsPropagated() {
  Assume.assumeTrue("Skip the test because server is not in the same process.", server != null);
  Span clientParentSpan = Tracing.getTracer().spanBuilder("Test.interopTest").startSpan();
  // A valid ID is guaranteed to be unique, so we can verify it is actually propagated.
  assertTrue(clientParentSpan.getContext().getTraceId().isValid());
  Context ctx =
      Context.ROOT.withValues(
          TAG_CONTEXT_KEY,
          tagger.emptyBuilder().put(
              StatsTestUtils.EXTRA_TAG, TagValue.create("extra value")).build(),
          ContextUtils.CONTEXT_SPAN_KEY,
          clientParentSpan);
  Context origCtx = ctx.attach();
  try {
    blockingStub.unaryCall(SimpleRequest.getDefaultInstance());
    Context serverCtx = contextCapture.get();
    assertNotNull(serverCtx);

    FakeTagContext statsCtx = (FakeTagContext) TAG_CONTEXT_KEY.get(serverCtx);
    assertNotNull(statsCtx);
    Map<TagKey, TagValue> tags = statsCtx.getTags();
    boolean tagFound = false;
    for (Map.Entry<TagKey, TagValue> tag : tags.entrySet()) {
      if (tag.getKey().equals(StatsTestUtils.EXTRA_TAG)) {
        assertEquals(TagValue.create("extra value"), tag.getValue());
        tagFound = true;
      }
    }
    assertTrue("tag not found", tagFound);

    Span span = CONTEXT_SPAN_KEY.get(serverCtx);
    assertNotNull(span);
    SpanContext spanContext = span.getContext();
    assertEquals(clientParentSpan.getContext().getTraceId(), spanContext.getTraceId());
  } finally {
    ctx.detach(origCtx);
  }
}
 
Example #30
Source File: CensusStatsModule.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
ClientCallTracer(CensusStatsModule module, TagContext parentCtx, String fullMethodName) {
  this.module = checkNotNull(module);
  this.parentCtx = checkNotNull(parentCtx);
  TagValue methodTag = TagValue.create(fullMethodName);
  this.startCtx = module.tagger.toBuilder(parentCtx)
      .putLocal(RpcMeasureConstants.GRPC_CLIENT_METHOD, methodTag)
      .build();
  this.stopwatch = module.stopwatchSupplier.get().start();
  if (module.recordStartedRpcs) {
    module.statsRecorder.newMeasureMap()
        .put(DeprecatedCensusConstants.RPC_CLIENT_STARTED_COUNT, 1)
        .record(startCtx);
  }
}