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
31 changes: 22 additions & 9 deletions core/src/main/java/google/registry/bsa/BlockListFetcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,34 +66,47 @@ LazyBlockList fetch(BlockListType blockListType) {
}

LazyBlockList tryFetch(BlockListType blockListType) {
HttpsURLConnection connection = null;
boolean handedOff = false;
try {
URL dataUrl = new URL(blockListUrls.get(blockListType.name()));
logger.atInfo().log("Downloading from %s", dataUrl);
HttpsURLConnection connection =
(HttpsURLConnection) urlConnectionService.createConnection(dataUrl);
connection = (HttpsURLConnection) urlConnectionService.createConnection(dataUrl);
connection.setRequestMethod(HttpMethods.GET);
connection.setRequestProperty("Authorization", "Bearer " + credential.getAuthToken());
int code = connection.getResponseCode();
if (code != SC_OK) {
String errorDetails = "";
try (InputStream errorStream = connection.getErrorStream()) {
errorDetails = new String(ByteStreams.toByteArray(errorStream), UTF_8);
} catch (NullPointerException e) {
// No error message.
} catch (Exception e) {
if (errorStream != null) {
errorDetails = new String(ByteStreams.toByteArray(errorStream), UTF_8);
}
} catch (IOException e) {
errorDetails = "Failed to retrieve error message: " + e.getMessage();
}
String responseMessage;
try {
responseMessage = connection.getResponseMessage();
} catch (IOException e) {
responseMessage = "Failed to retrieve response message: " + e.getMessage();
}
throw new BsaException(
String.format(
"Status code: [%s], error: [%s], details: [%s]",
code, connection.getResponseMessage(), errorDetails),
/* retriable= */ true);
code, responseMessage, errorDetails),
BsaException.isRetriableHttpStatus(code));
}
return new LazyBlockList(blockListType, connection);
LazyBlockList blockList = new LazyBlockList(blockListType, connection);
handedOff = true;
return blockList;
} catch (IOException e) {
throw new BsaException(e, /* retriable= */ true);
} catch (GeneralSecurityException e) {
throw new BsaException(e, /* retriable= */ false);
} finally {
if (!handedOff && connection != null) {
connection.disconnect();
}
}
}

Expand Down
29 changes: 21 additions & 8 deletions core/src/main/java/google/registry/bsa/BsaDownloadAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import google.registry.bsa.BsaDiffCreator.BsaDiff;
import google.registry.bsa.api.BlockLabel;
import google.registry.bsa.api.BlockOrder;
import google.registry.bsa.api.BsaException;
import google.registry.bsa.api.BsaReportSender;
import google.registry.bsa.api.UnblockableDomain;
import google.registry.bsa.persistence.DownloadSchedule;
Expand Down Expand Up @@ -106,6 +107,14 @@ public void run() {
logger.atInfo().log("%s.", message);
emailSender.sendNotification(message, /* body= */ "");
}
} catch (BsaException e) {
if (e.isRetriable()) {
logger.atWarning().withCause(e).log("Transient failure downloading/processing BSA data.");
} else {
logger.atSevere().withCause(e).log(
"Non-retriable BSA error during download; manual intervention may be required.");
}
emailSender.sendNotification("BSA download aborted", getStackTraceAsString(e));
} catch (Throwable throwable) {
logger.atWarning().withCause(throwable).log("Failed to download and process BSA data.");
emailSender.sendNotification("BSA download aborted", getStackTraceAsString(throwable));
Expand Down Expand Up @@ -162,27 +171,31 @@ Void runWithinLock() {
// TODO(01/15/24): add email alert.
return null;
}
schedule.updateJobStage(DownloadStage.MAKE_ORDER_AND_LABEL_DIFF, actualChecksum);
schedule =
schedule.updateJobStage(DownloadStage.MAKE_ORDER_AND_LABEL_DIFF, actualChecksum);
}
// Fall through
case MAKE_ORDER_AND_LABEL_DIFF:
diff = diffCreator.createDiff(schedule, lazyIdnChecker.get());
// TODO(weiminyu): log the diff stats
gcsClient.writeOrderDiffs(schedule.jobName(), diff.getOrders());
gcsClient.writeLabelDiffs(schedule.jobName(), diff.getLabels());
schedule.updateJobStage(DownloadStage.APPLY_ORDER_AND_LABEL_DIFF);
schedule = schedule.updateJobStage(DownloadStage.APPLY_ORDER_AND_LABEL_DIFF);
// Fall through
case APPLY_ORDER_AND_LABEL_DIFF:
DownloadSchedule applySchedule = schedule;
try (Stream<BlockLabel> labels =
diff != null ? diff.getLabels() : gcsClient.readLabelDiffs(schedule.jobName())) {
diff != null ? diff.getLabels() : gcsClient.readLabelDiffs(applySchedule.jobName())) {
Stream<ImmutableList<BlockLabel>> batches = toBatches(labels, transactionBatchSize);
gcsClient.writeUnblockableDomains(
schedule.jobName(),
applySchedule.jobName(),
batches
.map(batch -> applyLabelDiff(batch, lazyIdnChecker.get(), schedule, clock.now()))
.map(
batch ->
applyLabelDiff(batch, lazyIdnChecker.get(), applySchedule, clock.now()))
.flatMap(ImmutableList::stream));
}
schedule.updateJobStage(DownloadStage.REPORT_START_OF_ORDER_PROCESSING);
schedule = schedule.updateJobStage(DownloadStage.REPORT_START_OF_ORDER_PROCESSING);
// Fall through
case REPORT_START_OF_ORDER_PROCESSING:
try (Stream<BlockOrder> orders = gcsClient.readOrderDiffs(schedule.jobName())) {
Expand All @@ -197,7 +210,7 @@ Void runWithinLock() {
logger.atInfo().log("No new or deleted orders in this round.");
}
}
schedule.updateJobStage(DownloadStage.UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS);
schedule = schedule.updateJobStage(DownloadStage.UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS);
// Fall through
case UPLOAD_UNBLOCKABLE_DOMAINS_FOR_NEW_ORDERS:
try (Stream<UnblockableDomain> unblockables =
Expand All @@ -216,7 +229,7 @@ Void runWithinLock() {
logger.atInfo().log("No changes in the set of unblockable domains in this round.");
}
}
schedule.updateJobStage(DownloadStage.REPORT_END_OF_ORDER_PROCESSING);
schedule = schedule.updateJobStage(DownloadStage.REPORT_END_OF_ORDER_PROCESSING);
// Fall through
case REPORT_END_OF_ORDER_PROCESSING:
try (Stream<BlockOrder> orders = gcsClient.readOrderDiffs(schedule.jobName())) {
Expand Down
15 changes: 12 additions & 3 deletions core/src/main/java/google/registry/bsa/BsaRefreshAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import com.google.common.collect.ImmutableList;
import com.google.common.flogger.FluentLogger;
import google.registry.bsa.api.BsaException;
import google.registry.bsa.api.BsaReportSender;
import google.registry.bsa.api.JsonSerializations;
import google.registry.bsa.api.UnblockableDomainChange;
Expand Down Expand Up @@ -91,6 +92,14 @@ public void run() {
logger.atInfo().log("%s.", message);
emailSender.sendNotification(message, /* body= */ "");
}
} catch (BsaException e) {
if (e.isRetriable()) {
logger.atWarning().withCause(e).log("Transient failure refreshing BSA data.");
} else {
logger.atSevere().withCause(e).log(
"Non-retriable BSA error during refresh; manual intervention may be required.");
}
emailSender.sendNotification("BSA refresh aborted", getStackTraceAsString(e));
} catch (Throwable throwable) {
logger.atWarning().withCause(throwable).log("Failed to refresh BSA data.");
emailSender.sendNotification("BSA refresh aborted", getStackTraceAsString(throwable));
Expand Down Expand Up @@ -129,14 +138,14 @@ Void runWithinLock() {
return null;
}
gcsClient.writeRefreshChanges(schedule.jobName(), blockabilityChanges.stream());
schedule.updateJobStage(RefreshStage.APPLY_CHANGES);
schedule = schedule.updateJobStage(RefreshStage.APPLY_CHANGES);
// Fall through
case APPLY_CHANGES:
try (Stream<UnblockableDomainChange> changes =
gcsClient.readRefreshChanges(schedule.jobName())) {
BatchedStreams.toBatches(changes, 500).forEach(refresher::applyUnblockableChanges);
}
schedule.updateJobStage(RefreshStage.UPLOAD_REMOVALS);
schedule = schedule.updateJobStage(RefreshStage.UPLOAD_REMOVALS);
// Fall through
case UPLOAD_REMOVALS:
try (Stream<UnblockableDomainChange> changes =
Expand All @@ -156,7 +165,7 @@ Void runWithinLock() {
logger.atInfo().log("No Unblockable domains to remove.");
}
}
schedule.updateJobStage(RefreshStage.UPLOAD_ADDITIONS);
schedule = schedule.updateJobStage(RefreshStage.UPLOAD_ADDITIONS);
// Fall through
case UPLOAD_ADDITIONS:
try (Stream<UnblockableDomainChange> changes =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,10 +195,22 @@ boolean uploadToBsa(ImmutableSortedSet<String> unavailableDomains, Instant runTi
logger.atInfo().log(
"Uploading unavailable domains list %s to %s with hash %s", filename, apiUrl, sha512Hash);
try (Response uploadResponse = client.newCall(request).execute()) {
String responseBody =
uploadResponse.body() == null ? "(none)" : uploadResponse.body().string();
if (!uploadResponse.isSuccessful()) {
String sanitizedResponseBody = responseBody.replace('\r', '_').replace('\n', '_');
logger.atSevere().log(
"Failed to upload unavailable domains to BSA: status code %d from server: %s",
uploadResponse.code(), sanitizedResponseBody);
response.setStatus(SC_INTERNAL_SERVER_ERROR);
response.setPayload(
String.format(
"BSA upload failed with status code %d: %s",
uploadResponse.code(), responseBody));
return false;
}
logger.atInfo().log(
"Received response with code %s from server: %s",
uploadResponse.code(),
uploadResponse.body() == null ? "(none)" : uploadResponse.body().string());
"Received response with code %s from server: %s", uploadResponse.code(), responseBody);
}
return true;
} catch (IOException e) {
Expand All @@ -216,6 +228,10 @@ private static String createFilename(Instant runTime) {
private ImmutableSortedSet<String> getUnavailableDomains(Instant runTime) {
// Get list of TLDs to process.
ImmutableSet<Tld> bsaEnabledTlds = getActivatedBsaTlds();
if (bsaEnabledTlds.isEmpty()) {
logger.atInfo().log("No activated BSA TLDs found.");
return ImmutableSortedSet.of();
}

logger.atInfo().log(
"Getting unavailable domains in TLDs: %s ...",
Expand All @@ -225,18 +241,16 @@ private ImmutableSortedSet<String> getUnavailableDomains(Instant runTime) {
new ImmutableSortedSet.Builder<>(Ordering.natural());

// Add domains on reserved lists to unavailable names list.
replicaTm()
.transact(
() -> {
for (Tld tld : bsaEnabledTlds) {
for (ReservedList reservedList : loadReservedLists(tld.getReservedListNames())) {
unavailableDomains.addAll(
reservedList.getReservedListEntries().keySet().stream()
.map(label -> toDomain(label, tld))
.collect(toImmutableSet()));
}
}
});
// Loaded outside replicaTm() because ReservedList.loadReservedLists() falls back to tm() on
// cache misses, which must not nest inside a replicaTm() transaction.
for (Tld tld : bsaEnabledTlds) {
for (ReservedList reservedList : loadReservedLists(tld.getReservedListNames())) {
unavailableDomains.addAll(
reservedList.getReservedListEntries().keySet().stream()
.map(label -> toDomain(label, tld))
.collect(toImmutableSet()));
}
}

// Add existing domains to unavailable names list, in batches so as to not time out on replica.
ImmutableSet<String> tldNames =
Expand Down
12 changes: 9 additions & 3 deletions core/src/main/java/google/registry/bsa/api/BsaCredential.java
Original file line number Diff line number Diff line change
Expand Up @@ -135,14 +135,20 @@ String fetchNewAuthToken() throws IOException, GeneralSecurityException {
String errorDetails;
try {
errorDetails = new String(getResponseBytes(connection), UTF_8);
} catch (Exception e) {
} catch (IOException e) {
errorDetails = "Failed to retrieve error message: " + e.getMessage();
}
String responseMessage;
try {
responseMessage = connection.getResponseMessage();
} catch (IOException e) {
responseMessage = "Failed to retrieve response message: " + e.getMessage();
}
throw new BsaException(
String.format(
"Status code: [%s], error: [%s], details: [%s]",
code, connection.getResponseMessage(), errorDetails),
/* retriable= */ true);
code, responseMessage, errorDetails),
BsaException.isRetriableHttpStatus(code));
}
// TODO: catch json syntax exception
@SuppressWarnings("unchecked")
Expand Down
15 changes: 15 additions & 0 deletions core/src/main/java/google/registry/bsa/api/BsaException.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@

package google.registry.bsa.api;

import static jakarta.servlet.http.HttpServletResponse.SC_REQUEST_TIMEOUT;

public class BsaException extends RuntimeException {

private static final int SC_TOO_MANY_REQUESTS = 429;

private final boolean retriable;

public BsaException(Throwable cause, boolean retriable) {
Expand All @@ -31,4 +35,15 @@ public BsaException(String message, boolean retriable) {
public boolean isRetriable() {
return this.retriable;
}

/**
* Returns whether an unsuccessful HTTP status code represents a transient failure that should be
* retried ({@code 408}, {@code 429}, or {@code 5xx}) rather than a permanent client/request error
* (such as {@code 400}, {@code 401}, {@code 403}, {@code 404}, or {@code 422}).
*/
public static boolean isRetriableHttpStatus(int statusCode) {
return statusCode == SC_REQUEST_TIMEOUT
|| statusCode == SC_TOO_MANY_REQUESTS
|| (statusCode >= 500 && statusCode < 600);
}
}
39 changes: 27 additions & 12 deletions core/src/main/java/google/registry/bsa/api/BsaReportSender.java
Original file line number Diff line number Diff line change
Expand Up @@ -87,41 +87,56 @@ public void removeUnblockableDomainsUpdates(String payload) {
}

Void trySendData(String urlString, String payload) {
HttpsURLConnection connection = null;
try {
URL url = new URL(urlString);
HttpsURLConnection connection =
(HttpsURLConnection) urlConnectionService.createConnection(url);
connection = (HttpsURLConnection) urlConnectionService.createConnection(url);
connection.setRequestMethod(HttpMethods.POST);
connection.setRequestProperty("Authorization", "Bearer " + credential.getAuthToken());
UrlConnectionUtils.setPayload(connection, payload.getBytes(UTF_8), CONTENT_TYPE.toString());
int code = connection.getResponseCode();
if (code != SC_OK && code != SC_ACCEPTED) {
String errorDetails = "";
try (InputStream errorStream = connection.getErrorStream()) {
errorDetails = new String(ByteStreams.toByteArray(errorStream), UTF_8);
} catch (NullPointerException e) {
// No error message.
} catch (Exception e) {
if (errorStream != null) {
errorDetails = new String(ByteStreams.toByteArray(errorStream), UTF_8);
}
} catch (IOException e) {
errorDetails = "Failed to retrieve error message: " + e.getMessage();
}
String responseMessage;
try {
responseMessage = connection.getResponseMessage();
} catch (IOException e) {
responseMessage = "Failed to retrieve response message: " + e.getMessage();
}
// TODO(b/318404541): sanitize errorDetails to prevent log injection attack.
throw new BsaException(
String.format(
"Status code: [%s], error: [%s], details: [%s]",
code, connection.getResponseMessage(), errorDetails),
/* retriable= */ true);
code, responseMessage, errorDetails),
BsaException.isRetriableHttpStatus(code));
}
try (InputStream errorStream = connection.getInputStream()) {
String responseMessage = new String(ByteStreams.toByteArray(errorStream), UTF_8);
logger.atInfo().log("Received response: [%s]", responseMessage);
} catch (Exception e) {
try (InputStream inputStream = connection.getInputStream()) {
if (inputStream != null) {
String responseMessage =
new String(ByteStreams.toByteArray(inputStream), UTF_8)
.replace('\r', '_')
.replace('\n', '_');
logger.atInfo().log("Received response: [%s]", responseMessage);
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
}
} catch (IOException e) {
logger.atInfo().withCause(e).log("Failed to retrieve response message.");
}
return null;
} catch (IOException e) {
throw new BsaException(e, /* retriable= */ true);
} catch (GeneralSecurityException e) {
throw new BsaException(e, /* retriable= */ false);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
Loading
Loading