-
Notifications
You must be signed in to change notification settings - Fork 86
[PLUGIN-1808] Retry policy to service account for 5xx errors for bigquery plugin #1544
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
AnkitCLI
merged 1 commit into
data-integrations:develop
from
cloudsufi:AddingRetryWithFailsafe
Jul 8, 2025
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 49 additions & 0 deletions
49
src/main/java/io/cdap/plugin/gcp/common/ServerErrorException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| /* | ||
| * Copyright © 2025 Cask Data, Inc. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); you may not | ||
| * use this file except in compliance with the License. You may obtain a copy of | ||
| * the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
| * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
| * License for the specific language governing permissions and limitations under | ||
| * the License. | ||
| */ | ||
|
|
||
| package io.cdap.plugin.gcp.common; | ||
|
|
||
| /** | ||
| * Exception indicating a server-side error (HTTP 5xx). | ||
| * <p> | ||
| * This exception is intended to be used when a server responds with an HTTP 5xx status code, | ||
| * which typically indicates temporary unavailability or failure on the server's part. | ||
| * It can be used to trigger retries in retry frameworks like Failsafe. | ||
| */ | ||
| public class ServerErrorException extends RuntimeException { | ||
| private final int statusCode; | ||
|
|
||
| /** | ||
| * Constructs a new {@code ServerErrorException} with the given status code and message. | ||
| * | ||
| * @param statusCode the HTTP status code (should be in the 5xx range) | ||
| * @param message the detail message explaining the error | ||
| * @param cause the original cause of the error | ||
| */ | ||
| public ServerErrorException(int statusCode, String message, Throwable cause) { | ||
| super("Server error [" + statusCode + "]: " + message, cause); | ||
| this.statusCode = statusCode; | ||
| } | ||
|
|
||
| /** | ||
| * Returns the HTTP status code associated with this server error. | ||
| * | ||
| * @return the 5xx HTTP status code that triggered this exception | ||
| */ | ||
| public int getStatusCode() { | ||
| return statusCode; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -21,16 +21,24 @@ | |
| import com.google.bigtable.repackaged.com.google.gson.Gson; | ||
| import com.google.cloud.hadoop.util.AccessTokenProvider; | ||
| import com.google.cloud.hadoop.util.CredentialFactory; | ||
| import io.cdap.cdap.api.exception.ErrorCategory; | ||
| import io.cdap.cdap.api.exception.ErrorCategory.ErrorCategoryEnum; | ||
| import com.google.common.annotations.VisibleForTesting; | ||
| import dev.failsafe.Failsafe; | ||
| import dev.failsafe.FailsafeException; | ||
| import dev.failsafe.RetryPolicy; | ||
| import io.cdap.cdap.api.exception.ErrorType; | ||
| import io.cdap.cdap.api.exception.ErrorUtils; | ||
| import io.cdap.plugin.gcp.common.GCPErrorDetailsProviderUtil; | ||
| import io.cdap.plugin.gcp.common.GCPUtils; | ||
| import io.cdap.plugin.gcp.common.ServerErrorException; | ||
| import org.apache.hadoop.conf.Configuration; | ||
| import org.apache.http.HttpStatus; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import java.io.IOException; | ||
| import java.time.Duration; | ||
| import java.time.Instant; | ||
| import java.util.Date; | ||
| import java.util.regex.Pattern; | ||
| import java.util.stream.Collectors; | ||
| import java.util.stream.Stream; | ||
|
|
||
|
|
@@ -43,19 +51,65 @@ public class ServiceAccountAccessTokenProvider implements AccessTokenProvider { | |
| private Configuration conf; | ||
| private GoogleCredentials credentials; | ||
| private static final Gson GSON = new Gson(); | ||
| private static final Logger LOG = LoggerFactory.getLogger(ServiceAccountAccessTokenProvider.class); | ||
| public static final int DEFAULT_INITIAL_RETRY_DURATION_SECONDS = 5; | ||
| public static final int DEFAULT_MAX_RETRY_COUNT = 5; | ||
| public static final int DEFAULT_MAX_RETRY_DURATION_SECONDS = 80; | ||
| private static final RetryPolicy<Object> RETRY_POLICY = createRetryPolicy(); | ||
| private static final Pattern SERVER_ERROR_PATTERN = Pattern.compile("Unexpected Error code 5\\d{2} trying to get " + | ||
| "security access token from Compute Engine metadata for the default service account.*"); | ||
|
|
||
| @VisibleForTesting | ||
| @Override | ||
| public AccessToken getAccessToken() { | ||
| try { | ||
| com.google.auth.oauth2.AccessToken token = getCredentials().getAccessToken(); | ||
| if (token == null || token.getExpirationTime().before(Date.from(Instant.now()))) { | ||
| refresh(); | ||
| token = getCredentials().getAccessToken(); | ||
| try { | ||
| return Failsafe.with(RETRY_POLICY).get(() -> { | ||
| com.google.auth.oauth2.AccessToken token = retrieveAccessToken(); | ||
| if (token == null || token.getExpirationTime().before(Date.from(Instant.now()))) { | ||
| refresh(); | ||
| token = retrieveAccessToken(); | ||
| } | ||
| return new AccessToken(token.getTokenValue(), token.getExpirationTime().getTime()); | ||
| }); | ||
| } catch (FailsafeException e) { | ||
| Throwable t = e.getCause() != null ? e.getCause() : e; | ||
| ErrorType errorType = (t instanceof ServerErrorException) ? ErrorType.SYSTEM : ErrorType.UNKNOWN; | ||
| throw GCPErrorDetailsProviderUtil.getHttpResponseExceptionDetailsFromChain( | ||
| e, "Unable to get service account access token after retries.", errorType, true, | ||
itsankit-google marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| GCPUtils.GCE_METADATA_SERVER_ERROR_SUPPORTED_DOC_URL | ||
| ); | ||
| } | ||
| return new AccessToken(token.getTokenValue(), token.getExpirationTime().getTime()); | ||
| } | ||
|
|
||
| private static RetryPolicy<Object> createRetryPolicy() { | ||
| return RetryPolicy.builder() | ||
| .handle(ServerErrorException.class) | ||
| .withBackoff(Duration.ofSeconds(DEFAULT_INITIAL_RETRY_DURATION_SECONDS), | ||
| Duration.ofSeconds(DEFAULT_MAX_RETRY_DURATION_SECONDS)) | ||
| .withMaxRetries(DEFAULT_MAX_RETRY_COUNT) | ||
| .onRetry(event -> LOG.debug("Retry attempt {} due to {}", event.getAttemptCount(), event.getLastException(). | ||
| getMessage())) | ||
| .onSuccess(event -> LOG.debug("Access Token Fetched Successfully.")) | ||
| .onRetriesExceeded( | ||
| event -> LOG.error("Unable to get service account access token after {} retries.", event.getAttemptCount() - 1)) | ||
| .build(); | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| static boolean isServerError(IOException e) { | ||
itsankit-google marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| String msg = e.getMessage(); | ||
| return msg != null && SERVER_ERROR_PATTERN.matcher(msg).matches(); | ||
| } | ||
|
|
||
| com.google.auth.oauth2.AccessToken retrieveAccessToken() throws IOException { | ||
| try { | ||
| return getCredentials().getAccessToken(); | ||
| } catch (IOException e) { | ||
| throw ErrorUtils.getProgramFailureException(new ErrorCategory(ErrorCategoryEnum.PLUGIN), | ||
| "Unable to get service account access token.", e.getMessage(), ErrorType.UNKNOWN, true, e); | ||
| if (isServerError(e)) { | ||
| throw new ServerErrorException(HttpStatus.SC_SERVICE_UNAVAILABLE, "Server error while fetching access token: " | ||
itsankit-google marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| + e.getMessage(), e); | ||
| } | ||
| throw e; | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -64,9 +118,13 @@ public void refresh() throws IOException { | |
| try { | ||
| getCredentials().refresh(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should also add retries on
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. added |
||
| } catch (IOException e) { | ||
| throw ErrorUtils.getProgramFailureException(new ErrorCategory(ErrorCategoryEnum.PLUGIN), | ||
| "Unable to refresh service account access token.", e.getMessage(), | ||
| ErrorType.UNKNOWN, true, e); | ||
| if (isServerError(e)) { | ||
| throw new ServerErrorException(HttpStatus.SC_SERVICE_UNAVAILABLE, "Server error during refresh: " + | ||
| e.getMessage(), e); | ||
| } | ||
| throw GCPErrorDetailsProviderUtil.getHttpResponseExceptionDetailsFromChain( | ||
| e, "Unable to refresh service account access token.", ErrorType.UNKNOWN, true, | ||
| GCPUtils.GCE_METADATA_SERVER_ERROR_SUPPORTED_DOC_URL); | ||
| } | ||
| } | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.