io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener#io.opencensus.tags.TagContext源码实例Demo

下面列出了io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener#io.opencensus.tags.TagContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: opencensus-java   文件: ScopedTagMapTest.java
@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();
  }
}
 
@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();
  }
}
 
@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();
  }
}
 
@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));
}
 
源代码5 项目: opencensus-java   文件: ViewManagerImplTest.java
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);
}
 
源代码6 项目: opencensus-java   文件: TagContextExample.java
/**
 * 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()));
}
 
源代码7 项目: opencensus-java   文件: TagMapImplTest.java
@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();
}
 
@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);
}
 
源代码9 项目: opencensus-java   文件: MeasureToViewMap.java
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);
    }
  }
}
 
源代码10 项目: opencensus-java   文件: TaggerImpl.java
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();
  }
}
 
源代码11 项目: opencensus-java   文件: BinarySerializationUtils.java
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();
}
 
源代码12 项目: grpc-nebula-java   文件: StatsTestUtils.java
@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()
        .put(EXTRA_TAG,
            TagValue.create(serializedString.substring(EXTRA_TAG_HEADER_VALUE_PREFIX.length())))
        .build();
  } else {
    throw new TagContextDeserializationException("Malformed value");
  }
}
 
源代码13 项目: grpc-nebula-java   文件: StatsTestUtils.java
@Override
public byte[] toByteArray(TagContext tags) {
  TagValue extraTagValue = getTags(tags).get(EXTRA_TAG);
  if (extraTagValue == null) {
    throw new UnsupportedOperationException("TagContext must contain EXTRA_TAG");
  }
  return (EXTRA_TAG_HEADER_VALUE_PREFIX + extraTagValue.asString()).getBytes(UTF_8);
}
 
源代码14 项目: opencensus-java   文件: TaggerImplTest.java
@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);
}
 
源代码15 项目: opencensus-java   文件: TaggerImplTest.java
@Test
public void toBuilder_ConvertUnknownTagContextToTagMapImpl() {
  TagContext unknownTagContext = new SimpleTagContext(TAG1, TAG2, TAG3);
  TagContext newTagContext = tagger.toBuilder(unknownTagContext).build();
  assertThat(tagContextToList(newTagContext)).containsExactly(TAG1, TAG2, TAG3);
  assertThat(newTagContext).isInstanceOf(TagMapImpl.class);
}
 
源代码16 项目: opencensus-java   文件: ViewManagerImplTest.java
private void testMultipleViews_DifferentMeasures(
    Measure measure1, Measure measure2, double value1, double value2) {
  final View view1 = createCumulativeView(VIEW_NAME, measure1, DISTRIBUTION, Arrays.asList(KEY));
  final View view2 =
      createCumulativeView(VIEW_NAME_2, measure2, DISTRIBUTION, Arrays.asList(KEY));
  clock.setTime(Timestamp.create(1, 0));
  viewManager.registerView(view1);
  clock.setTime(Timestamp.create(2, 0));
  viewManager.registerView(view2);
  TagContext tags = tagger.emptyBuilder().put(KEY, VALUE).build();
  MeasureMap measureMap = statsRecorder.newMeasureMap();
  putToMeasureMap(measureMap, measure1, value1);
  putToMeasureMap(measureMap, measure2, value2);
  measureMap.record(tags);
  clock.setTime(Timestamp.create(3, 0));
  ViewData viewData1 = viewManager.getView(VIEW_NAME);
  clock.setTime(Timestamp.create(4, 0));
  ViewData viewData2 = viewManager.getView(VIEW_NAME_2);
  assertThat(viewData1.getWindowData())
      .isEqualTo(CumulativeData.create(Timestamp.create(1, 0), Timestamp.create(3, 0)));
  StatsTestUtil.assertAggregationMapEquals(
      viewData1.getAggregationMap(),
      ImmutableMap.of(
          Arrays.asList(VALUE),
          StatsTestUtil.createAggregationData(DISTRIBUTION, measure1, value1)),
      EPSILON);
  assertThat(viewData2.getWindowData())
      .isEqualTo(CumulativeData.create(Timestamp.create(2, 0), Timestamp.create(4, 0)));
  StatsTestUtil.assertAggregationMapEquals(
      viewData2.getAggregationMap(),
      ImmutableMap.of(
          Arrays.asList(VALUE),
          StatsTestUtil.createAggregationData(DISTRIBUTION, measure2, value2)),
      EPSILON);
}
 
源代码17 项目: grpc-nebula-java   文件: CensusStatsModule.java
/**
 * Creates a {@link ClientCallTracer} for a new call.
 */
@VisibleForTesting
ClientCallTracer newClientCallTracer(
    TagContext parentCtx, String fullMethodName,
    boolean recordStartedRpcs, boolean recordFinishedRpcs) {
  return new ClientCallTracer(
      this, parentCtx, fullMethodName, recordStartedRpcs, recordFinishedRpcs);
}
 
源代码18 项目: opencensus-java   文件: TaggerImplTest.java
private TagContext getResultOfWithTagContext(TagContext tagsToSet) {
  Scope scope = tagger.withTagContext(tagsToSet);
  try {
    return ContextUtils.getValue(Context.current());
  } finally {
    scope.close();
  }
}
 
源代码19 项目: opencensus-java   文件: JaxrsClientFilterTest.java
static HttpRequestContext createHttpRequestContext(Span span, TagContext tagContext)
    throws Exception {
  Constructor<HttpRequestContext> constructor =
      HttpRequestContext.class.getDeclaredConstructor(Span.class, TagContext.class);
  constructor.setAccessible(true);
  return constructor.newInstance(span, tagContext);
}
 
源代码20 项目: firebase-android-sdk   文件: StackdriverMetrics.java
/** Records failure of the execution stage named {@code name}. */
public void measureFailure(Task task) {

  TagContext ctx =
      Tags.getTagger()
          .toBuilder(globalContext)
          .put(STAGE, TagValue.create(task.getName()))
          .put(GRADLE_PROJECT, TagValue.create(task.getProject().getPath()))
          .build();
  Stats.getStatsRecorder().newMeasureMap().put(M_SUCCESS, 0).record(ctx);
}
 
源代码21 项目: firebase-android-sdk   文件: StackdriverMetrics.java
/** Extract opencensus context(if any) from environment. */
private static TagContext deserializeContext() {
  String serializedContext = System.getenv("OPENCENSUS_STATS_CONTEXT");
  if (serializedContext == null) {
    return Tags.getTagger().empty();
  }

  TagContextBinarySerializer serializer = Tags.getTagPropagationComponent().getBinarySerializer();

  try {
    return serializer.fromByteArray(Base64.getDecoder().decode(serializedContext));
  } catch (TagContextDeserializationException e) {
    return Tags.getTagger().empty();
  }
}
 
@Override
public void startedJob(String dataType, String exportService, String importService) {
  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)
      .build();
  try (Scope ss = tagger.withTagContext(tctx)) {
    STATS_RECORDER.newMeasureMap().put(JOB_STARTED, 1).record();
  }
}
 
源代码23 项目: opencensus-java   文件: ViewManagerImplTest.java
@Test
public void getViewDoesNotClearStats() {
  View view = createCumulativeView(VIEW_NAME, MEASURE_DOUBLE, DISTRIBUTION, Arrays.asList(KEY));
  clock.setTime(Timestamp.create(10, 0));
  viewManager.registerView(view);
  TagContext tags = tagger.emptyBuilder().put(KEY, VALUE).build();
  statsRecorder.newMeasureMap().put(MEASURE_DOUBLE, 0.1).record(tags);
  clock.setTime(Timestamp.create(11, 0));
  ViewData viewData1 = viewManager.getView(VIEW_NAME);
  assertThat(viewData1.getWindowData())
      .isEqualTo(CumulativeData.create(Timestamp.create(10, 0), Timestamp.create(11, 0)));
  StatsTestUtil.assertAggregationMapEquals(
      viewData1.getAggregationMap(),
      ImmutableMap.of(
          Arrays.asList(VALUE),
          StatsTestUtil.createAggregationData(DISTRIBUTION, MEASURE_DOUBLE, 0.1)),
      EPSILON);

  statsRecorder.newMeasureMap().put(MEASURE_DOUBLE, 0.2).record(tags);
  clock.setTime(Timestamp.create(12, 0));
  ViewData viewData2 = viewManager.getView(VIEW_NAME);

  // The second view should have the same start time as the first view, and it should include both
  // recorded values:
  assertThat(viewData2.getWindowData())
      .isEqualTo(CumulativeData.create(Timestamp.create(10, 0), Timestamp.create(12, 0)));
  StatsTestUtil.assertAggregationMapEquals(
      viewData2.getAggregationMap(),
      ImmutableMap.of(
          Arrays.asList(VALUE),
          StatsTestUtil.createAggregationData(DISTRIBUTION, MEASURE_DOUBLE, 0.1, 0.2)),
      EPSILON);
}
 
@Override
public void recordGenericMetric(String dataType, String service, String tag, boolean bool) {
  TagContext tctx = tagger.emptyBuilder()
      .put(KEY_DATA_TYPE, TagValue.create(dataType), TAG_METADATA)
      .put(KEY_GENERIC_SERVICE, TagValue.create(service), TAG_METADATA)
      .put(KEY_GENERIC_TAG, TagValue.create(tag), TAG_METADATA)
      .put(KEY_GENERIC_BOOL, TagValue.create(Boolean.toString(bool)), TAG_METADATA)
      .build();
  try (Scope ss = tagger.withTagContext(tctx)) {
    STATS_RECORDER.newMeasureMap()
        .put(GENERIC_BOOLEAN, 1)
        .record();
  }
}
 
@Override
public void recordGenericMetric(String dataType, String service, String tag, Duration duration) {
  TagContext tctx = tagger.emptyBuilder()
      .put(KEY_DATA_TYPE, TagValue.create(dataType), TAG_METADATA)
      .put(KEY_GENERIC_SERVICE, TagValue.create(service), TAG_METADATA)
      .put(KEY_GENERIC_TAG, TagValue.create(tag), TAG_METADATA)
      .build();
  try (Scope ss = tagger.withTagContext(tctx)) {
    STATS_RECORDER.newMeasureMap()
        .put(GENERIC_DURATION, duration.toMillis())
        .record();
  }
}
 
@Override
public void recordGenericMetric(String dataType, String service, String tag, int value) {
  TagContext tctx = tagger.emptyBuilder()
      .put(KEY_DATA_TYPE, TagValue.create(dataType), TAG_METADATA)
      .put(KEY_GENERIC_SERVICE, TagValue.create(service), TAG_METADATA)
      .put(KEY_GENERIC_TAG, TagValue.create(tag), TAG_METADATA)
      .build();
  try (Scope ss = tagger.withTagContext(tctx)) {
    STATS_RECORDER.newMeasureMap()
        .put(GENERIC_COUNT, value)
        .record();
  }
}
 
源代码27 项目: meghanada-server   文件: TelemetryUtils.java
@SuppressWarnings("try")
public static void recordStat(Measure.MeasureLong ml, Long n) {
  TagContext tctx = tagger.emptyBuilder().build();
  try (Scope ss = tagger.withTagContext(tctx)) {
    statsRecorder.newMeasureMap().put(ml, n).record();
  }
}
 
源代码28 项目: meghanada-server   文件: TelemetryUtils.java
@SuppressWarnings("try")
public static void recordTaggedStat(TagKey key, String value, Measure.MeasureLong ml, Long n) {
  TagContext tctx = tagger.emptyBuilder().putLocal(key, TagValue.create(value)).build();
  try (Scope ss = tagger.withTagContext(tctx)) {
    statsRecorder.newMeasureMap().put(ml, n).record();
  }
}
 
源代码29 项目: meghanada-server   文件: TelemetryUtils.java
@SuppressWarnings("try")
public static void recordTaggedStat(
    TagKey key, String value, Measure.MeasureDouble md, Double d) {
  TagContext tctx = tagger.emptyBuilder().putLocal(key, TagValue.create(value)).build();
  try (Scope ss = tagger.withTagContext(tctx)) {
    statsRecorder.newMeasureMap().put(md, d).record();
  }
}
 
源代码30 项目: meghanada-server   文件: TelemetryUtils.java
@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();
  }
}