Search in sources :

Example 11 with Timestamp

use of io.opencensus.common.Timestamp in project instrumentation-java by census-instrumentation.

the class DatadogExporterHandler method convertToJson.

String convertToJson(Collection<SpanData> spanDataList) {
    final ArrayList<DatadogSpan> datadogSpans = new ArrayList<>();
    for (SpanData sd : spanDataList) {
        SpanContext sc = sd.getContext();
        final long startTime = timestampToNanos(sd.getStartTimestamp());
        final Timestamp endTimestamp = Optional.ofNullable(sd.getEndTimestamp()).orElseGet(() -> Tracing.getClock().now());
        final long endTime = timestampToNanos(endTimestamp);
        final long duration = endTime - startTime;
        final Long parentId = Optional.ofNullable(sd.getParentSpanId()).map(DatadogExporterHandler::convertSpanId).orElse(null);
        final Map<String, AttributeValue> attributes = sd.getAttributes().getAttributeMap();
        final Map<String, String> meta = attributes.isEmpty() ? new HashMap<>() : attributesToMeta(attributes);
        final String resource = meta.getOrDefault("resource", "UNKNOWN");
        final DatadogSpan span = new DatadogSpan(sc.getTraceId().getLowerLong(), convertSpanId(sc.getSpanId()), sd.getName(), resource, this.service, this.type, startTime, duration, parentId, errorCode(sd.getStatus()), meta);
        datadogSpans.add(span);
    }
    final Collection<List<DatadogSpan>> traces = datadogSpans.stream().collect(Collectors.groupingBy(DatadogSpan::getTraceId, Collectors.toList())).values();
    return gson.toJson(traces);
}
Also used : AttributeValue(io.opencensus.trace.AttributeValue) SpanContext(io.opencensus.trace.SpanContext) SpanData(io.opencensus.trace.export.SpanData) ArrayList(java.util.ArrayList) Timestamp(io.opencensus.common.Timestamp) ArrayList(java.util.ArrayList) List(java.util.List)

Example 12 with Timestamp

use of io.opencensus.common.Timestamp in project instrumentation-java by census-instrumentation.

the class JsonConversionUtils method convertToJson.

/**
 * Converts a collection of {@link SpanData} to a Collection of json string.
 *
 * @param appName the name of app to include in traces.
 * @param spanDataList Collection of {@code SpanData} to be converted to json.
 * @return Collection of {@code SpanData} converted to JSON to be indexed.
 */
static List<String> convertToJson(String appName, Collection<SpanData> spanDataList) {
    List<String> spanJson = new ArrayList<String>();
    if (spanDataList == null) {
        return spanJson;
    }
    StringBuilder sb = new StringBuilder();
    for (final SpanData span : spanDataList) {
        final SpanContext spanContext = span.getContext();
        final SpanId parentSpanId = span.getParentSpanId();
        final Timestamp startTimestamp = span.getStartTimestamp();
        final Timestamp endTimestamp = span.getEndTimestamp();
        final Status status = span.getStatus();
        if (endTimestamp == null) {
            continue;
        }
        sb.append('{');
        sb.append("\"appName\":\"").append(appName).append("\",");
        sb.append("\"spanId\":\"").append(encodeSpanId(spanContext.getSpanId())).append("\",");
        sb.append("\"traceId\":\"").append(encodeTraceId(spanContext.getTraceId())).append("\",");
        if (parentSpanId != null) {
            sb.append("\"parentId\":\"").append(encodeSpanId(parentSpanId)).append("\",");
        }
        sb.append("\"timestamp\":").append(toMillis(startTimestamp)).append(',');
        sb.append("\"duration\":").append(toMillis(startTimestamp, endTimestamp)).append(',');
        sb.append("\"name\":\"").append(toSpanName(span)).append("\",");
        sb.append("\"kind\":\"").append(toSpanKind(span)).append("\",");
        sb.append("\"dateStarted\":\"").append(formatDate(startTimestamp)).append("\",");
        sb.append("\"dateEnded\":\"").append(formatDate(endTimestamp)).append('"');
        if (status == null) {
            sb.append(",\"status\":").append("\"ok\"");
        } else if (!status.isOk()) {
            sb.append(",\"error\":").append("true");
        }
        Map<String, AttributeValue> attributeMap = span.getAttributes().getAttributeMap();
        if (attributeMap.size() > 0) {
            StringBuilder builder = new StringBuilder();
            builder.append('{');
            for (Entry<String, AttributeValue> entry : attributeMap.entrySet()) {
                if (builder.length() > 1) {
                    builder.append(',');
                }
                builder.append("\"").append(entry.getKey()).append("\":\"").append(attributeValueToString(entry.getValue())).append("\"");
            }
            builder.append('}');
            sb.append(",\"data\":").append(builder);
        }
        sb.append('}');
        spanJson.add(sb.toString());
    }
    return spanJson;
}
Also used : Status(io.opencensus.trace.Status) AttributeValue(io.opencensus.trace.AttributeValue) SpanContext(io.opencensus.trace.SpanContext) SpanData(io.opencensus.trace.export.SpanData) ArrayList(java.util.ArrayList) Timestamp(io.opencensus.common.Timestamp) SpanId(io.opencensus.trace.SpanId)

Example 13 with Timestamp

use of io.opencensus.common.Timestamp in project instrumentation-java by census-instrumentation.

the class TraceProtoUtils method toSpanProto.

/**
 * Converts {@link SpanData} to {@link Span} proto.
 *
 * @param spanData the {@code SpanData}.
 * @return proto representation of {@code Span}.
 */
static Span toSpanProto(SpanData spanData) {
    SpanContext spanContext = spanData.getContext();
    TraceId traceId = spanContext.getTraceId();
    SpanId spanId = spanContext.getSpanId();
    Span.Builder spanBuilder = Span.newBuilder().setTraceId(toByteString(traceId.getBytes())).setSpanId(toByteString(spanId.getBytes())).setTracestate(toTracestateProto(spanContext.getTracestate())).setName(toTruncatableStringProto(spanData.getName())).setStartTime(toTimestampProto(spanData.getStartTimestamp())).setAttributes(toAttributesProto(spanData.getAttributes())).setTimeEvents(toTimeEventsProto(spanData.getAnnotations(), spanData.getMessageEvents())).setLinks(toLinksProto(spanData.getLinks()));
    Kind kind = spanData.getKind();
    if (kind != null) {
        spanBuilder.setKind(toSpanKindProto(kind));
    }
    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));
    }
    Integer childSpanCount = spanData.getChildSpanCount();
    if (childSpanCount != null) {
        spanBuilder.setChildSpanCount(UInt32Value.newBuilder().setValue(childSpanCount).build());
    }
    Boolean hasRemoteParent = spanData.getHasRemoteParent();
    if (hasRemoteParent != null) {
        spanBuilder.setSameProcessAsParentSpan(BoolValue.of(!hasRemoteParent));
    }
    SpanId parentSpanId = spanData.getParentSpanId();
    if (parentSpanId != null && parentSpanId.isValid()) {
        spanBuilder.setParentSpanId(toByteString(parentSpanId.getBytes()));
    }
    return spanBuilder.build();
}
Also used : SpanContext(io.opencensus.trace.SpanContext) SpanKind(io.opencensus.proto.trace.v1.Span.SpanKind) Kind(io.opencensus.trace.Span.Kind) TraceId(io.opencensus.trace.TraceId) Span(io.opencensus.proto.trace.v1.Span) Timestamp(io.opencensus.common.Timestamp) SpanId(io.opencensus.trace.SpanId)

Example 14 with Timestamp

use of io.opencensus.common.Timestamp in project instrumentation-java by census-instrumentation.

the class DerivedDoubleCumulativeImplTest method withConstantLabels.

@Test
public void withConstantLabels() {
    List<LabelKey> labelKeys = Arrays.asList(LabelKey.create("key1", "desc"), LabelKey.create("key2", "desc"));
    List<LabelValue> labelValues = Arrays.asList(LabelValue.create("value1"), LabelValue.create("value2"));
    LabelKey constantKey = LabelKey.create("constant_key", "desc");
    LabelValue constantValue = LabelValue.create("constant_value");
    Map<LabelKey, LabelValue> constantLabels = Collections.<LabelKey, LabelValue>singletonMap(constantKey, constantValue);
    DerivedDoubleCumulativeImpl derivedDoubleCumulative2 = new DerivedDoubleCumulativeImpl(METRIC_NAME, METRIC_DESCRIPTION, METRIC_UNIT, labelKeys, constantLabels, START_TIME);
    derivedDoubleCumulative2.createTimeSeries(labelValues, new QueueManager(), queueManagerFunction);
    testClock.advanceTime(ONE_MINUTE);
    Timestamp endTime = testClock.now();
    List<LabelKey> allKeys = new ArrayList<>(labelKeys);
    allKeys.add(constantKey);
    MetricDescriptor expectedDescriptor = MetricDescriptor.create(METRIC_NAME, METRIC_DESCRIPTION, METRIC_UNIT, Type.CUMULATIVE_DOUBLE, allKeys);
    List<LabelValue> allValues = new ArrayList<>(labelValues);
    allValues.add(constantValue);
    TimeSeries expectedTimeSeries = TimeSeries.createWithOnePoint(allValues, Point.create(Value.doubleValue(2.5), endTime), START_TIME);
    Metric metric = derivedDoubleCumulative2.getMetric(testClock);
    assertThat(metric).isNotNull();
    assertThat(metric.getMetricDescriptor()).isEqualTo(expectedDescriptor);
    assertThat(metric.getTimeSeriesList()).containsExactly(expectedTimeSeries);
    derivedDoubleCumulative2.removeTimeSeries(labelValues);
    Metric metric2 = derivedDoubleCumulative2.getMetric(testClock);
    assertThat(metric2).isNull();
}
Also used : MetricDescriptor(io.opencensus.metrics.export.MetricDescriptor) TimeSeries(io.opencensus.metrics.export.TimeSeries) LabelValue(io.opencensus.metrics.LabelValue) ArrayList(java.util.ArrayList) LabelKey(io.opencensus.metrics.LabelKey) Metric(io.opencensus.metrics.export.Metric) Timestamp(io.opencensus.common.Timestamp) Test(org.junit.Test)

Example 15 with Timestamp

use of io.opencensus.common.Timestamp in project instrumentation-java by census-instrumentation.

the class DerivedLongCumulativeImplTest method addTimeSeries_IgnoreNegativeValue.

@Test
public void addTimeSeries_IgnoreNegativeValue() {
    derivedLongCumulative.createTimeSeries(LABEL_VALUES, null, negativeLongFunction);
    testClock.advanceTime(ONE_MINUTE);
    Timestamp endTime = testClock.now();
    Metric metric = derivedLongCumulative.getMetric(testClock);
    assertThat(metric).isNotNull();
    assertThat(metric).isEqualTo(Metric.createWithOneTimeSeries(METRIC_DESCRIPTOR, TimeSeries.createWithOnePoint(LABEL_VALUES, Point.create(Value.longValue(0), endTime), START_TIME)));
}
Also used : Metric(io.opencensus.metrics.export.Metric) Timestamp(io.opencensus.common.Timestamp) Test(org.junit.Test)

Aggregations

Timestamp (io.opencensus.common.Timestamp)40 Test (org.junit.Test)29 Metric (io.opencensus.metrics.export.Metric)19 ArrayList (java.util.ArrayList)12 TimeSeries (io.opencensus.metrics.export.TimeSeries)8 SpanContext (io.opencensus.trace.SpanContext)6 DoublePoint (io.opencensus.metrics.DoubleCumulative.DoublePoint)4 LabelKey (io.opencensus.metrics.LabelKey)4 LabelValue (io.opencensus.metrics.LabelValue)4 LongPoint (io.opencensus.metrics.LongCumulative.LongPoint)4 MetricDescriptor (io.opencensus.metrics.export.MetricDescriptor)4 AggregationWindowData (io.opencensus.stats.ViewData.AggregationWindowData)4 View (io.opencensus.stats.View)3 ViewData (io.opencensus.stats.ViewData)3 AttributeValue (io.opencensus.trace.AttributeValue)3 SpanId (io.opencensus.trace.SpanId)3 Status (io.opencensus.trace.Status)3 SpanData (io.opencensus.trace.export.SpanData)3 CurrentState (io.opencensus.implcore.internal.CurrentState)2 CumulativeData (io.opencensus.stats.ViewData.AggregationWindowData.CumulativeData)2