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 @@ -750,9 +750,11 @@ Properties createProperties() {
BigQueryJdbcUrlUtility.ENABLE_GRAPH_METADATA_PROPERTY_NAME,
String.valueOf(this.enableGraphMetadata));
}
connectionProperties.setProperty(
BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME,
String.valueOf(getEnableDiagnosticTelemetry()));
if (this.enableDiagnosticTelemetry != null) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Careful when merging with @Neenu1995 changes around datasource

connectionProperties.setProperty(
BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME,
String.valueOf(this.enableDiagnosticTelemetry));
}
return connectionProperties;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ final class TelemetryBatcher implements AutoCloseable {
private volatile boolean backoffActive;

private final AtomicBoolean isClosed = new AtomicBoolean(false);
// Set concurrently by close(false) without acquiring flushLock so opt-out or suppression
// teardown never blocks on an in-flight upload and aborts or skips requeue on the batcher
// thread.
private volatile boolean discardPending = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest just passing it as argument since it is only 2 methods

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

discardPending can't be a method argument because close(false) doesn't call flush() — flush() is already running asynchronously on the background jdbc-telemetry-batcher thread holding flushLock, while close(false) runs on a JDBC connecting thread without acquiring flushLock (so connect never blocks on an in-flight upload).

volatile boolean discardPending is the cross-thread cancellation signal from close(false) to an in-flight flush(). Added comments explaining this and a concurrency unit test

private final AtomicBoolean flushPending = new AtomicBoolean();
private final AtomicLong currentScheduleDelayMs = new AtomicLong(-1);
private volatile ScheduledFuture<?> scheduledTask;
Expand Down Expand Up @@ -132,11 +136,30 @@ private boolean isConfigured() {

@Override
public void close() {
close(true);
}

/**
* Stops background flushing.
*
* <p>Called with {@code flush = false} on opt-out, suppression, or race-loser teardown so
* buffered metrics are discarded immediately without attempting an outbound upload or blocking on
* an in-flight flush.
*/
void close(boolean flush) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When do we call it with false?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's called via TelemetryManager.closeQuietly(manager, false) in three places:

  1. TelemetryManager.disableGlobally(...) — opt-out in this PR, custom universe/endpoint suppression in fix(bigquery-jdbc): suppress Clearcut diagnostic telemetry for custom universes and endpoint overrides #15395, and conflicting transport profiles in fix(bigquery-jdbc): propagate proxy and SSL TrustStore settings to Clearcut transport #15396 (must discard buffered metrics without uploading to play.googleapis.com or blocking connect for up to 2 s).
  2. Closing a losing race candidate in TelemetryManager.getInstance(...)
  3. Test teardown (TelemetryTestUtils.reset()).

Updated the close(boolean flush) Javadoc to call this out explicitly.

if (!flush) {
discardPending = true;
}
if (isClosed.compareAndSet(false, true)) {
if (scheduledTask != null) {
scheduledTask.cancel(false);
}
boolean flushed = flushOnClose();
boolean flushed = false;
if (flush) {
flushed = flushOnClose();
} else {
Comment thread
keshavdandeva marked this conversation as resolved.
Resolved
metricsMap = new ConcurrentHashMap<>();
}
if (ownsExecutor && executorService != null) {
if (flushed) {
executorService.shutdown();
Expand Down Expand Up @@ -206,7 +229,10 @@ private <A extends TelemetryAccumulator> A getOrAddAccumulator(TelemetryKey key)
TransportResult flush() {
flushLock.lock();
try {
if (!isConfigured()) {
if (!isConfigured() || discardPending) {
if (discardPending) {
this.metricsMap = new ConcurrentHashMap<>();
Comment thread
keshavdandeva marked this conversation as resolved.
Resolved
}
return TransportResult.disabled();
}

Expand All @@ -232,6 +258,12 @@ TransportResult flush() {
accumulator.addToPayload(payloadBuilder);
}

// Re-check before sending: close(false) may set discardPending concurrently without
// flushLock.
if (discardPending) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually this is also unreachable? Line 226

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reachable under concurrency: close(false) does not acquire flushLock, so another thread can set discardPending = true after the background flush() thread passed line 226 while it is assembling the payload. Re-checking here aborts before transport.send(...) sends an outbound request. Added an inline comment clarifying this.

return TransportResult.disabled();
}

TransportResult result;
try {
result = transport.send(payloadBuilder.build());
Expand All @@ -241,6 +273,11 @@ TransportResult flush() {
}

if (!result.isSuccess()) {
// Re-check after send: close(false) may have fired (or interrupted send) while in flight;
// skip re-merging discarded metrics back into metricsMap.
if (discardPending) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is unreachable? Line 255 should return

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also reachable under concurrency: if close(false) fires while flush() is blocked inside transport.send(...) (including when executorService.shutdownNow() interrupts the in-flight send, causing !result.isSuccess()), discardPending flips to true after line 255. Re-checking here skips remergeFailedMetrics(snapMetrics) so discarded metrics aren't re-inserted into metricsMap after close(false) cleared it. Added an inline comment and a test for this path.

return result;
}
// Suppress the size trigger until a flush succeeds; reschedule() below spaces the retries.
backoffActive = true;
// Simple requeue logic for failed requests
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,16 @@ static Builder builder() {
return new Builder();
}

Builder toBuilder() {
return new Builder()
.setEnabled(enabled)
.setLogSource(logSource)
.setEndpointUrl(endpointUrl)
.setUploadIntervalMs(uploadIntervalMs)
.setBatchSizeThreshold(batchSizeThreshold)
.setDriverEnvironment(driverEnvironment);
}

/** Builder for {@link TelemetryConfiguration}. */
static class Builder {
private boolean enabled = TelemetryPropertyUtility.DEFAULT_ENABLE_DIAGNOSTIC_TELEMETRY_VALUE;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand All @@ -39,6 +40,7 @@ public final class TelemetryManager implements AutoCloseable {

private static volatile TelemetryManager instance;
private static volatile boolean globallyDisabled = false;
private static final AtomicBoolean SHUTDOWN_HOOK_REGISTERED = new AtomicBoolean(false);

private final TelemetryBatcher batcher;

Expand All @@ -59,12 +61,10 @@ public static TelemetryManager getInstance(Properties properties) {
return null;
}

if (properties != null
&& !TelemetryConfiguration.builder().resolveProperties(properties).build().isEnabled()) {
synchronized (TelemetryManager.class) {
globallyDisabled = true;
closeInstance();
}
TelemetryConfiguration preliminaryConfig =
TelemetryConfiguration.builder().resolveProperties(properties).build();
if (!preliminaryConfig.isEnabled()) {
disableGlobally("opt-out configuration");
return null;
}

Expand All @@ -73,37 +73,71 @@ public static TelemetryManager getInstance(Properties properties) {
return localRef;
}

TelemetryConfiguration config =
preliminaryConfig.toBuilder()
.setDriverEnvironment(DriverEnvironmentDetector.build())
.build();
ClearcutTransport transport = new ClearcutTransport(config);
TelemetryManager candidate = new TelemetryManager(new TelemetryBatcher(config, transport));

TelemetryManager active;
boolean closeCandidate = false;
synchronized (TelemetryManager.class) {
if (globallyDisabled) {
return null;
active = null;
closeCandidate = true;
} else if (instance != null) {
active = instance;
closeCandidate = true;
} else {
// Registered before the instance is published so that a non-null instance always implies a
// registered shutdown hook.
registerShutdownHook();
instance = candidate;
active = candidate;
}
}
if (closeCandidate) {
closeQuietly(candidate, false);
}
return active;
}

static void disableGlobally(String reason) {
TelemetryManager localRef;
boolean newlyDisabled;
synchronized (TelemetryManager.class) {
newlyDisabled = !globallyDisabled;
globallyDisabled = true;
localRef = instance;
if (localRef != null) {
return localRef;
}
TelemetryConfiguration config =
TelemetryConfiguration.builder()
.resolveProperties(properties)
.setDriverEnvironment(DriverEnvironmentDetector.build())
.build();
ClearcutTransport transport = new ClearcutTransport(config);
TelemetryBatcher batcher = new TelemetryBatcher(config, transport);
localRef = new TelemetryManager(batcher);
// Registered before the instance is published so that a non-null instance always implies a
// registered shutdown hook.
registerShutdownHook();
instance = localRef;
return localRef;
instance = null;
}
if (newlyDisabled && reason != null) {
logger.log(Level.FINE, "Diagnostic telemetry disabled globally: " + reason);
}
closeQuietly(localRef, false);
}

/** Package-private lifecycle initialisation method for explicit configuration or unit testing. */
static synchronized void init(TelemetryConfiguration config, ClearcutTransport transport) {
static void init(TelemetryConfiguration config, ClearcutTransport transport) {
closeInstance();
if (globallyDisabled || config == null || !config.isEnabled() || transport == null) {
return;
}
instance = new TelemetryManager(new TelemetryBatcher(config, transport));
TelemetryManager candidate = new TelemetryManager(new TelemetryBatcher(config, transport));
TelemetryManager toClose;
boolean flushOld;
synchronized (TelemetryManager.class) {
if (globallyDisabled) {
toClose = candidate;
flushOld = false;
} else {
toClose = instance;
instance = candidate;
flushOld = true;
}
}
closeQuietly(toClose, flushOld);
}

/**
Expand Down Expand Up @@ -144,14 +178,21 @@ public static boolean isInitialized() {
}

/** Flushes pending buffered metrics and shuts down the shared instance. */
public static synchronized void closeInstance() {
TelemetryManager localRef = instance;
instance = null;
if (localRef == null) {
public static void closeInstance() {
TelemetryManager localRef;
synchronized (TelemetryManager.class) {
localRef = instance;
instance = null;
}
closeQuietly(localRef, true);
}

private static void closeQuietly(TelemetryManager manager, boolean flush) {
if (manager == null) {
return;
}
try {
localRef.close();
manager.batcher.close(flush);
} catch (Throwable t) {
logger.log(Level.FINE, "Error closing TelemetryManager instance", t);
}
Expand Down Expand Up @@ -317,23 +358,21 @@ public static String extractSqlState(Throwable t) {
return "";
}

/**
* Registers the JVM shutdown hook that flushes pending telemetry.
*
* <p>Only reached from the instance-creation critical section of {@link
* #getInstance(Properties)}, which already guarantees single execution, so no further guarding is
* needed here.
*/
/** Registers the JVM shutdown hook that flushes pending telemetry at most once per JVM. */
private static void registerShutdownHook() {
if (!SHUTDOWN_HOOK_REGISTERED.compareAndSet(false, true)) {
return;
}
try {
Runtime.getRuntime()
.addShutdownHook(
new Thread(
TelemetryManager::closeInstanceOnShutdown,
"bigquery-jdbc-telemetry-shutdown-hook"));
} catch (IllegalStateException e) {
// Thrown if the JVM is already in the process of shutting down
SHUTDOWN_HOOK_REGISTERED.set(false);
} catch (SecurityException e) {
SHUTDOWN_HOOK_REGISTERED.set(false);
logger.warning("SecurityManager prevented registering telemetry shutdown hook");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -414,4 +414,19 @@ public void testAllowUrlLogPathFalseBlocksUrlAndPropertiesLogPath(@TempDir Path
}
}
}

@Test
public void testDataSource_urlOptOutNotClobberedByDefaultDataSource() throws SQLException {
DataSource ds = new DataSource();
ds.setURL(
getUriOAuthToken()
.append("ProjectId", "MyBigQueryProject")
.append("EnableDiagnosticTelemetry", 0)
.toString());

try (Connection conn = ds.getConnection()) {
assertThat(conn.isClosed()).isFalse();
}
assertThat(TelemetryManager.isInitialized()).isFalse();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,11 @@ public void testParseDiagnosticTelemetryProperties() {
DataSource defaultDs = DataSource.fromUrl(urlWithoutTelemetry);
assertThat(defaultDs.getEnableDiagnosticTelemetry())
.isEqualTo(TelemetryPropertyUtility.DEFAULT_ENABLE_DIAGNOSTIC_TELEMETRY_VALUE);
assertThat(defaultDs.createProperties().getProperty("EnableDiagnosticTelemetry")).isNull();

defaultDs.setEnableDiagnosticTelemetry(true);
assertThat(defaultDs.createProperties().getProperty("EnableDiagnosticTelemetry"))
.isEqualTo("true");
}

@Test
Expand Down
Loading
Loading