io.opencensus.tags.TagContextBuilder Java Examples

The following examples show how to use io.opencensus.tags.TagContextBuilder. 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: TagContextRoundtripTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testRoundtrip_TagContextWithMaximumSize() throws Exception {
  TagContextBuilder builder = tagger.emptyBuilder();
  for (int i = 0; i < BinarySerializationUtils.TAGCONTEXT_SERIALIZED_SIZE_LIMIT / 8; i++) {
    // Each tag will be with format {key : "0123", value : "0123"}, so the length of it is 8.
    // Add 1024 tags, the total size should just be 8192.
    String str;
    if (i < 10) {
      str = "000" + i;
    } else if (i < 100) {
      str = "00" + i;
    } else if (i < 1000) {
      str = "0" + i;
    } else {
      str = "" + i;
    }
    builder.put(TagKey.create(str), TagValue.create(str));
  }
  testRoundtripSerialization(builder.build());
}
 
Example #2
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 #3
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void toBuilder_TaggingReenabled() {
  TagContext tags = new SimpleTagContext(TAG1);
  tagsComponent.setState(TaggingState.DISABLED);
  assertThat(tagger.toBuilder(tags)).isSameInstanceAs(NoopTagMapBuilder.INSTANCE);
  tagsComponent.setState(TaggingState.ENABLED);
  TagContextBuilder builder = tagger.toBuilder(tags);
  assertThat(builder).isInstanceOf(TagMapBuilderImpl.class);
  assertThat(tagContextToList(builder.build())).containsExactly(TAG1);
}
 
Example #4
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void currentBuilder_RemoveDuplicateTags() {
  Tag tag1 = Tag.create(K1, V1);
  Tag tag2 = Tag.create(K1, V2);
  TagContext tagContextWithDuplicateTags = new SimpleTagContext(tag1, tag2);
  TagContextBuilder result = getResultOfCurrentBuilder(tagContextWithDuplicateTags);
  assertThat(tagContextToList(result.build())).containsExactly(tag2);
}
 
Example #5
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void currentBuilder() {
  TagContext tags = new SimpleTagContext(TAG1, TAG2, TAG3);
  TagContextBuilder result = getResultOfCurrentBuilder(tags);
  assertThat(result).isInstanceOf(TagMapBuilderImpl.class);
  assertThat(tagContextToList(result.build())).containsExactly(TAG1, TAG2, TAG3);
}
 
Example #6
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyBuilder_TaggingReenabled() {
  tagsComponent.setState(TaggingState.DISABLED);
  assertThat(tagger.emptyBuilder()).isSameInstanceAs(NoopTagMapBuilder.INSTANCE);
  tagsComponent.setState(TaggingState.ENABLED);
  TagContextBuilder builder = tagger.emptyBuilder();
  assertThat(builder).isInstanceOf(TagMapBuilderImpl.class);
  assertThat(tagContextToList(builder.put(K1, V1).build())).containsExactly(Tag.create(K1, V1));
}
 
Example #7
Source File: TagMapImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void remove_nullKey() {
  TagContext tags = new TagMapImpl(ImmutableMap.of(K1, VM1));
  TagContextBuilder builder = tagger.toBuilder(tags);
  thrown.expect(NullPointerException.class);
  thrown.expectMessage("key");
  builder.remove(null);
}
 
Example #8
Source File: TagMapImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void put_nullValue() {
  TagContext tags = new TagMapImpl(ImmutableMap.of(K1, VM1));
  TagContextBuilder builder = tagger.toBuilder(tags);
  thrown.expect(NullPointerException.class);
  thrown.expectMessage("value");
  builder.put(K2, null);
}
 
Example #9
Source File: TagMapImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void put_nullKey() {
  TagContext tags = new TagMapImpl(ImmutableMap.of(K1, VM1));
  TagContextBuilder builder = tagger.toBuilder(tags);
  thrown.expect(NullPointerException.class);
  thrown.expectMessage("key");
  builder.put(null, V2);
}
 
Example #10
Source File: TagMapBuilderImpl.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
public TagContextBuilder put(TagKey key, TagValue value, TagMetadata tagMetadata) {
  TagValueWithMetadata valueWithMetadata =
      TagValueWithMetadata.create(
          checkNotNull(value, "value"), checkNotNull(tagMetadata, "tagMetadata"));
  tags.put(checkNotNull(key, "key"), valueWithMetadata);
  return this;
}
 
Example #11
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void currentBuilder_TaggingReenabled() {
  TagContext tags = new SimpleTagContext(TAG1);
  tagsComponent.setState(TaggingState.DISABLED);
  assertThat(getResultOfCurrentBuilder(tags)).isSameInstanceAs(NoopTagMapBuilder.INSTANCE);
  tagsComponent.setState(TaggingState.ENABLED);
  TagContextBuilder builder = getResultOfCurrentBuilder(tags);
  assertThat(builder).isInstanceOf(TagMapBuilderImpl.class);
  assertThat(tagContextToList(builder.build())).containsExactly(TAG1);
}
 
Example #12
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private TagContextBuilder getResultOfCurrentBuilder(TagContext tagsToSet) {
  Context orig = ContextUtils.withValue(Context.current(), tagsToSet).attach();
  try {
    return tagger.currentBuilder();
  } finally {
    Context.current().detach(orig);
  }
}
 
Example #13
Source File: OpenCensusMetricExporterSpi.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
private Scope tagScope() {
    TagContextBuilder builder = Tags.getTagger().currentBuilder();

    if (sendInstanceName)
        builder.put(INSTANCE_NAME_TAG, instanceNameValue, METADATA);

    if (sendNodeId)
        builder.put(NODE_ID_TAG, nodeIdValue, METADATA);

    if (sendConsistentId)
        builder.put(CONSISTENT_ID_TAG, consistenIdValue, METADATA);

    return builder.buildScoped();
}
 
Example #14
Source File: TagsBenchmarksUtil.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** Adds 'numTags' tags to 'tagsBuilder' and returns the associated tag context. */
@VisibleForTesting
public static TagContext createTagContext(TagContextBuilder tagsBuilder, int numTags) {
  for (int i = 0; i < numTags; i++) {
    tagsBuilder.put(TAG_KEYS.get(i), TAG_VALUES.get(i), UNLIMITED_PROPAGATION);
  }
  return tagsBuilder.build();
}
 
Example #15
Source File: RecordMultipleViewsBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private TagContext createContext(int size) {
  TagContextBuilder builder = tagger.emptyBuilder();
  for (int i = 0; i < size; i++) {
    builder.put(
        TagsBenchmarksUtil.TAG_KEYS.get(i),
        TagsBenchmarksUtil.TAG_VALUES.get(0),
        TagsBenchmarksUtil.UNLIMITED_PROPAGATION);
  }
  return builder.build();
}
 
Example #16
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 #17
Source File: TelemetryUtils.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("try")
public static void recordTaggedStat(
    TagKey[] keys, String[] values, Measure.MeasureLong md, Long n) {
  TagContextBuilder builder = tagger.emptyBuilder();
  for (int i = 0; i < keys.length; i++) {
    builder.putLocal(keys[i], TagValue.create(values[i]));
  }
  TagContext tctx = builder.build();

  try (Scope ss = tagger.withTagContext(tctx)) {
    statsRecorder.newMeasureMap().put(md, n).record();
  }
}
 
Example #18
Source File: TelemetryUtils.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("try")
public static void recordTaggedStat(
    TagKey[] keys, String[] values, Measure.MeasureDouble md, Double d) {
  TagContextBuilder builder = tagger.emptyBuilder();
  for (int i = 0; i < keys.length; i++) {
    builder.putLocal(keys[i], TagValue.create(values[i]));
  }
  TagContext tctx = builder.build();
  try (Scope ss = tagger.withTagContext(tctx)) {
    statsRecorder.newMeasureMap().put(md, d).record();
  }
}
 
Example #19
Source File: StatsTestUtils.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Override
public TagContextBuilder remove(TagKey key) {
  tagsBuilder.remove(key);
  return this;
}
 
Example #20
Source File: OpenCensusPluginSink.java    From ffwd with Apache License 2.0 4 votes vote down vote up
public void sendMetric(Metric metric) {
  try {
    String metricName = getOutputMetricName(metric);
    MeasureLong measure = measures.get(metricName);

    if (measure == null) {
      if (measures.size() > maxViews) {
        throw new RuntimeException("maxViews exceeded. " +
            "Please increase in configuration or decrease number of metrics.");
      }

      measure = MeasureLong.create("Events", "Number of Events", "1");
      measures.put(metricName, measure);

      // Stackdriver expects each metric to have the same set of tags so metrics
      // missing tags will be rejected. NB by default stackdriver will create
      // the metricDescription based on the first metric received so be consistant
      // from the start.
      final List<TagKey> columns = new ArrayList<TagKey>(metric.getTags().size());
      metric.getTags().keySet().forEach(tagName -> {
          columns.add(TagKey.create(sanitizeName(tagName)));
      });
      final View view =
          View.create(
              Name.create(metricName),
              metricName,
              measure,
              Sum.create(),
              columns);

      Stats.getViewManager().registerView(view);
    }
    final TagContextBuilder builder = tagger.emptyBuilder();
    metric.getTags().forEach((k, v) -> {
        builder.putPropagating(TagKey.create(sanitizeName(k)), TagValue.create(v));
    });
    final TagContext context = builder.build();

    statsRecorder.newMeasureMap().put(measure, (long) metric.getValue()).record(context);
  } catch (Exception ex) {
    log.error("Couldn't send metric %s", ex);
    throw ex;
  }
}
 
Example #21
Source File: StatsTestUtils.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Override
public TagContextBuilder emptyBuilder() {
  return new FakeTagContextBuilder(ImmutableMap.<TagKey, TagValue>of());
}
 
Example #22
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void currentBuilder_SkipNullTag() {
  TagContext tagContextWithNullTag = new SimpleTagContext(TAG1, null, TAG2);
  TagContextBuilder result = getResultOfCurrentBuilder(tagContextWithNullTag);
  assertThat(tagContextToList(result.build())).containsExactly(TAG1, TAG2);
}
 
Example #23
Source File: StatsTestUtils.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Override
public TagContextBuilder currentBuilder() {
  throw new UnsupportedOperationException();
}
 
Example #24
Source File: StatsTestUtils.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public TagContextBuilder put(TagKey key, TagValue value) {
  tagsBuilder.put(key, value);
  return this;
}
 
Example #25
Source File: StatsTestUtils.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Override
public TagContextBuilder emptyBuilder() {
  return new FakeTagContextBuilder(ImmutableMap.<TagKey, TagValue>of());
}
 
Example #26
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void currentBuilder_DefaultIsEmpty() {
  TagContextBuilder currentBuilder = tagger.currentBuilder();
  assertThat(currentBuilder).isInstanceOf(TagMapBuilderImpl.class);
  assertThat(tagContextToList(currentBuilder.build())).isEmpty();
}
 
Example #27
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void emptyBuilder() {
  TagContextBuilder builder = tagger.emptyBuilder();
  assertThat(builder).isInstanceOf(TagMapBuilderImpl.class);
  assertThat(tagContextToList(builder.build())).isEmpty();
}
 
Example #28
Source File: NoopTagMapBuilder.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Override
public TagContextBuilder remove(TagKey key) {
  return this;
}
 
Example #29
Source File: NoopTagMapBuilder.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Override
public TagContextBuilder put(TagKey key, TagValue value, TagMetadata tagMetadata) {
  return this;
}
 
Example #30
Source File: NoopTagMapBuilder.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public TagContextBuilder put(TagKey key, TagValue value) {
  return this;
}