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;
}
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);
}
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);
}
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)));
});
}
}
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())));
}
Aggregations