Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import io.opentelemetry.sdk.common.export.ProxyOptions;
import io.opentelemetry.sdk.common.export.RetryPolicy;
import io.opentelemetry.sdk.common.internal.DaemonThreadFactory;
import io.opentelemetry.sdk.common.internal.ThrottlingLogger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -68,6 +69,7 @@ public final class JdkHttpSender implements HttpSender {

private static final Logger logger = Logger.getLogger(JdkHttpSender.class.getName());

private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger);
private final boolean managedExecutor;
private final ExecutorService executorService;
private final HttpClient client;
Expand Down Expand Up @@ -420,7 +422,12 @@ private HttpResponse toHttpResponse(java.net.http.HttpResponse<InputStream> resp
bodyBytes = baos.toByteArray();
} catch (IOException e) {
bodyBytes = new byte[0];
logger.log(Level.WARNING, "Failed to read response body", e);
throttlingLogger.log(
Level.WARNING,
"Failed to read response body. Enable FINE logging for "
+ JdkHttpSender.class.getName()
+ " for details.");
logger.log(Level.FINE, "Failed to read response body", e);
}
if (bodyBytes.length > maxResponseBodySize) {
throw new ResponseBodyTooLargeException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import io.opentelemetry.sdk.common.export.MessageWriter;
import io.opentelemetry.sdk.common.export.ProxyOptions;
import io.opentelemetry.sdk.common.export.RetryPolicy;
import io.opentelemetry.sdk.common.internal.ThrottlingLogger;
import java.io.IOException;
import java.net.URI;
import java.time.Duration;
Expand Down Expand Up @@ -61,6 +62,7 @@ public final class OkHttpHttpSender implements HttpSender {

private static final Logger logger = Logger.getLogger(OkHttpHttpSender.class.getName());

private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger);
private final boolean managedExecutor;
private final OkHttpClient client;
private final HttpUrl url;
Expand Down Expand Up @@ -221,7 +223,12 @@ private void handleResponse(
}
}
} catch (IOException e) {
logger.log(Level.WARNING, "Failed to read response body", e);
throttlingLogger.log(
Level.WARNING,
"Failed to read response body. Enable FINE logging for "
+ OkHttpHttpSender.class.getName()
+ " for details.");
logger.log(Level.FINE, "Failed to read response body", e);
}

if (buffer.size() > maxResponseBodySize) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,12 +193,7 @@ private static <C> SpanContext getSpanContextFromHeader(
// the propagation value
value = URLDecoder.decode(value, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException | IllegalArgumentException e) {
logger.fine(
"Error decoding '"
+ PROPAGATION_HEADER
+ "' with value "
+ value
+ ". Returning INVALID span context.");
logger.fine("Error decoding '" + PROPAGATION_HEADER + "'. Returning INVALID span context.");
return SpanContext.getInvalid();
}
}
Expand All @@ -207,12 +202,7 @@ private static <C> SpanContext getSpanContextFromHeader(
// large token array before the length check below.
String[] parts = value.split(String.valueOf(PROPAGATION_HEADER_DELIMITER), 5);
if (parts.length != 4) {
logger.fine(
"Invalid header '"
+ PROPAGATION_HEADER
+ "' with value "
+ value
+ ". Returning INVALID span context.");
logger.fine("Invalid header '" + PROPAGATION_HEADER + "'. Returning INVALID span context.");
return SpanContext.getInvalid();
}

Expand All @@ -221,9 +211,7 @@ private static <C> SpanContext getSpanContextFromHeader(
logger.fine(
"Invalid TraceId in Jaeger header: '"
+ PROPAGATION_HEADER
+ "' with traceId "
+ traceId
+ ". Returning INVALID span context.");
+ "'. Returning INVALID span context.");
return SpanContext.getInvalid();
}

Expand Down Expand Up @@ -398,22 +386,16 @@ private static void logMalformed(String header, int start, int end) {
}

private static SpanContext buildSpanContext(String traceId, String spanId, String flags) {
try {
String otelTraceId = StringUtils.padLeft(traceId, MAX_TRACE_ID_LENGTH);
String otelSpanId = StringUtils.padLeft(spanId, MAX_SPAN_ID_LENGTH);
int flagsInt = Integer.parseInt(flags, 16);
return SpanContext.createFromRemoteParent(
otelTraceId,
otelSpanId,
((flagsInt & 1) == 1) ? TraceFlags.getSampled() : TraceFlags.getDefault(),
TraceState.getDefault());
} catch (RuntimeException e) {
logger.log(
Level.FINE,
"Error parsing '" + PROPAGATION_HEADER + "' header. Returning INVALID span context.",
e);
return SpanContext.getInvalid();
}
// Q: can you explain the code changes in this file besides avoiding logging the exception in
// this method, which was the original ask?
String otelTraceId = StringUtils.padLeft(traceId, MAX_TRACE_ID_LENGTH);
String otelSpanId = StringUtils.padLeft(spanId, MAX_SPAN_ID_LENGTH);
int flagsInt = Integer.parseInt(flags, 16);
return SpanContext.createFromRemoteParent(
otelTraceId,
otelSpanId,
((flagsInt & 1) == 1) ? TraceFlags.getSampled() : TraceFlags.getDefault(),
TraceState.getDefault());
}

private static boolean isTraceIdValid(String value) {
Expand All @@ -425,6 +407,18 @@ private static boolean isSpanIdValid(String value) {
}

private static boolean isFlagsValid(String value) {
return !value.isEmpty() && value.length() <= MAX_FLAGS_LENGTH;
if (value.isEmpty() || value.length() > MAX_FLAGS_LENGTH) {
return false;
}
int start = value.charAt(0) == '+' || value.charAt(0) == '-' ? 1 : 0;
if (start == value.length()) {
return false;
}
for (int i = start; i < value.length(); i++) {
if (Character.digit(value.charAt(i), 16) == -1) {
return false;
}
}
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import static org.assertj.core.api.Assertions.assertThat;

import com.google.common.collect.ImmutableMap;
import io.github.netmikey.logunit.api.LogCapturer;
import io.jaegertracing.internal.JaegerSpanContext;
import io.jaegertracing.internal.propagation.TextMapCodec;
import io.opentelemetry.api.baggage.Baggage;
Expand Down Expand Up @@ -36,14 +37,19 @@
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.event.Level;

/** Unit tests for {@link JaegerPropagator}. */
@SuppressWarnings("deprecation")
class JaegerPropagatorTest {

@RegisterExtension
LogCapturer logs = LogCapturer.create().captureForType(JaegerPropagator.class, Level.DEBUG);

private static final String BAGGAGE_HEADER = JaegerPropagator.BAGGAGE_HEADER;
private static final String BAGGAGE_PREFIX = JaegerPropagator.BAGGAGE_PREFIX;
private static final char DEPRECATED_PARENT_SPAN = JaegerPropagator.DEPRECATED_PARENT_SPAN;
Expand Down Expand Up @@ -347,9 +353,13 @@ void extract_InvalidFlags_NonNumeric() {
Map<String, String> invalidHeaders = new LinkedHashMap<>();
invalidHeaders.put(
PROPAGATION_HEADER,
generateTraceIdHeaderValue(TRACE_ID, SPAN_ID, DEPRECATED_PARENT_SPAN, "abcdefr"));
generateTraceIdHeaderValue(TRACE_ID, SPAN_ID, DEPRECATED_PARENT_SPAN, "g"));

verifyInvalidBehavior(invalidHeaders);
assertThat(
logs.assertContains("Invalid Flags in Jaeger header: 'uber-trace-id'").getThrowable())
.isNull();
assertThat(logs.getEvents()).hasSize(1);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.DoubleHistogramBuilder;
import io.opentelemetry.api.metrics.LongHistogramBuilder;
import io.opentelemetry.common.impl.ApiUsageLogger;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.common.internal.ThrottlingLogger;
import io.opentelemetry.sdk.metrics.internal.aggregator.ExplicitBucketHistogramUtils;
import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor;
import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand Down Expand Up @@ -106,11 +106,16 @@ public LongHistogramBuilder ofLongs() {

@Override
public DoubleHistogramBuilder setExplicitBucketBoundariesAdvice(List<Double> bucketBoundaries) {
try {
Objects.requireNonNull(bucketBoundaries, "bucketBoundaries must not be null");
ExplicitBucketHistogramUtils.validateBucketBoundaries(bucketBoundaries);
} catch (IllegalArgumentException | NullPointerException e) {
logger.log(Level.WARNING, "Error setting explicit bucket boundaries advice", e);
if (bucketBoundaries == null) {
ApiUsageLogger.logNullParam(
DoubleHistogramBuilder.class, "setExplicitBucketBoundariesAdvice", "bucketBoundaries");
return this;
}
String error =
ExplicitBucketHistogramUtils.getBucketBoundariesValidationError(bucketBoundaries);
if (error != null) {
ApiUsageLogger.logUsageIssue(
DoubleHistogramBuilder.class, "setExplicitBucketBoundariesAdvice", error);
return this;
}
builder.setExplicitBucketBoundaries(bucketBoundaries);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongHistogram;
import io.opentelemetry.api.metrics.LongHistogramBuilder;
import io.opentelemetry.common.impl.ApiUsageLogger;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.common.internal.ThrottlingLogger;
import io.opentelemetry.sdk.metrics.internal.aggregator.ExplicitBucketHistogramUtils;
import io.opentelemetry.sdk.metrics.internal.descriptor.Advice;
import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor;
import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

class SdkLongHistogram extends AbstractInstrument implements LongHistogram {
private static final Logger logger = Logger.getLogger(SdkLongHistogram.class.getName());
Expand Down Expand Up @@ -109,13 +109,26 @@ public SdkLongHistogram build() {

@Override
public LongHistogramBuilder setExplicitBucketBoundariesAdvice(List<Long> bucketBoundaries) {
List<Double> boundaries;
try {
Objects.requireNonNull(bucketBoundaries, "bucketBoundaries must not be null");
boundaries = bucketBoundaries.stream().map(Long::doubleValue).collect(Collectors.toList());
ExplicitBucketHistogramUtils.validateBucketBoundaries(boundaries);
} catch (IllegalArgumentException | NullPointerException e) {
logger.log(Level.WARNING, "Error setting explicit bucket boundaries advice", e);
if (bucketBoundaries == null) {
ApiUsageLogger.logNullParam(
LongHistogramBuilder.class, "setExplicitBucketBoundariesAdvice", "bucketBoundaries");
return this;
}
List<Double> boundaries = new ArrayList<>(bucketBoundaries.size());
String error = null;
for (Long boundary : bucketBoundaries) {
if (boundary == null) {
error = "bucketBoundaries must not contain null";
break;
}
boundaries.add(boundary.doubleValue());
}
if (error == null) {
error = ExplicitBucketHistogramUtils.getBucketBoundariesValidationError(boundaries);
}
if (error != null) {
ApiUsageLogger.logUsageIssue(
LongHistogramBuilder.class, "setExplicitBucketBoundariesAdvice", error);
return this;
}
builder.setExplicitBucketBoundaries(boundaries);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.api.metrics.MeterProvider;
import io.opentelemetry.api.metrics.ObservableMeasurement;
import io.opentelemetry.common.impl.ApiUsageLogger;
import io.opentelemetry.context.Context;
import io.opentelemetry.sdk.common.InstrumentationScopeInfo;
import io.opentelemetry.sdk.metrics.data.MetricData;
Expand Down Expand Up @@ -192,7 +193,7 @@ void resetForTest() {

@Override
public LongCounterBuilder counterBuilder(String name) {
if (!checkValidInstrumentName(name)) {
if (!checkValidInstrumentName(name, "counterBuilder")) {
return NOOP_METER.counterBuilder(NOOP_INSTRUMENT_NAME);
}
return INCUBATOR_AVAILABLE
Expand All @@ -202,7 +203,7 @@ public LongCounterBuilder counterBuilder(String name) {

@Override
public LongUpDownCounterBuilder upDownCounterBuilder(String name) {
if (!checkValidInstrumentName(name)) {
if (!checkValidInstrumentName(name, "upDownCounterBuilder")) {
return NOOP_METER.upDownCounterBuilder(NOOP_INSTRUMENT_NAME);
}
return INCUBATOR_AVAILABLE
Expand All @@ -212,7 +213,7 @@ public LongUpDownCounterBuilder upDownCounterBuilder(String name) {

@Override
public DoubleHistogramBuilder histogramBuilder(String name) {
if (!checkValidInstrumentName(name)) {
if (!checkValidInstrumentName(name, "histogramBuilder")) {
return NOOP_METER.histogramBuilder(NOOP_INSTRUMENT_NAME);
}
return INCUBATOR_AVAILABLE
Expand All @@ -222,7 +223,7 @@ public DoubleHistogramBuilder histogramBuilder(String name) {

@Override
public DoubleGaugeBuilder gaugeBuilder(String name) {
if (!checkValidInstrumentName(name)) {
if (!checkValidInstrumentName(name, "gaugeBuilder")) {
return NOOP_METER.gaugeBuilder(NOOP_INSTRUMENT_NAME);
}
return INCUBATOR_AVAILABLE
Expand Down Expand Up @@ -360,24 +361,29 @@ public String toString() {
return "SdkMeter{instrumentationScopeInfo=" + instrumentationScopeInfo + "}";
}

/** Check if the instrument name is valid. If invalid, log a warning. */
// Visible for testing
static boolean checkValidInstrumentName(String name) {
if (name != null && VALID_INSTRUMENT_NAME_PATTERN.matcher(name).matches()) {
private static boolean checkValidInstrumentName(String name, String methodName) {
if (checkValidInstrumentName(name)) {
return true;
}
if (logger.isLoggable(Level.WARNING)) {
logger.log(
Level.WARNING,
// Q: only called internally so we don't need to check this stuff
if (name == null) {
ApiUsageLogger.logNullParam(Meter.class, methodName, "name");
} else {
ApiUsageLogger.logUsageIssue(
Meter.class,
methodName,
"Instrument name \""
+ name
+ "\" is invalid, returning noop instrument. Instrument names must consist of 255 or fewer characters including alphanumeric, _, ., -, /, and start with a letter.",
new AssertionError());
+ (name.length() <= 255 ? name : name.substring(0, 255) + "...")
+ "\" is invalid, returning noop instrument. Instrument names must consist of 255 or fewer characters including alphanumeric, _, ., -, /, and start with a letter.");
}

return false;
}

// Visible for testing
static boolean checkValidInstrumentName(String name) {
return name != null && VALID_INSTRUMENT_NAME_PATTERN.matcher(name).matches();
}

private static class MultiWritableMetricStorage implements WriteableMetricStorage {
private final List<? extends WriteableMetricStorage> storages;

Expand Down
Loading
Loading