io.opencensus.tags.TagContext Java Examples

The following examples show how to use io.opencensus.tags.TagContext. 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: 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 #2
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 #3
Source File: TagMapImplTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testEquals() {
  new EqualsTester()
      .addEqualityGroup(
          tagger.emptyBuilder().put(K1, V1).put(K2, V2).build(),
          tagger.emptyBuilder().put(K1, V1).put(K2, V2).build(),
          tagger.emptyBuilder().put(K2, V2).put(K1, V1).build(),
          new TagContext() {
            @Override
            protected Iterator<Tag> getIterator() {
              return Lists.<Tag>newArrayList(Tag.create(K1, V1), Tag.create(K2, V2)).iterator();
            }
          })
      .addEqualityGroup(tagger.emptyBuilder().put(K1, V1).put(K2, V1).build())
      .addEqualityGroup(tagger.emptyBuilder().put(K1, V2).put(K2, V1).build())
      .testEquals();
}
 
Example #4
Source File: MeasureToViewMap.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
synchronized void record(TagContext tags, MeasureMapInternal stats, Timestamp timestamp) {
  Iterator<Measurement> iterator = stats.iterator();
  Map<String, AttachmentValue> attachments = stats.getAttachments();
  while (iterator.hasNext()) {
    Measurement measurement = iterator.next();
    Measure measure = measurement.getMeasure();
    if (!measure.equals(registeredMeasures.get(measure.getName()))) {
      // unregistered measures will be ignored.
      continue;
    }
    Collection<MutableViewData> viewDataCollection = mutableMap.get(measure.getName());
    for (MutableViewData viewData : viewDataCollection) {
      viewData.record(
          tags, RecordUtils.getDoubleValueFromMeasurement(measurement), timestamp, attachments);
    }
  }
}
 
Example #5
Source File: ScopedTagMapTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void addToCurrentTagsWithBuilder() {
  TagContext scopedTags = tagger.emptyBuilder().put(KEY_1, VALUE_1).build();
  Scope scope1 = tagger.withTagContext(scopedTags);
  try {
    Scope scope2 = tagger.currentBuilder().put(KEY_2, VALUE_2).buildScoped();
    try {
      assertThat(tagContextToList(tagger.getCurrentTagContext()))
          .containsExactly(Tag.create(KEY_1, VALUE_1), Tag.create(KEY_2, VALUE_2));
    } finally {
      scope2.close();
    }
    assertThat(tagger.getCurrentTagContext()).isSameInstanceAs(scopedTags);
  } finally {
    scope1.close();
  }
}
 
Example #6
Source File: BinarySerializationUtils.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
static byte[] serializeBinary(TagContext tags) throws TagContextSerializationException {
  // Use a ByteArrayDataOutput to avoid needing to handle IOExceptions.
  final ByteArrayDataOutput byteArrayDataOutput = ByteStreams.newDataOutput();
  byteArrayDataOutput.write(VERSION_ID);
  int totalChars = 0; // Here chars are equivalent to bytes, since we're using ascii chars.
  for (Iterator<Tag> i = InternalUtils.getTags(tags); i.hasNext(); ) {
    Tag tag = i.next();
    if (TagTtl.NO_PROPAGATION.equals(tag.getTagMetadata().getTagTtl())) {
      continue;
    }
    totalChars += tag.getKey().getName().length();
    totalChars += tag.getValue().asString().length();
    encodeTag(tag, byteArrayDataOutput);
  }
  if (totalChars > TAGCONTEXT_SERIALIZED_SIZE_LIMIT) {
    throw new TagContextSerializationException(
        "Size of TagContext exceeds the maximum serialized size "
            + TAGCONTEXT_SERIALIZED_SIZE_LIMIT);
  }
  return byteArrayDataOutput.toByteArray();
}
 
Example #7
Source File: GoogleDtpInternalMetricRecorder.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Override
public void exportPageFinished(
    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, 1)
        .put(EXPORT_PAGE_DURATION, duration.toMillis())
        .record();
  }
}
 
Example #8
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 #9
Source File: TaggerImpl.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static TagMapImpl toTagMapImpl(TagContext tags) {
  if (tags instanceof TagMapImpl) {
    return (TagMapImpl) tags;
  } else {
    Iterator<Tag> i = InternalUtils.getTags(tags);
    if (!i.hasNext()) {
      return TagMapImpl.EMPTY;
    }
    TagMapBuilderImpl builder = new TagMapBuilderImpl();
    while (i.hasNext()) {
      Tag tag = i.next();
      if (tag != null) {
        TagContextUtils.addTagToBuilder(tag, builder);
      }
    }
    return builder.build();
  }
}
 
Example #10
Source File: TagContextExample.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Main method.
 *
 * @param args the main arguments.
 */
public static void main(String[] args) {
  System.out.println("Hello Stats World");
  System.out.println("Default Tags: " + tagger.empty());
  System.out.println("Current Tags: " + tagger.getCurrentTagContext());
  TagContext tags1 = tagger.emptyBuilder().put(K1, V1).put(K2, V2).build();
  try (Scope scopedTagCtx1 = tagger.withTagContext(tags1)) {
    System.out.println("  Current Tags: " + tagger.getCurrentTagContext());
    System.out.println(
        "  Current == Default + tags1: " + tagger.getCurrentTagContext().equals(tags1));
    TagContext tags2 = tagger.toBuilder(tags1).put(K3, V3).put(K4, V4).build();
    try (Scope scopedTagCtx2 = tagger.withTagContext(tags2)) {
      System.out.println("    Current Tags: " + tagger.getCurrentTagContext());
      System.out.println(
          "    Current == Default + tags1 + tags2: "
              + tagger.getCurrentTagContext().equals(tags2));
      statsRecorder.newMeasureMap().put(M1, 0.2).put(M2, 0.4).record();
    }
  }
  System.out.println(
      "Current == Default: " + tagger.getCurrentTagContext().equals(tagger.empty()));
}
 
Example #11
Source File: ViewManagerImplTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private void testRecordCumulative(Measure measure, Aggregation aggregation, double... values) {
  View view = createCumulativeView(VIEW_NAME, measure, aggregation, Arrays.asList(KEY));
  clock.setTime(Timestamp.create(1, 2));
  viewManager.registerView(view);
  TagContext tags = tagger.emptyBuilder().put(KEY, VALUE).build();
  for (double val : values) {
    putToMeasureMap(statsRecorder.newMeasureMap(), measure, val).record(tags);
  }
  clock.setTime(Timestamp.create(3, 4));
  ViewData viewData = viewManager.getView(VIEW_NAME);
  assertThat(viewData.getView()).isEqualTo(view);
  assertThat(viewData.getWindowData())
      .isEqualTo(CumulativeData.create(Timestamp.create(1, 2), Timestamp.create(3, 4)));
  StatsTestUtil.assertAggregationMapEquals(
      viewData.getAggregationMap(),
      ImmutableMap.of(
          Arrays.asList(VALUE),
          StatsTestUtil.createAggregationData(aggregation, measure, values)),
      EPSILON);
}
 
Example #12
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void withTagContext_RemoveDuplicatesFromUnknownTagContext() {
  Tag tag1 = Tag.create(K1, V1);
  Tag tag2 = Tag.create(K1, V2);
  TagContext tagContextWithDuplicateTags = new SimpleTagContext(tag1, tag2);
  TagContext result = getResultOfWithTagContext(tagContextWithDuplicateTags);
  assertThat(tagContextToList(result)).containsExactly(tag2);
}
 
Example #13
Source File: CorrelationContextFormatTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void extract_WithUnknownProperties() throws TagContextDeserializationException {
  Map<String, String> carrier =
      Collections.singletonMap(CORRELATION_CONTEXT, "k1=v1;property1=p1;property2=p2,k2=v2");
  Tag expected = Tag.create(K1, TagValue.create("v1"), METADATA_UNLIMITED_PROPAGATION);
  TagContext tagContext = textFormat.extract(carrier, getter);
  assertThat(TagsTestUtil.tagContextToList(tagContext)).containsExactly(expected, T2);
}
 
Example #14
Source File: MutableViewData.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
void record(
    TagContext context,
    double value,
    Timestamp timestamp,
    Map<String, AttachmentValue> attachments) {
  List</*@Nullable*/ TagValue> tagValues =
      getTagValues(getTagMap(context), super.view.getColumns());
  if (!tagValueAggregationMap.containsKey(tagValues)) {
    tagValueAggregationMap.put(
        tagValues,
        createMutableAggregation(super.view.getAggregation(), super.getView().getMeasure()));
  }
  tagValueAggregationMap.get(tagValues).add(value, attachments, timestamp);
}
 
Example #15
Source File: RecordDifferentTagValuesBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private List<TagContext> createContexts(int size) {
  TagContext[] contexts = new TagContext[size];
  for (int i = 0; i < size; i++) {
    contexts[i] =
        tagger
            .emptyBuilder()
            .put(
                TagsBenchmarksUtil.TAG_KEYS.get(0),
                TagsBenchmarksUtil.TAG_VALUES.get(i),
                TagsBenchmarksUtil.UNLIMITED_PROPAGATION)
            .build();
  }
  return Arrays.asList(contexts);
}
 
Example #16
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 #17
Source File: RecordDifferentTagValuesBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static MeasureMap record(Data data, Measure.MeasureLong measure, int value) {
  MeasureMap map = data.recorder.newMeasureMap();
  map.put(measure, value);
  for (TagContext tags : data.contexts) {
    map.record(tags);
  }
  return map;
}
 
Example #18
Source File: RecordDifferentTagValuesBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static MeasureMap record(Data data, Measure.MeasureDouble measure, double value) {
  MeasureMap map = data.recorder.newMeasureMap();
  map.put(measure, value);
  for (TagContext tags : data.contexts) {
    map.record(tags);
  }
  return map;
}
 
Example #19
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 #20
Source File: TagContextDeserializationTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializeOneTag() throws TagContextDeserializationException {
  ByteArrayDataOutput output = ByteStreams.newDataOutput();
  output.write(BinarySerializationUtils.VERSION_ID);
  encodeTagToOutput("Key", "Value", output);
  TagContext expected =
      tagger.emptyBuilder().put(TagKey.create("Key"), TagValue.create("Value")).build();
  assertThat(serializer.fromByteArray(output.toByteArray())).isEqualTo(expected);
}
 
Example #21
Source File: ViewManagerImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private void testRecord_MeasureNotMatch(Measure measure1, Measure measure2, double value) {
  viewManager.registerView(createCumulativeView(VIEW_NAME, measure1, MEAN, Arrays.asList(KEY)));
  TagContext tags = tagger.emptyBuilder().put(KEY, VALUE).build();
  putToMeasureMap(statsRecorder.newMeasureMap(), measure2, value).record(tags);
  ViewData view = viewManager.getView(VIEW_NAME);
  assertThat(view.getAggregationMap()).isEmpty();
}
 
Example #22
Source File: CorrelationContextFormatTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static TagContext makeTagContext(final Tag... tags) {
  return new TagContext() {
    @Override
    public Iterator<Tag> getIterator() {
      return Arrays.<Tag>asList(tags).iterator();
    }
  };
}
 
Example #23
Source File: NoopStats.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
public void record(TagContext tags) {
  Utils.checkNotNull(tags, "tags");

  if (hasUnsupportedValues) {
    // drop all the recorded values
    logger.log(Level.WARNING, "Dropping values, value to record must be non-negative.");
  }
}
 
Example #24
Source File: ScopedTagMapTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void withTagContext() {
  assertThat(tagContextToList(tagger.getCurrentTagContext())).isEmpty();
  TagContext scopedTags = tagger.emptyBuilder().put(KEY_1, VALUE_1).build();
  Scope scope = tagger.withTagContext(scopedTags);
  try {
    assertThat(tagger.getCurrentTagContext()).isSameInstanceAs(scopedTags);
  } finally {
    scope.close();
  }
  assertThat(tagContextToList(tagger.getCurrentTagContext())).isEmpty();
}
 
Example #25
Source File: RecordUtils.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
static Map<TagKey, TagValueWithMetadata> getTagMap(TagContext ctx) {
  if (ctx instanceof TagMapImpl) {
    return ((TagMapImpl) ctx).getTags();
  }
  Map<TagKey, TagValueWithMetadata> tags = Maps.newHashMap();
  for (Iterator<Tag> i = InternalUtils.getTags(ctx); i.hasNext(); ) {
    Tag tag = i.next();
    tags.put(tag.getKey(), TagValueWithMetadata.create(tag.getValue(), tag.getTagMetadata()));
  }
  return tags;
}
 
Example #26
Source File: TaggerImpl.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static TagMapBuilderImpl toTagMapBuilderImpl(TagContext tags) {
  // Copy the tags more efficiently in the expected case, when the TagContext is a TagMapImpl.
  if (tags instanceof TagMapImpl) {
    return new TagMapBuilderImpl(((TagMapImpl) tags).getTags());
  } else {
    TagMapBuilderImpl builder = new TagMapBuilderImpl();
    for (Iterator<Tag> i = InternalUtils.getTags(tags); i.hasNext(); ) {
      Tag tag = i.next();
      if (tag != null) {
        TagContextUtils.addTagToBuilder(tag, builder);
      }
    }
    return builder;
  }
}
 
Example #27
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 #28
Source File: StatsManager.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
void record(TagContext tags, MeasureMapInternal measurementValues) {
  // TODO(songya): consider exposing No-op MeasureMap and use it when stats state is DISABLED, so
  // that we don't need to create actual MeasureMapImpl.
  if (state.getInternal() == State.ENABLED) {
    queue.enqueue(new StatsEvent(this, tags, measurementValues));
  }
}
 
Example #29
Source File: MeasureMapImpl.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
public void record(TagContext tags) {
  if (hasUnsupportedValues) {
    // drop all the recorded values
    logger.log(Level.WARNING, "Dropping values, value to record must be non-negative.");
    return;
  }
  statsManager.record(tags, builder.build());
}
 
Example #30
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getCurrentTagContext_TaggingReenabled() {
  TagContext tags = new SimpleTagContext(TAG1);
  tagsComponent.setState(TaggingState.DISABLED);
  assertThat(tagContextToList(getResultOfGetCurrentTagContext(tags))).isEmpty();
  tagsComponent.setState(TaggingState.ENABLED);
  assertThat(tagContextToList(getResultOfGetCurrentTagContext(tags))).containsExactly(TAG1);
}