Skip to content
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
- Keep the Android feedback form available when its options configurator throws ([#6239](https://github.com/getsentry/sentry-java/pull/6239)).
- Isolate nonfatal callback throwables while continuing to propagate fatal JVM errors ([#6251](https://github.com/getsentry/sentry-java/pull/6251)).

### Internal

- Hold the hostname cache on `SentryOptions` instead of a static singleton ([#6117](https://github.com/getsentry/sentry-java/pull/6117))

### Dependencies

- Bump Native SDK from v0.17.2 to v0.17.3 ([#6250](https://github.com/getsentry/sentry-java/pull/6250))
Expand Down
2 changes: 1 addition & 1 deletion sentry/api/sentry.api
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,6 @@ public final class io/sentry/Hint {

public final class io/sentry/HostnameCache {
public fun getHostname ()Ljava/lang/String;
public static fun getInstance ()Lio/sentry/HostnameCache;
}

public final class io/sentry/HttpBodyType : java/lang/Enum {
Expand Down Expand Up @@ -3808,6 +3807,7 @@ public class io/sentry/SentryOptions : io/sentry/transport/RateLimiterConfig {
public fun getFlushTimeoutMillis ()J
public fun getFullyDisplayedReporter ()Lio/sentry/FullyDisplayedReporter;
public fun getGestureTargetLocators ()Ljava/util/List;
public fun getHostnameCache ()Lio/sentry/HostnameCache;
public fun getIdleTimeout ()Ljava/lang/Long;
public fun getIgnoredCheckIns ()Ljava/util/List;
public fun getIgnoredErrors ()Ljava/util/List;
Expand Down
29 changes: 9 additions & 20 deletions sentry/src/main/java/io/sentry/HostnameCache.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package io.sentry;

import io.sentry.util.AutoClosableReentrantLock;
import io.sentry.util.Objects;
import java.net.InetAddress;
import java.util.concurrent.Callable;
Expand All @@ -26,8 +25,8 @@
* purposes, the operation of retrieving the hostname will automatically fail after a period of time
* defined by {@link #GET_HOSTNAME_TIMEOUT} without result.
*
* <p>HostnameCache is a singleton and its instance should be obtained through {@link
* HostnameCache#getInstance()}.
* <p>One instance is held per {@link SentryOptions} and should be obtained through {@link
* SentryOptions#getHostnameCache()}.
*/
@ApiStatus.Internal
public final class HostnameCache {
Expand All @@ -39,10 +38,6 @@ public final class HostnameCache {
/** How long the worker thread may stay idle before it self-terminates. */
private static final long THREAD_KEEP_ALIVE_SECONDS = 30;

private static volatile @Nullable HostnameCache INSTANCE;
private static final @NotNull AutoClosableReentrantLock staticLock =
new AutoClosableReentrantLock();

/** Time for which the cache is kept. */
private final long cacheDuration;

Expand All @@ -59,19 +54,13 @@ public final class HostnameCache {

private final @NotNull ExecutorService executorService;

public static @NotNull HostnameCache getInstance() {
if (INSTANCE == null) {
try (final @NotNull ISentryLifecycleToken ignored = staticLock.acquire()) {
if (INSTANCE == null) {
INSTANCE = new HostnameCache();
}
}
}

return INSTANCE;
}

private HostnameCache() {
/**
* Do not construct a hostname cache directly; get it from {@link
* SentryOptions#getHostnameCache()}. Every instance resolves the hostname as soon as it is built
* and caches it on its own, so another instance would repeat that blocking lookup instead of
* sharing the cached value.
*/
HostnameCache() {
this(HOSTNAME_CACHE_DURATION);
}

Expand Down
12 changes: 1 addition & 11 deletions sentry/src/main/java/io/sentry/MainEventProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ public final class MainEventProcessor implements SentryEventProcessor {
private final @NotNull SentryOptions options;
private final @NotNull SentryThreadFactory sentryThreadFactory;
private final @NotNull SentryExceptionFactory sentryExceptionFactory;
private volatile @Nullable HostnameCache hostnameCache = null;

public MainEventProcessor(final @NotNull SentryOptions options) {
this.options = options;
Expand Down Expand Up @@ -161,16 +160,7 @@ private void setServerName(final @NotNull SentryBaseEvent event) {
}

if (options.isAttachServerName() && event.getServerName() == null) {
ensureHostnameCache();
if (hostnameCache != null) {
event.setServerName(hostnameCache.getHostname());
}
}
}

private void ensureHostnameCache() {
if (hostnameCache == null) {
hostnameCache = HostnameCache.getInstance();
event.setServerName(options.getHostnameCache().getHostname());
}
}

Expand Down
16 changes: 16 additions & 0 deletions sentry/src/main/java/io/sentry/SentryOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,16 @@ public class SentryOptions implements RateLimiterConfig {
private final @NotNull LazyEvaluator<SentryDateProvider> dateProvider =
new LazyEvaluator<>(() -> new SentryAutoDateProvider());

/**
* Cache of the local hostname, used when {@link #isAttachServerName()} is enabled.
*
* <p>Evaluated lazily because resolving the hostname blocks on {@code
* InetAddress.getLocalHost()}, which no {@code Sentry.init} should pay for up front.
*/
@ApiStatus.Internal
private final @NotNull LazyEvaluator<HostnameCache> hostnameCache =
new LazyEvaluator<>(() -> new HostnameCache());

private final @NotNull List<IPerformanceCollector> performanceCollectors = new ArrayList<>();

/** Performance collector that collect performance stats while transactions run. */
Expand Down Expand Up @@ -3140,6 +3150,12 @@ public void setDateProvider(final @NotNull SentryDateProvider dateProvider) {
return JavaMonotonicTicker.getInstance();
}

/** Returns the hostname cache, resolving the hostname on first use. */
@ApiStatus.Internal
public @NotNull HostnameCache getHostnameCache() {
return hostnameCache.getValue();
}

/**
* Adds a ICollector.
*
Expand Down
3 changes: 1 addition & 2 deletions sentry/src/main/java/io/sentry/logger/LoggerApi.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package io.sentry.logger;

import io.sentry.HostnameCache;
import io.sentry.IScope;
import io.sentry.ISpan;
import io.sentry.PropagationContext;
Expand Down Expand Up @@ -256,7 +255,7 @@ private void setServerName(
"server.address",
new SentryLogEventAttributeValue(SentryAttributeType.STRING, optionsServerName));
} else if (options.isAttachServerName()) {
final @Nullable String hostname = HostnameCache.getInstance().getHostname();
final @Nullable String hostname = options.getHostnameCache().getHostname();
if (hostname != null) {
attributes.put(
"server.address",
Expand Down
3 changes: 1 addition & 2 deletions sentry/src/main/java/io/sentry/metrics/MetricsApi.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package io.sentry.metrics;

import io.sentry.HostnameCache;
import io.sentry.IScope;
import io.sentry.ISpan;
import io.sentry.PropagationContext;
Expand Down Expand Up @@ -241,7 +240,7 @@ private void setServerName(
"server.address",
new SentryLogEventAttributeValue(SentryAttributeType.STRING, optionsServerName));
} else if (options.isAttachServerName()) {
final @Nullable String hostname = HostnameCache.getInstance().getHostname();
final @Nullable String hostname = options.getHostnameCache().getHostname();
if (hostname != null) {
attributes.put(
"server.address",
Expand Down
37 changes: 15 additions & 22 deletions sentry/src/test/java/io/sentry/MainEventProcessorTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import io.sentry.protocol.User
import io.sentry.util.HintUtils
import java.lang.RuntimeException
import java.net.InetAddress
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
Expand All @@ -19,7 +18,6 @@ import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
import org.awaitility.kotlin.await
import org.mockito.Mockito
import org.mockito.kotlin.mock
import org.mockito.kotlin.reset
import org.mockito.kotlin.times
Expand All @@ -28,17 +26,23 @@ import org.mockito.kotlin.whenever

class MainEventProcessorTest {
class Fixture {
val sentryOptions: SentryOptions =
SentryOptions().apply {
dsn = dsnString
release = "release"
dist = "dist"
sdkVersion = SdkVersion("test", "1.2.3")
}
val scopes = mock<IScopes>()
val getLocalhost = mock<InetAddress>()
// Built in getSut() rather than here: the constructor resolves the hostname straight away,
// so it has to run after getLocalhost is stubbed.
lateinit var hostnameCache: HostnameCache
val sentryOptions: SentryOptions =
object : SentryOptions() {
// Qualified: an unqualified name here would resolve to this override, not the field.
override fun getHostnameCache(): HostnameCache = this@Fixture.hostnameCache
}
.apply {
dsn = dsnString
release = "release"
dist = "dist"
sdkVersion = SdkVersion("test", "1.2.3")
}
lateinit var sentryTracer: SentryTracer
private val hostnameCacheMock = Mockito.mockStatic(HostnameCache::class.java)

fun getSut(
attachThreads: Boolean = true,
Expand Down Expand Up @@ -76,21 +80,10 @@ class MainEventProcessorTest {
}
whenever(scopes.options).thenReturn(sentryOptions)
sentryTracer = SentryTracer(TransactionContext("", ""), scopes)

val hostnameCache = HostnameCache(hostnameCacheDuration) { getLocalhost }
hostnameCacheMock.`when`<Any> { HostnameCache.getInstance() }.thenReturn(hostnameCache)
hostnameCache = HostnameCache(hostnameCacheDuration) { getLocalhost }

return MainEventProcessor(sentryOptions)
}

fun teardown() {
hostnameCacheMock.close()
}
}

@AfterTest
fun teardown() {
fixture.teardown()
}

private val fixture = Fixture()
Expand Down
18 changes: 18 additions & 0 deletions sentry/src/test/java/io/sentry/SentryOptionsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package io.sentry
import com.google.common.truth.Truth.assertThat
import io.sentry.SentryOptions.RequestSize
import io.sentry.logger.ILoggerBatchProcessorFactory
import io.sentry.test.getProperty
import io.sentry.util.LazyEvaluator
import io.sentry.util.StringUtils
import java.io.File
import java.net.Proxy
Expand Down Expand Up @@ -1331,4 +1333,20 @@ class SentryOptionsTest {
options.scopesStorageFactory = null
assertNull(options.scopesStorageFactory)
}

private fun SentryOptions.peekHostnameCache(): HostnameCache? =
getProperty<LazyEvaluator<HostnameCache>>("hostnameCache").getProperty("value")

@Test
fun `hostname is resolved on first use, not when options are constructed`() {
val options = SentryOptions()

assertThat(options.peekHostnameCache()).isNull()

val cache = options.hostnameCache

// Also keeps the assertion above honest: peek does report a cache once one exists.
assertThat(options.peekHostnameCache()).isSameInstanceAs(cache)
assertThat(options.hostnameCache).isSameInstanceAs(cache)
}
}
Loading