com.google.devtools.cloudtrace.v2.Span Java Examples

The following examples show how to use com.google.devtools.cloudtrace.v2.Span. 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: StackdriverTraceAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncReporterHealthCheck() {
	Sender senderMock = mock(Sender.class);
	when(senderMock.check()).thenReturn(CheckResult.failed(new RuntimeException()));
	when(senderMock.encoding()).thenReturn(SpanBytesEncoder.PROTO3.encoding());

	this.contextRunner
			.withBean(
					StackdriverTraceAutoConfiguration.SENDER_BEAN_NAME,
					Sender.class,
					() -> senderMock)
			.run(context -> {
				Reporter<Span> asyncReporter = context.getBean(Reporter.class);
				assertThat(asyncReporter).isNotNull();
				verify(senderMock, times(1)).check();
			});
}
 
Example #2
Source File: StackdriverV2ExporterHandler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
public void export(Collection<SpanData> spanDataList) {
  // Start a new span with explicit 1/10000 sampling probability to avoid the case when user
  // sets the default sampler to always sample and we get the gRPC span of the stackdriver
  // export call always sampled and go to an infinite loop.
  io.opencensus.trace.Span span =
      tracer
          .spanBuilder(EXPORT_STACKDRIVER_TRACES)
          .setSampler(probabilitySampler)
          .setRecordEvents(true)
          .startSpan();
  Scope scope = tracer.withSpan(span);
  try {
    List<Span> spans = new ArrayList<>(spanDataList.size());
    for (SpanData spanData : spanDataList) {
      spans.add(generateSpan(spanData, RESOURCE_LABELS, fixedAttributes));
    }
    // Sync call because it is already called for a batch of data, and on a separate thread.
    // TODO(bdrutu): Consider to make this async in the future.
    traceServiceClient.batchWriteSpans(projectName, spans);
  } finally {
    scope.close();
    span.end(END_SPAN_OPTIONS);
  }
}
 
Example #3
Source File: StackdriverV2ExporterHandlerProtoTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void generateSpan_WithResourceLabels() {
  SpanData spanData =
      SpanData.create(
          spanContext,
          parentSpanId,
          /* hasRemoteParent= */ true,
          SPAN_NAME,
          null,
          startTimestamp,
          attributes,
          annotations,
          messageEvents,
          links,
          CHILD_SPAN_COUNT,
          status,
          endTimestamp);
  Span span =
      handler.generateSpan(
          spanData, EXPECTED_RESOURCE_ATTRIBUTES, Collections.<String, AttributeValue>emptyMap());
  Map<String, AttributeValue> attributeMap = span.getAttributes().getAttributeMapMap();
  assertThat(attributeMap.entrySet())
      .containsAtLeastElementsIn(EXPECTED_RESOURCE_ATTRIBUTES.entrySet());
}
 
Example #4
Source File: StackdriverSender.java    From zipkin-gcp with Apache License 2.0 6 votes vote down vote up
StackdriverSender(Builder builder) {
  channel = builder.channel;
  callOptions = builder.callOptions;
  projectName = ByteString.copyFromUtf8("projects/" + builder.projectId);
  serverResponseTimeoutMs = builder.serverResponseTimeoutMs;
  traceIdPrefix = projectName.concat(ByteString.copyFromUtf8("/traces/"));
  shutdownChannelOnClose = builder.shutdownChannelOnClose;
  projectNameFieldSize = CodedOutputStream.computeBytesSize(1, projectName);

  // The size of the contents of the Span.name field, used to preallocate the correct sized
  // buffer when computing Span.name.
  spanNameSize = traceIdPrefix.size() + 32 + SPAN_ID_PREFIX.size() + 16;

  spanNameFieldSize = CodedOutputStream.computeTagSize(1)
      + CodedOutputStream.computeUInt32SizeNoTag(spanNameSize) + spanNameSize;

  BatchWriteSpansRequest healthcheckRequest = BatchWriteSpansRequest.newBuilder()
      .setNameBytes(projectName)
      .addSpans(Span.newBuilder().build())
      .build();
  healthcheckCall = new BatchWriteSpansCall(healthcheckRequest);
}
 
Example #5
Source File: StackdriverV2ExporterHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static Span.TimeEvents toTimeEventsProto(
    TimedEvents<Annotation> annotationTimedEvents,
    TimedEvents<io.opencensus.trace.MessageEvent> messageEventTimedEvents) {
  Span.TimeEvents.Builder timeEventsBuilder = Span.TimeEvents.newBuilder();
  timeEventsBuilder.setDroppedAnnotationsCount(annotationTimedEvents.getDroppedEventsCount());
  for (TimedEvent<Annotation> annotation : annotationTimedEvents.getEvents()) {
    timeEventsBuilder.addTimeEvent(toTimeAnnotationProto(annotation));
  }
  timeEventsBuilder.setDroppedMessageEventsCount(messageEventTimedEvents.getDroppedEventsCount());
  for (TimedEvent<io.opencensus.trace.MessageEvent> networkEvent :
      messageEventTimedEvents.getEvents()) {
    timeEventsBuilder.addTimeEvent(toTimeMessageEventProto(networkEvent));
  }
  return timeEventsBuilder.build();
}
 
Example #6
Source File: StackdriverV2ExporterHandlerProtoTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void addFixedAttributes() {
  final ImmutableMap<String, AttributeValue> fixedAttributes =
      ImmutableMap.of(
          "string_attr_key",
          toStringAttributeValueProto("my-project"),
          "long_attr_key",
          AttributeValue.newBuilder().setIntValue(1234).build(),
          "bool_attr_key",
          AttributeValue.newBuilder().setBoolValue(true).build());

  SpanData spanData =
      SpanData.create(
          spanContext,
          parentSpanId,
          /* hasRemoteParent= */ true,
          "Sent." + SPAN_NAME,
          Kind.CLIENT,
          startTimestamp,
          attributes,
          annotations,
          messageEvents,
          links,
          CHILD_SPAN_COUNT,
          status,
          endTimestamp);

  Span span = handler.generateSpan(spanData, EMPTY_RESOURCE_LABELS, fixedAttributes);
  Map<String, AttributeValue> attributeMap = span.getAttributes().getAttributeMapMap();
  assertThat(attributeMap.entrySet()).containsAtLeastElementsIn(fixedAttributes.entrySet());
}
 
Example #7
Source File: StackdriverMockServer.java    From zipkin-gcp with Apache License 2.0 5 votes vote down vote up
@Override
public void batchWriteSpans(BatchWriteSpansRequest request,
    StreamObserver<Empty> responseObserver) {
  final List<Span> spansList = request.getSpansList();
  for (Span span : spansList) {
    spanIds.add(span.getSpanId());
    spanCountdown.countDown();
  }
  responseObserver.onNext(Empty.getDefaultInstance());
  responseObserver.onCompleted();
}
 
Example #8
Source File: StackdriverSender.java    From zipkin-gcp with Apache License 2.0 5 votes vote down vote up
static Span parseTraceIdPrefixedSpan(
    byte[] traceIdPrefixedSpan, int spanNameSize, ByteString traceIdPrefix) {
  // start parsing after the trace ID
  int off = 32, len = traceIdPrefixedSpan.length - off;
  Span.Builder span = Span.newBuilder();
  try {
    span.mergeFrom(traceIdPrefixedSpan, off, len);
  } catch (IOException e) {
    throw new AssertionError(e);
  }

  int offset = 0;

  // Span name in Stackdriver is the global unique identifier of the span, including project ID,
  // trace ID, and span ID. It is _not_ the same as the name in Zipkin which is the semantic name.
  byte[] spanName = new byte[spanNameSize];
  traceIdPrefix.copyTo(spanName, offset);
  offset += traceIdPrefix.size();
  System.arraycopy(traceIdPrefixedSpan, 0, spanName, offset, 32);
  offset += 32;
  SPAN_ID_PREFIX.copyTo(spanName, offset);
  offset += SPAN_ID_PREFIX.size();
  span.getSpanIdBytes().copyTo(spanName, offset);

  span.setNameBytes(UnsafeByteOperations.unsafeWrap(spanName));
  return span.build();
}
 
Example #9
Source File: StackdriverTraceAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Test
public void supportsMultipleReporters() {
	this.contextRunner
			.withUserConfiguration(MultipleReportersConfig.class)
			.run((context) -> {
		SleuthProperties sleuthProperties = context.getBean(SleuthProperties.class);
		assertThat(sleuthProperties.isTraceId128()).isTrue();
		assertThat(sleuthProperties.isSupportsJoin()).isFalse();
		assertThat(context.getBean(HttpClientParser.class)).isNotNull();
		assertThat(context.getBean(HttpServerParser.class)).isNotNull();
		assertThat(context.getBean(ManagedChannel.class)).isNotNull();
		assertThat(context.getBeansOfType(Sender.class)).hasSize(2);
		assertThat(context.getBeansOfType(Sender.class)).containsKeys("stackdriverSender",
				"otherSender");
		assertThat(context.getBeansOfType(Reporter.class)).hasSize(2);
		assertThat(context.getBeansOfType(Reporter.class)).containsKeys("stackdriverReporter",
				"otherReporter");

		brave.Span span = context.getBean(Tracing.class).tracer().nextSpan().name("foo")
				.tag("foo", "bar").start();
		span.finish();
		String spanId = span.context().spanIdString();

		MultipleReportersConfig.GcpTraceService gcpTraceService
				= context.getBean(MultipleReportersConfig.GcpTraceService.class);
		await().atMost(10, TimeUnit.SECONDS)
				.pollInterval(Duration.ONE_SECOND)
				.untilAsserted(() -> {
					assertThat(gcpTraceService.hasSpan(spanId)).isTrue();

					Span traceSpan = gcpTraceService.getSpan(spanId);
					assertThat(traceSpan.getDisplayName().getValue()).isEqualTo("foo");
					assertThat(traceSpan.getAttributes().getAttributeMapMap()).containsKey("foo");
					assertThat(traceSpan.getAttributes().getAttributeMapMap().get("foo").getStringValue().getValue())
							.isEqualTo("bar");
				});

		MultipleReportersConfig.OtherSender sender
				= (MultipleReportersConfig.OtherSender) context.getBean("otherSender");
		await().atMost(10, TimeUnit.SECONDS)
				.untilAsserted(() -> assertThat(sender.isSpanSent()).isTrue());
	});
}
 
Example #10
Source File: StackdriverTraceAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
@Bean
Reporter<zipkin2.Span> otherReporter(OtherSender otherSender) {
	return AsyncReporter.create(otherSender);
}
 
Example #11
Source File: StackdriverTraceAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 4 votes vote down vote up
Span getSpan(String spanId) {
	return this.traces.get(spanId);
}
 
Example #12
Source File: StackdriverV2ExporterHandler.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
Span generateSpan(
    SpanData spanData,
    Map<String, AttributeValue> resourceLabels,
    Map<String, AttributeValue> fixedAttributes) {
  SpanContext context = spanData.getContext();
  final String spanIdHex = context.getSpanId().toLowerBase16();
  SpanName spanName =
      SpanName.newBuilder()
          .setProject(projectId)
          .setTrace(context.getTraceId().toLowerBase16())
          .setSpan(spanIdHex)
          .build();
  Span.Builder spanBuilder =
      Span.newBuilder()
          .setName(spanName.toString())
          .setSpanId(spanIdHex)
          .setDisplayName(
              toTruncatableStringProto(toDisplayName(spanData.getName(), spanData.getKind())))
          .setStartTime(toTimestampProto(spanData.getStartTimestamp()))
          .setAttributes(
              toAttributesProto(spanData.getAttributes(), resourceLabels, fixedAttributes))
          .setTimeEvents(
              toTimeEventsProto(spanData.getAnnotations(), spanData.getMessageEvents()));
  io.opencensus.trace.Status status = spanData.getStatus();
  if (status != null) {
    spanBuilder.setStatus(toStatusProto(status));
  }
  Timestamp end = spanData.getEndTimestamp();
  if (end != null) {
    spanBuilder.setEndTime(toTimestampProto(end));
  }
  spanBuilder.setLinks(toLinksProto(spanData.getLinks()));
  Integer childSpanCount = spanData.getChildSpanCount();
  if (childSpanCount != null) {
    spanBuilder.setChildSpanCount(Int32Value.newBuilder().setValue(childSpanCount).build());
  }
  if (spanData.getParentSpanId() != null && spanData.getParentSpanId().isValid()) {
    spanBuilder.setParentSpanId(spanData.getParentSpanId().toLowerBase16());
  }
  /*@Nullable*/ Boolean hasRemoteParent = spanData.getHasRemoteParent();
  if (hasRemoteParent != null) {
    spanBuilder.setSameProcessAsParentSpan(BoolValue.of(!hasRemoteParent));
  }
  return spanBuilder.build();
}
 
Example #13
Source File: StackdriverV2ExporterHandlerProtoTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void mapHttpAttributes() {
  Map<String, io.opencensus.trace.AttributeValue> attributesMap =
      new HashMap<String, io.opencensus.trace.AttributeValue>();

  attributesMap.put("http.host", io.opencensus.trace.AttributeValue.stringAttributeValue("host"));
  attributesMap.put(
      "http.method", io.opencensus.trace.AttributeValue.stringAttributeValue("method"));
  attributesMap.put("http.path", io.opencensus.trace.AttributeValue.stringAttributeValue("path"));
  attributesMap.put(
      "http.route", io.opencensus.trace.AttributeValue.stringAttributeValue("route"));
  attributesMap.put(
      "http.user_agent", io.opencensus.trace.AttributeValue.stringAttributeValue("user_agent"));
  attributesMap.put(
      "http.status_code", io.opencensus.trace.AttributeValue.longAttributeValue(200L));
  SpanData.Attributes httpAttributes = SpanData.Attributes.create(attributesMap, 0);

  SpanData spanData =
      SpanData.create(
          spanContext,
          parentSpanId,
          /* hasRemoteParent= */ true,
          SPAN_NAME,
          null,
          startTimestamp,
          httpAttributes,
          annotations,
          messageEvents,
          links,
          CHILD_SPAN_COUNT,
          status,
          endTimestamp);

  Span span =
      handler.generateSpan(
          spanData, EMPTY_RESOURCE_LABELS, Collections.<String, AttributeValue>emptyMap());
  Map<String, AttributeValue> attributes = span.getAttributes().getAttributeMapMap();

  assertThat(attributes).containsEntry("/http/host", toStringAttributeValueProto("host"));
  assertThat(attributes).containsEntry("/http/method", toStringAttributeValueProto("method"));
  assertThat(attributes).containsEntry("/http/path", toStringAttributeValueProto("path"));
  assertThat(attributes).containsEntry("/http/route", toStringAttributeValueProto("route"));
  assertThat(attributes)
      .containsEntry("/http/user_agent", toStringAttributeValueProto("user_agent"));
  assertThat(attributes)
      .containsEntry("/http/status_code", AttributeValue.newBuilder().setIntValue(200L).build());
}