mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(backup): publish BACKUP_JOB_COMPLETED to the vault's SNS topic (#5623)
* fix(backup): publish BACKUP_JOB_COMPLETED to the vault's SNS topic PutBackupVaultNotifications stored the configuration but job completion never read it, so a subscriber received nothing. When a backup job completes in a vault whose BackupVaultEvents include BACKUP_JOB_COMPLETED, publish one message to the configured SNSTopicArn after the job and recovery point are stored. A failed publish is logged and never undoes the completion. Other events remain stored-only; docs say which. * fix(backup): log the exception when a BACKUP_JOB_COMPLETED publish fails * test(backup): import log-capture classes instead of qualifying them inline * fix(backup): notify only the vault a job started in, not a same-name replacement completeJob looked the vault up by name at completion time, so a job whose vault was deleted and recreated mid-run published BACKUP_JOB_COMPLETED to the replacement vault's topic. Pin the vault's sub-resource key (which carries its creation date) when the job starts and read the notification configuration through it; a deleted vault's configuration goes with it, so nothing is sent. * fix(backup): match AWS's BACKUP_JOB_COMPLETED message and pin vaults by id The published notification now follows AWS's documented "Backup job completed" example: the body ends at the BackupJob ID with no vault name, and the publish carries the EventType, State, AccountId, Id and StartTime message attributes that subscription filter policies match on. Vault sub-resources and in-flight jobs were bound to a vault by its creation second, so a vault deleted and recreated within the same second shared a key with its predecessor and a running job could notify the replacement. Each vault now gets a random FlociVaultId at creation and the sub-resource key uses it; vaults stored before the field existed fall back to the creation date, so their stored configuration is still found. The id is persisted but stripped from DescribeBackupVault and ListBackupVaults responses. * test(backup): spell out the RequestSpecification type instead of var
This commit is contained in:
1 parent
007744b925
commit
c23641457a
5 files changed
+277
-23
No files matched your search
@@ -1,17 +1,28 @@
|
||||
package io.github.hectorvent.floci.services.backup;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.json.JsonPath;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.logging.Handler;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogRecord;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Integration tests for AWS Backup via REST JSON protocol.
|
||||
@@ -1421,4 +1432,179 @@ class BackupIntegrationTest {
|
||||
awaitJobState(OTHER_ACCOUNT_AUTH, jid, "ABORTED");
|
||||
}
|
||||
|
||||
|
||||
// ── Vault notifications: delivery ──────────────────────────────────────────
|
||||
|
||||
private static String createQueue(String name) {
|
||||
return given().contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateQueue").formParam("QueueName", name)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("CreateQueueResponse.CreateQueueResult.QueueUrl");
|
||||
}
|
||||
|
||||
/** A topic with {@code queueUrl} subscribed, so what SNS delivers can be read back from SQS. */
|
||||
private static String topicDeliveringTo(String name, String queueUrl) {
|
||||
return topicDeliveringTo(name, queueUrl, null);
|
||||
}
|
||||
|
||||
/** As above, with the subscription filtered by {@code filterPolicy} when it is non-null. */
|
||||
private static String topicDeliveringTo(String name, String queueUrl, String filterPolicy) {
|
||||
String topicArn = given().contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateTopic").formParam("Name", name)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("CreateTopicResponse.CreateTopicResult.TopicArn");
|
||||
RequestSpecification subscribe = given().contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "Subscribe").formParam("TopicArn", topicArn)
|
||||
.formParam("Protocol", "sqs").formParam("Endpoint", queueUrl);
|
||||
if (filterPolicy != null) {
|
||||
subscribe = subscribe.formParam("Attributes.entry.1.key", "FilterPolicy")
|
||||
.formParam("Attributes.entry.1.value", filterPolicy);
|
||||
}
|
||||
subscribe.when().post("/").then().statusCode(200);
|
||||
return topicArn;
|
||||
}
|
||||
|
||||
private static String receiveBody(String queueUrl) {
|
||||
return given().contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "ReceiveMessage").formParam("QueueUrl", queueUrl)
|
||||
.formParam("MaxNumberOfMessages", "1")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("ReceiveMessageResponse.ReceiveMessageResult.Message.Body");
|
||||
}
|
||||
|
||||
private static String startJobInNotifiedVault(String vault, String topicArn, String event) {
|
||||
given().header("Authorization", AUTH).contentType("application/json").body("{}")
|
||||
.when().put("/backup-vaults/" + vault).then().statusCode(200);
|
||||
given().header("Authorization", AUTH).contentType("application/json")
|
||||
.body("{\"SNSTopicArn\":\"%s\",\"BackupVaultEvents\":[\"%s\"]}".formatted(topicArn, event))
|
||||
.when().put("/backup-vaults/" + vault + "/notification-configuration").then().statusCode(204);
|
||||
return given().header("Authorization", AUTH).contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"BackupVaultName": "%s",
|
||||
"ResourceArn": "%s",
|
||||
"IamRoleArn": "%s"
|
||||
}
|
||||
""".formatted(vault, RESOURCE_ARN, IAM_ROLE))
|
||||
.when().put("/backup-jobs").then().statusCode(200).extract().path("BackupJobId");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(170)
|
||||
void aCompletedJobIsPublishedOnlyToAVaultThatAskedForBackupJobCompleted() {
|
||||
String quietQueue = createQueue("backup-notify-quiet-queue");
|
||||
String quietTopic = topicDeliveringTo("backup-notify-quiet-topic", quietQueue);
|
||||
String notifiedQueue = createQueue("backup-notify-queue");
|
||||
// Filtered on the attributes AWS's "Backup job completed" example carries: a publish
|
||||
// without them is dropped by SNS and never reaches the queue.
|
||||
String notifiedTopic = topicDeliveringTo("backup-notify-topic", notifiedQueue,
|
||||
"{\"EventType\":[\"BACKUP_JOB\"],\"State\":[\"COMPLETED\"]}");
|
||||
|
||||
// The quiet vault's job is started first. Completions run on one scheduler thread in
|
||||
// start order, so by the time the notified vault's message has arrived, any publish
|
||||
// the quiet vault's completion was going to make has already been made.
|
||||
String quietJob = startJobInNotifiedVault("notify-quiet-vault", quietTopic, "BACKUP_JOB_FAILED");
|
||||
String jid = startJobInNotifiedVault("notify-vault", notifiedTopic, "BACKUP_JOB_COMPLETED");
|
||||
|
||||
String[] body = new String[1];
|
||||
await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100))
|
||||
.until(() -> (body[0] = receiveBody(notifiedQueue)) != null && !body[0].isEmpty());
|
||||
|
||||
awaitJobCompleted(jid);
|
||||
String rpArn = given().header("Authorization", AUTH)
|
||||
.when().get("/backup-jobs/" + jid).then().statusCode(200)
|
||||
.extract().path("RecoveryPointArn");
|
||||
|
||||
JsonPath envelope = new JsonPath(body[0]);
|
||||
assertEquals(notifiedTopic, envelope.getString("TopicArn"));
|
||||
assertEquals("Notification from AWS Backup", envelope.getString("Subject"));
|
||||
// AWS's documented body, which ends at the job ID and does not name the vault.
|
||||
assertEquals("An AWS Backup job was completed successfully. Recovery point ARN: " + rpArn
|
||||
+ ". Resource ARN : " + RESOURCE_ARN + ". BackupJob ID : " + jid, envelope.getString("Message"));
|
||||
long created = given().header("Authorization", AUTH)
|
||||
.when().get("/backup-jobs/" + jid).then().statusCode(200)
|
||||
.extract().jsonPath().getLong("CreationDate");
|
||||
assertEquals(Map.of(
|
||||
"EventType", Map.of("Type", "String", "Value", "BACKUP_JOB"),
|
||||
"State", Map.of("Type", "String", "Value", "COMPLETED"),
|
||||
"AccountId", Map.of("Type", "String", "Value", "000000000000"),
|
||||
"Id", Map.of("Type", "String", "Value", jid),
|
||||
"StartTime", Map.of("Type", "String", "Value", Instant.ofEpochSecond(created).toString())),
|
||||
envelope.getMap("MessageAttributes"));
|
||||
|
||||
awaitJobCompleted(quietJob);
|
||||
assertThat(receiveBody(quietQueue), anyOf(nullValue(), emptyString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(171)
|
||||
void aFailedPublishIsLoggedWithItsStackTraceAndDoesNotUndoTheJob() {
|
||||
List<LogRecord> records = new CopyOnWriteArrayList<>();
|
||||
Handler capture = new Handler() {
|
||||
@Override public void publish(LogRecord r) { records.add(r); }
|
||||
@Override public void flush() { }
|
||||
@Override public void close() { }
|
||||
};
|
||||
Logger log = Logger.getLogger(BackupService.class.getName());
|
||||
log.addHandler(capture);
|
||||
try {
|
||||
String missingTopic = "arn:aws:sns:us-east-1:000000000000:backup-notify-no-such-topic";
|
||||
String jid = startJobInNotifiedVault("notify-broken-vault", missingTopic, "BACKUP_JOB_COMPLETED");
|
||||
awaitJobCompleted(jid);
|
||||
await().atMost(Duration.ofSeconds(10)).until(() -> records.stream()
|
||||
.anyMatch(r -> r.getLevel().intValue() >= Level.WARNING.intValue()
|
||||
&& String.valueOf(r.getMessage()).contains("BACKUP_JOB_COMPLETED")));
|
||||
assertThat("the warning carries the exception, not just its message",
|
||||
records.stream().filter(r -> String.valueOf(r.getMessage()).contains("BACKUP_JOB_COMPLETED"))
|
||||
.allMatch(r -> r.getThrown() != null));
|
||||
} finally {
|
||||
log.removeHandler(capture);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(172)
|
||||
void aJobWhoseVaultWasReplacedDoesNotNotifyTheReplacement() {
|
||||
String replacementQueue = createQueue("backup-notify-replacement-queue");
|
||||
String replacementTopic = topicDeliveringTo("backup-notify-replacement-topic", replacementQueue);
|
||||
String sentinelQueue = createQueue("backup-notify-sentinel-queue");
|
||||
String sentinelTopic = topicDeliveringTo("backup-notify-sentinel-topic", sentinelQueue);
|
||||
String vault = "notify-replaced-vault";
|
||||
|
||||
// No waiting for the clock: the original and its replacement are normally created in
|
||||
// the same second, and must still be told apart.
|
||||
given().header("Authorization", AUTH).contentType("application/json").body("{}")
|
||||
.when().put("/backup-vaults/" + vault).then().statusCode(200);
|
||||
// The incarnation id is Floci-internal and must not leak into the AWS response.
|
||||
given().header("Authorization", AUTH)
|
||||
.when().get("/backup-vaults/" + vault).then().statusCode(200)
|
||||
.body("$", not(hasKey("FlociVaultId")));
|
||||
given().header("Authorization", AUTH)
|
||||
.when().get("/backup-vaults/").then().statusCode(200)
|
||||
.body(not(containsString("FlociVaultId")));
|
||||
|
||||
String oldJob = given().header("Authorization", AUTH).contentType("application/json")
|
||||
.body("""
|
||||
{"BackupVaultName": "%s", "ResourceArn": "%s", "IamRoleArn": "%s"}
|
||||
""".formatted(vault, RESOURCE_ARN, IAM_ROLE))
|
||||
.when().put("/backup-jobs").then().statusCode(200).extract().path("BackupJobId");
|
||||
given().header("Authorization", AUTH)
|
||||
.when().delete("/backup-vaults/" + vault).then().statusCode(204);
|
||||
// Recreates the name and points it at a topic the old job must never reach.
|
||||
startJobInNotifiedVault(vault, replacementTopic, "BACKUP_JOB_COMPLETED");
|
||||
// Completions run in start order on one thread: once this one is delivered, the
|
||||
// old job's completion, and any publish it was going to make, has already happened.
|
||||
startJobInNotifiedVault("notify-sentinel-vault", sentinelTopic, "BACKUP_JOB_COMPLETED");
|
||||
|
||||
await().atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(100))
|
||||
.until(() -> { String b = receiveBody(sentinelQueue); return b != null && !b.isEmpty(); });
|
||||
awaitJobCompleted(oldJob);
|
||||
|
||||
// The replacement's own job does publish; the old job must not have published too.
|
||||
String first = receiveBody(replacementQueue);
|
||||
assertThat(first, not(containsString("BackupJob ID : " + oldJob)));
|
||||
String second = receiveBody(replacementQueue);
|
||||
assertThat(second == null ? "" : second, not(containsString("BackupJob ID : " + oldJob)));
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user