Search in sources :

Example 1 with Status

use of io.opencensus.trace.Status 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 2 with Status

use of io.opencensus.trace.Status in project instrumentation-java by census-instrumentation.

the class HttpTraceUtilTest method parseResponseStatus.

private static void parseResponseStatus(int code, CanonicalCode expectedCanonicalCode, String expectedDesc) {
    Status status = HttpTraceUtil.parseResponseStatus(code, null);
    assertThat(status.getCanonicalCode()).isEqualTo(expectedCanonicalCode);
    assertThat(status.getDescription()).isEqualTo(expectedDesc);
}
Also used : Status(io.opencensus.trace.Status)

Example 3 with Status

use of io.opencensus.trace.Status in project ignite by apache.

the class TimeLimitedHandler method handleException.

/**
 * @param e Exception.
 * @param logMessage Logger message.
 */
private void handleException(Exception e, String logMessage) {
    Status status = e instanceof TimeoutException ? Status.DEADLINE_EXCEEDED : Status.UNKNOWN;
    tracer.getCurrentSpan().setStatus(status.withDescription(e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()));
    logger.log(Level.WARNING, logMessage);
}
Also used : Status(io.opencensus.trace.Status) TimeoutException(java.util.concurrent.TimeoutException)

Example 4 with Status

use of io.opencensus.trace.Status in project ignite by apache.

the class OpenCensusTracingSpiTest method testNodeJoinTracing.

/**
 * Test checks that node join process is traced correctly in positive case.
 */
@Test
public void testNodeJoinTracing() throws Exception {
    IgniteEx joinedNode = startGrid(GRID_CNT);
    awaitPartitionMapExchange();
    // Consistent id is the same with node name.
    List<String> clusterNodeNames = grid(0).cluster().nodes().stream().map(node -> (String) node.consistentId()).collect(Collectors.toList());
    handler().flush();
    String joinedNodeId = joinedNode.localNode().id().toString();
    // Check existence of Traces.Discovery.NODE_JOIN_REQUEST spans with OK status on all nodes:
    Map<AttributeValue, SpanData> nodeJoinReqSpans = handler().allSpans().filter(span -> DISCOVERY_NODE_JOIN_REQUEST.spanName().equals(span.getName())).filter(span -> span.getStatus() == Status.OK).filter(span -> stringAttributeValue(joinedNodeId).equals(span.getAttributes().getAttributeMap().get(SpanTags.tag(SpanTags.EVENT_NODE, SpanTags.ID)))).collect(Collectors.toMap(span -> span.getAttributes().getAttributeMap().get(SpanTags.tag(SpanTags.NODE, SpanTags.NAME)), span -> span));
    // NODE_JOIN_REQUEST must be processed at least on coordinator node.
    // For other nodes there is no such guarantee.
    int CRD_IDX = 0;
    clusterNodeNames.stream().filter(node -> node.endsWith(String.valueOf(CRD_IDX))).forEach(nodeName -> Assert.assertTrue(String.format("%s not found on node with name=%s, nodeJoinReqSpans=%s", DISCOVERY_NODE_JOIN_REQUEST, nodeName, nodeJoinReqSpans), nodeJoinReqSpans.containsKey(stringAttributeValue(nodeName))));
    // Check existence of Traces.Discovery.NODE_JOIN_ADD spans with OK status on all nodes:
    for (int i = 0; i <= GRID_CNT; i++) {
        List<SpanData> nodeJoinAddSpans = handler().spansReportedByNode(getTestIgniteInstanceName(i)).filter(span -> DISCOVERY_NODE_JOIN_ADD.spanName().equals(span.getName())).filter(span -> span.getStatus() == Status.OK).filter(span -> stringAttributeValue(joinedNodeId).equals(span.getAttributes().getAttributeMap().get(SpanTags.tag(SpanTags.EVENT_NODE, SpanTags.ID)))).collect(Collectors.toList());
        Assert.assertTrue(String.format("%s span not found, nodeId=%d", DISCOVERY_NODE_JOIN_ADD, i), !nodeJoinReqSpans.isEmpty());
        nodeJoinAddSpans.forEach(spanData -> {
            SpanData parentSpan = handler().spanById(spanData.getParentSpanId());
            Assert.assertNotNull("Parent span doesn't exist for " + spanData, parentSpan);
            Assert.assertEquals("Parent span name is invalid, parentSpan=" + parentSpan, DISCOVERY_NODE_JOIN_REQUEST.spanName(), parentSpan.getName());
            Assert.assertEquals("Parent span is not related to joined node, parentSpan=" + parentSpan, stringAttributeValue(joinedNodeId), parentSpan.getAttributes().getAttributeMap().get(SpanTags.tag(SpanTags.EVENT_NODE, SpanTags.ID)));
        });
    }
    // Check existence of Traces.Discovery.NODE_JOIN_FINISH spans with OK status on all nodes:
    for (int i = 0; i <= GRID_CNT; i++) {
        List<SpanData> nodeJoinAddSpans = handler().spansReportedByNode(getTestIgniteInstanceName(i)).filter(span -> DISCOVERY_NODE_JOIN_FINISH.spanName().equals(span.getName())).filter(span -> span.getStatus() == Status.OK).filter(span -> stringAttributeValue(joinedNodeId).equals(span.getAttributes().getAttributeMap().get(SpanTags.tag(SpanTags.EVENT_NODE, SpanTags.ID)))).collect(Collectors.toList());
        Assert.assertTrue(String.format("%s span not found, nodeId=%d", DISCOVERY_NODE_JOIN_FINISH, i), !nodeJoinReqSpans.isEmpty());
        nodeJoinAddSpans.forEach(spanData -> {
            SpanData parentSpan = handler().spanById(spanData.getParentSpanId());
            Assert.assertNotNull("Parent span doesn't exist for " + spanData, parentSpan);
            Assert.assertEquals("Parent span name is invalid " + parentSpan, DISCOVERY_NODE_JOIN_ADD.spanName(), parentSpan.getName());
            Assert.assertEquals("Parent span is not related to joined node " + parentSpan, stringAttributeValue(joinedNodeId), parentSpan.getAttributes().getAttributeMap().get(SpanTags.tag(SpanTags.EVENT_NODE, SpanTags.ID)));
        });
    }
}
Also used : DISCOVERY_NODE_LEFT(org.apache.ignite.internal.processors.tracing.SpanType.DISCOVERY_NODE_LEFT) AttributeValue(io.opencensus.trace.AttributeValue) COMMUNICATION_REGULAR_PROCESS(org.apache.ignite.internal.processors.tracing.SpanType.COMMUNICATION_REGULAR_PROCESS) SOCKET_WRITE_BYTES(org.apache.ignite.internal.processors.tracing.SpanTags.SOCKET_WRITE_BYTES) COMMUNICATION_JOB_EXECUTE_REQUEST(org.apache.ignite.internal.processors.tracing.SpanType.COMMUNICATION_JOB_EXECUTE_REQUEST) CUSTOM_JOB_CALL(org.apache.ignite.internal.processors.tracing.SpanType.CUSTOM_JOB_CALL) IgniteEx(org.apache.ignite.internal.IgniteEx) IgniteFeatures(org.apache.ignite.internal.IgniteFeatures) SpanData(io.opencensus.trace.export.SpanData) OpenCensusTracingSpi(org.apache.ignite.spi.tracing.opencensus.OpenCensusTracingSpi) COMMUNICATION_SOCKET_READ(org.apache.ignite.internal.processors.tracing.SpanType.COMMUNICATION_SOCKET_READ) Map(java.util.Map) DISCOVERY_NODE_JOIN_ADD(org.apache.ignite.internal.processors.tracing.SpanType.DISCOVERY_NODE_JOIN_ADD) TracingConfigurationCoordinates(org.apache.ignite.spi.tracing.TracingConfigurationCoordinates) DISCOVERY_NODE_JOIN_REQUEST(org.apache.ignite.internal.processors.tracing.SpanType.DISCOVERY_NODE_JOIN_REQUEST) EXCHANGE_FUTURE(org.apache.ignite.internal.processors.tracing.SpanType.EXCHANGE_FUTURE) Status(io.opencensus.trace.Status) EventType(org.apache.ignite.events.EventType) SpanTags(org.apache.ignite.internal.processors.tracing.SpanTags) DISCOVERY_NODE_JOIN_FINISH(org.apache.ignite.internal.processors.tracing.SpanType.DISCOVERY_NODE_JOIN_FINISH) Scope(org.apache.ignite.spi.tracing.Scope) Test(org.junit.Test) Collectors(java.util.stream.Collectors) Integer.parseInt(java.lang.Integer.parseInt) COMMUNICATION_SOCKET_WRITE(org.apache.ignite.internal.processors.tracing.SpanType.COMMUNICATION_SOCKET_WRITE) DISCOVERY_CUSTOM_EVENT(org.apache.ignite.internal.processors.tracing.SpanType.DISCOVERY_CUSTOM_EVENT) List(java.util.List) COMMUNICATION_JOB_EXECUTE_RESPONSE(org.apache.ignite.internal.processors.tracing.SpanType.COMMUNICATION_JOB_EXECUTE_RESPONSE) SAMPLING_RATE_ALWAYS(org.apache.ignite.spi.tracing.TracingConfigurationParameters.SAMPLING_RATE_ALWAYS) MTC(org.apache.ignite.internal.processors.tracing.MTC) TracingConfigurationParameters(org.apache.ignite.spi.tracing.TracingConfigurationParameters) TracingSpi(org.apache.ignite.spi.tracing.TracingSpi) Assert(org.junit.Assert) AttributeValue.stringAttributeValue(io.opencensus.trace.AttributeValue.stringAttributeValue) AttributeValue(io.opencensus.trace.AttributeValue) AttributeValue.stringAttributeValue(io.opencensus.trace.AttributeValue.stringAttributeValue) SpanData(io.opencensus.trace.export.SpanData) IgniteEx(org.apache.ignite.internal.IgniteEx) Test(org.junit.Test)

Example 5 with Status

use of io.opencensus.trace.Status in project instrumentation-java by census-instrumentation.

the class TracezZPageHandler method emitSingleSpan.

// Emits the internal html for a single {@link SpanData}.
@SuppressWarnings("deprecation")
private static void emitSingleSpan(Formatter formatter, SpanData span) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(TimeUnit.SECONDS.toMillis(span.getStartTimestamp().getSeconds()));
    long microsField = TimeUnit.NANOSECONDS.toMicros(span.getStartTimestamp().getNanos());
    String elapsedSecondsStr = span.getEndTimestamp() != null ? String.format("%13.6f", durationToNanos(span.getEndTimestamp().subtractTimestamp(span.getStartTimestamp())) * 1.0e-9) : String.format("%13s", " ");
    SpanContext spanContext = span.getContext();
    formatter.format("<b>%04d/%02d/%02d-%02d:%02d:%02d.%06d %s     TraceId: <b style=\"color:%s;\">%s</b> " + "SpanId: %s ParentSpanId: %s</b>%n", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND), microsField, elapsedSecondsStr, spanContext.getTraceOptions().isSampled() ? SAMPLED_TRACE_ID_COLOR : NOT_SAMPLED_TRACE_ID_COLOR, BaseEncoding.base16().lowerCase().encode(spanContext.getTraceId().getBytes()), BaseEncoding.base16().lowerCase().encode(spanContext.getSpanId().getBytes()), BaseEncoding.base16().lowerCase().encode(span.getParentSpanId() == null ? SpanId.INVALID.getBytes() : span.getParentSpanId().getBytes()));
    int lastEntryDayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
    Timestamp lastTimestampNanos = span.getStartTimestamp();
    TimedEvents<Annotation> annotations = span.getAnnotations();
    TimedEvents<io.opencensus.trace.NetworkEvent> networkEvents = span.getNetworkEvents();
    List<TimedEvent<?>> timedEvents = new ArrayList<TimedEvent<?>>(annotations.getEvents());
    timedEvents.addAll(networkEvents.getEvents());
    Collections.sort(timedEvents, new TimedEventComparator());
    for (TimedEvent<?> event : timedEvents) {
        // Special printing so that durations smaller than one second
        // are left padded with blanks instead of '0' characters.
        // E.g.,
        // Number                  Printout
        // ---------------------------------
        // 0.000534                  .   534
        // 1.000534                 1.000534
        long deltaMicros = TimeUnit.NANOSECONDS.toMicros(durationToNanos(event.getTimestamp().subtractTimestamp(lastTimestampNanos)));
        String deltaString;
        if (deltaMicros >= 1000000) {
            deltaString = String.format("%.6f", (deltaMicros / 1000000.0));
        } else {
            deltaString = String.format(".%6d", deltaMicros);
        }
        calendar.setTimeInMillis(TimeUnit.SECONDS.toMillis(event.getTimestamp().getSeconds()) + TimeUnit.NANOSECONDS.toMillis(event.getTimestamp().getNanos()));
        microsField = TimeUnit.NANOSECONDS.toMicros(event.getTimestamp().getNanos());
        int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
        if (dayOfYear == lastEntryDayOfYear) {
            formatter.format("%11s", "");
        } else {
            formatter.format("%04d/%02d/%02d-", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
            lastEntryDayOfYear = dayOfYear;
        }
        formatter.format("%02d:%02d:%02d.%06d %13s ... %s%n", calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND), microsField, deltaString, htmlEscaper().escape(event.getEvent() instanceof Annotation ? renderAnnotation((Annotation) event.getEvent()) : renderNetworkEvents((io.opencensus.trace.NetworkEvent) castNonNull(event.getEvent()))));
        lastTimestampNanos = event.getTimestamp();
    }
    Status status = span.getStatus();
    if (status != null) {
        formatter.format("%44s %s%n", "", htmlEscaper().escape(renderStatus(status)));
    }
    formatter.format("%44s %s%n", "", htmlEscaper().escape(renderAttributes(span.getAttributes().getAttributeMap())));
}
Also used : Status(io.opencensus.trace.Status) SpanContext(io.opencensus.trace.SpanContext) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) TimedEvent(io.opencensus.trace.export.SpanData.TimedEvent) Timestamp(io.opencensus.common.Timestamp) Annotation(io.opencensus.trace.Annotation)

Aggregations

Status (io.opencensus.trace.Status)8 AttributeValue (io.opencensus.trace.AttributeValue)4 SpanContext (io.opencensus.trace.SpanContext)4 Timestamp (io.opencensus.common.Timestamp)3 SpanData (io.opencensus.trace.export.SpanData)3 Annotation (io.opencensus.trace.Annotation)2 SpanId (io.opencensus.trace.SpanId)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 TimeoutException (java.util.concurrent.TimeoutException)2 AttributeValue.stringAttributeValue (io.opencensus.trace.AttributeValue.stringAttributeValue)1 TimedEvent (io.opencensus.trace.export.SpanData.TimedEvent)1 Integer.parseInt (java.lang.Integer.parseInt)1 Calendar (java.util.Calendar)1 List (java.util.List)1 Collectors (java.util.stream.Collectors)1 EventType (org.apache.ignite.events.EventType)1 IgniteEx (org.apache.ignite.internal.IgniteEx)1 IgniteFeatures (org.apache.ignite.internal.IgniteFeatures)1 MTC (org.apache.ignite.internal.processors.tracing.MTC)1