Skip to content
Closed
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 @@ -292,13 +292,38 @@ static void setEnabledForTesting(@Nullable Boolean enabled) {
QueueImpl.setCloudTaskEnabledForTesting(enabled);
}

static void setSharedClientForTesting(CloudTasksClient client) {
sharedClient = client;
// The testing setters take CLIENT_INIT_LOCK so that a lazy getClient()/getV2Beta3Client() call
// already inside a slow create() (e.g. from an async task left over from a previous test) cannot
// overwrite the injected client after it has been set. A displaced client is shut down outside
// the lock with shutdownNow(), which releases its channel and threads and cancels any calls still
// in flight on it (close() would let them run to their deadline).
static void setSharedClientForTesting(@Nullable CloudTasksClient client) {
CloudTasksClient previous;
CLIENT_INIT_LOCK.lock();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Two edge cases worth tightening while we are touching these setters:

First, if the race described in the comment triggers, getClient() will have already assigned a real CloudTasksClient (backed by a live Netty channel and executor threads) to sharedClient right before setSharedClientForTesting acquires CLIENT_INIT_LOCK. Overwriting that reference without closing the displaced instance leaks its channel and background threads for the lifetime of the JVM; closing it outside the lock also ensures any stray caller fails fast locally rather than reaching cloudtasks.googleapis.com. (Worth marking both parameters @nullable as well to match setEnabledForTesting above.)

Second, getClient() (lines 644/688) and getV2Beta3Client() (lines 693/738) read the volatile field twice without a local variable (if (sharedClient == null) { ... } return sharedClient;). If tearDown() calls setSharedClientForTesting(null) between those two reads, getClient() can return null and NPE at the call site. Reading into a local client variable fixes the double-checked locking read.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed

try {
previous = sharedClient;
sharedClient = client;
} finally {
CLIENT_INIT_LOCK.unlock();
}
if (previous != null && previous != client) {
previous.shutdownNow();
}
}

static void setSharedV2Beta3ClientForTesting(
com.google.cloud.tasks.v2beta3.CloudTasksClient client) {
sharedV2Beta3Client = client;
com.google.cloud.tasks.v2beta3.@Nullable CloudTasksClient client) {
com.google.cloud.tasks.v2beta3.CloudTasksClient previous;
CLIENT_INIT_LOCK.lock();
try {
previous = sharedV2Beta3Client;
sharedV2Beta3Client = client;
} finally {
CLIENT_INIT_LOCK.unlock();
}
if (previous != null && previous != client) {
previous.shutdownNow();
}
}

static void setMetadataBaseUrlForTesting(String baseUrl) {
Expand Down Expand Up @@ -628,101 +653,110 @@ static String getValidAccessToken() throws IOException {

static CloudTasksClient getClient() {
// NOMUTANTS -- production gRPC client initialization requires live credentials
if (sharedClient == null) {
// Read the volatile field once so a concurrent reset cannot make this return null.
CloudTasksClient client = sharedClient;
if (client == null) {
CLIENT_INIT_LOCK.lock();
try {
if (sharedClient == null) {
try {
sharedClient = CloudTasksClient.create();
} catch (Exception directEx) {
logger.log(
Level.FINE,
"CloudTasksClient.create() failed, attempting custom credentials",
directEx);
try {
CredentialsProvider credentialsProvider =
() -> {
try {
String token = getValidAccessToken();
// AccessToken's constructor only accepts java.util.Date (not Instant),
// and ErrorProne's JavaUtilDate check requires Date.from(Instant).
return GoogleCredentials.create(
new AccessToken(token, Date.from(Instant.ofEpochMilli(cachedTokenExpiry))));
} catch (Exception e) {
throw new IOException("Failed to refresh access token", e);
}
};
CloudTasksSettings settings =
CloudTasksSettings.newBuilder()
.setCredentialsProvider(credentialsProvider)
.build();
sharedClient = CloudTasksClient.create(settings);
} catch (Exception fallbackEx) {
logger.log(Level.SEVERE, "Failed to initialize CloudTasksClient", fallbackEx);
throw new IllegalStateException(
"Failed to initialize CloudTasksClient: direct="
+ directEx.getMessage()
+ ", fallback="
+ fallbackEx.getMessage(),
fallbackEx);
}
}
client = sharedClient;
if (client == null) {
client = createCloudTasksClient();
sharedClient = client;
}
} finally {
CLIENT_INIT_LOCK.unlock();
}
}
return sharedClient;
return client;
}

private static CloudTasksClient createCloudTasksClient() {
try {
return CloudTasksClient.create();
} catch (Exception directEx) {
logger.log(
Level.FINE, "CloudTasksClient.create() failed, attempting custom credentials", directEx);
try {
CredentialsProvider credentialsProvider =
() -> {
try {
String token = getValidAccessToken();
// AccessToken's constructor only accepts java.util.Date (not Instant),
// and ErrorProne's JavaUtilDate check requires Date.from(Instant).
return GoogleCredentials.create(
new AccessToken(token, Date.from(Instant.ofEpochMilli(cachedTokenExpiry))));
} catch (Exception e) {
throw new IOException("Failed to refresh access token", e);
}
};
CloudTasksSettings settings =
CloudTasksSettings.newBuilder().setCredentialsProvider(credentialsProvider).build();
return CloudTasksClient.create(settings);
} catch (Exception fallbackEx) {
logger.log(Level.SEVERE, "Failed to initialize CloudTasksClient", fallbackEx);
throw new IllegalStateException(
"Failed to initialize CloudTasksClient: direct="
+ directEx.getMessage()
+ ", fallback="
+ fallbackEx.getMessage(),
fallbackEx);
}
}
}

static com.google.cloud.tasks.v2beta3.CloudTasksClient getV2Beta3Client() {
// NOMUTANTS -- production gRPC client initialization requires live credentials
if (sharedV2Beta3Client == null) {
// Read the volatile field once so a concurrent reset cannot make this return null.
com.google.cloud.tasks.v2beta3.CloudTasksClient client = sharedV2Beta3Client;
if (client == null) {
CLIENT_INIT_LOCK.lock();
try {
if (sharedV2Beta3Client == null) {
try {
sharedV2Beta3Client = com.google.cloud.tasks.v2beta3.CloudTasksClient.create();
} catch (Exception directEx) {
logger.log(
Level.FINE,
"v2beta3 CloudTasksClient.create() failed, attempting custom credentials",
directEx);
try {
CredentialsProvider credentialsProvider =
() -> {
try {
String token = getValidAccessToken();
return GoogleCredentials.create(
new AccessToken(
token, Date.from(Instant.ofEpochMilli(cachedTokenExpiry))));
} catch (Exception e) {
throw new IOException("Failed to refresh access token", e);
}
};
com.google.cloud.tasks.v2beta3.CloudTasksSettings settings =
com.google.cloud.tasks.v2beta3.CloudTasksSettings.newBuilder()
.setCredentialsProvider(credentialsProvider)
.build();
sharedV2Beta3Client =
com.google.cloud.tasks.v2beta3.CloudTasksClient.create(settings);
} catch (Exception fallbackEx) {
logger.log(
Level.SEVERE, "Failed to initialize v2beta3 CloudTasksClient", fallbackEx);
throw new IllegalStateException(
"Failed to initialize v2beta3 CloudTasksClient: direct="
+ directEx.getMessage()
+ ", fallback="
+ fallbackEx.getMessage(),
fallbackEx);
}
}
client = sharedV2Beta3Client;
if (client == null) {
client = createV2Beta3Client();
sharedV2Beta3Client = client;
}
} finally {
CLIENT_INIT_LOCK.unlock();
}
}
return sharedV2Beta3Client;
return client;
}

private static com.google.cloud.tasks.v2beta3.CloudTasksClient createV2Beta3Client() {
try {
return com.google.cloud.tasks.v2beta3.CloudTasksClient.create();
} catch (Exception directEx) {
logger.log(
Level.FINE,
"v2beta3 CloudTasksClient.create() failed, attempting custom credentials",
directEx);
try {
CredentialsProvider credentialsProvider =
() -> {
try {
String token = getValidAccessToken();
return GoogleCredentials.create(
new AccessToken(token, Date.from(Instant.ofEpochMilli(cachedTokenExpiry))));
} catch (Exception e) {
throw new IOException("Failed to refresh access token", e);
}
};
com.google.cloud.tasks.v2beta3.CloudTasksSettings settings =
com.google.cloud.tasks.v2beta3.CloudTasksSettings.newBuilder()
.setCredentialsProvider(credentialsProvider)
.build();
return com.google.cloud.tasks.v2beta3.CloudTasksClient.create(settings);
} catch (Exception fallbackEx) {
logger.log(Level.SEVERE, "Failed to initialize v2beta3 CloudTasksClient", fallbackEx);
throw new IllegalStateException(
"Failed to initialize v2beta3 CloudTasksClient: direct="
+ directEx.getMessage()
+ ", fallback="
+ fallbackEx.getMessage(),
fallbackEx);
}
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
Expand All @@ -94,6 +95,8 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
Expand All @@ -103,6 +106,8 @@
/** Unit tests for {@link CloudTasksClientWrapper} and {@link TaskProcessor} v2 gRPC paths. */
@RunWith(JUnit4.class)
public class CloudTasksClientWrapperTest {
private static final Logger logger =
Logger.getLogger(CloudTasksClientWrapperTest.class.getName());
private static final String TEST_PROJECT = "test-proj";
private static final String TEST_LOCATION = "us-central1";
private static final String TEST_TOKEN = "fake-oauth-token";
Expand Down Expand Up @@ -356,19 +361,51 @@ public boolean awaitTermination(long duration, TimeUnit unit) {

@After
public void tearDown() {
CloudTasksClientWrapper.setEnabledForTesting(null);
CloudTasksClientWrapper.setSharedClientForTesting(null);
CloudTasksClientWrapper.setSharedV2Beta3ClientForTesting(null);
CloudTasksClientWrapper.setProjectIdForTesting(null);
CloudTasksClientWrapper.setLocationForTesting(null);
CloudTasksClientWrapper.setAccessTokenForTesting(null, 0);
CloudTasksClientWrapper.setMetadataBaseUrlForTesting(null);
CloudTasksClientWrapper.setCredentialsTokenForTesting(null);
// Fire-and-forget dispatches (e.g. the queue.add() fast path) run on the shared static
// IO_EXECUTOR. Let them finish while the stub clients are still installed; otherwise they can
// lazily build a real CloudTasksClient and leak into the next test.
try {
awaitIoExecutorIdle(Duration.ofSeconds(10));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.log(Level.WARNING, "Interrupted while waiting for IO_EXECUTOR to go idle", e);
} finally {
CloudTasksClientWrapper.setEnabledForTesting(null);
CloudTasksClientWrapper.setSharedClientForTesting(null);
CloudTasksClientWrapper.setSharedV2Beta3ClientForTesting(null);
CloudTasksClientWrapper.setProjectIdForTesting(null);
CloudTasksClientWrapper.setLocationForTesting(null);
CloudTasksClientWrapper.setAccessTokenForTesting(null, 0);
CloudTasksClientWrapper.setMetadataBaseUrlForTesting(null);
CloudTasksClientWrapper.setCredentialsTokenForTesting(null);

if (server != null) {
server.stop(0);
if (server != null) {
server.stop(0);
}
helper.tearDown();
}
}

private static void awaitIoExecutorIdle(Duration timeout) throws InterruptedException {
if (!(CloudTasksClientWrapper.IO_EXECUTOR instanceof ThreadPoolExecutor)) {
return;
}
ThreadPoolExecutor pool = (ThreadPoolExecutor) CloudTasksClientWrapper.IO_EXECUTOR;
long deadline = System.nanoTime() + timeout.toNanos();
while (pool.getActiveCount() > 0 || !pool.getQueue().isEmpty()) {
if (System.nanoTime() >= deadline) {
logger.warning(
"IO_EXECUTOR still busy after "
+ timeout
+ " (active="
+ pool.getActiveCount()
+ ", queued="
+ pool.getQueue().size()
+ "); resetting CloudTasksClientWrapper state anyway");
return;
}
Thread.sleep(10);
}
helper.tearDown();
}

@Test
Expand Down
6 changes: 0 additions & 6 deletions e2etests/devappservertests/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,6 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-utils</artifactId>
Expand Down
6 changes: 0 additions & 6 deletions e2etests/stagingtests/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,6 @@
<artifactId>appengine-tools-sdk</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>2.0.2-beta</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-apis-dev</artifactId>
Expand Down