mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(cloudformation): provision CloudWatch log streams (#3869)
* feat(cloudformation): provision CloudWatch log streams * fix(cloudformation): preserve conditional log stream name omission --------- Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com>
This commit is contained in:
1 parent
c2611038a4
commit
0142d443ac
7 files changed
+1298
-1
No files matched your search
+270
@@ -0,0 +1,270 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Output;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Parameter;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
|
||||
import software.amazon.awssdk.services.cloudwatchlogs.model.InputLogEvent;
|
||||
import software.amazon.awssdk.services.cloudwatchlogs.model.LogStream;
|
||||
import software.amazon.awssdk.services.cloudwatchlogs.model.OutputLogEvent;
|
||||
import software.amazon.awssdk.services.cloudwatchlogs.model.ResourceNotFoundException;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DisplayName("CloudFormation AWS::Logs::LogStream")
|
||||
class CloudFormationLogStreamTest {
|
||||
|
||||
private static CloudFormationClient cfn;
|
||||
private static CloudWatchLogsClient logs;
|
||||
private String stackName;
|
||||
private boolean stackCreated;
|
||||
private final List<String> logGroups = new ArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void clients() {
|
||||
cfn = TestFixtures.cloudFormationClient();
|
||||
logs = TestFixtures.cloudWatchLogsClient();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
stackName = TestFixtures.uniqueName("compat-cfn-log-stream");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() throws InterruptedException {
|
||||
try {
|
||||
deleteStack();
|
||||
} finally {
|
||||
for (String group : logGroups) {
|
||||
try {
|
||||
logs.deleteLogGroup(r -> r.logGroupName(group));
|
||||
} catch (ResourceNotFoundException ignored) {
|
||||
// Stack rollback may already have removed a group created by the template.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void closeClients() {
|
||||
cfn.close();
|
||||
logs.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsWritableStreamFromGroupReferenceAndDeletesItFromRetainedGroup() throws InterruptedException {
|
||||
String group = "/test/" + stackName;
|
||||
logGroups.add(group);
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Group": {
|
||||
"Type": "AWS::Logs::LogGroup",
|
||||
"DeletionPolicy": "Retain",
|
||||
"Properties": {"LogGroupName": "%s"}
|
||||
},
|
||||
"Stream": {
|
||||
"Type": "AWS::Logs::LogStream",
|
||||
"Properties": {
|
||||
"LogGroupName": {"Ref": "Group"},
|
||||
"LogStreamName": "application"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {"StreamRef": {"Value": {"Ref": "Stream"}}}
|
||||
}
|
||||
""".formatted(group);
|
||||
|
||||
createStack(template, List.of());
|
||||
assertIdentity("application");
|
||||
assertThat(streamNames(group)).containsExactly("application");
|
||||
assertWritable(group, output(), "created through CloudFormation");
|
||||
|
||||
deleteStack();
|
||||
assertThat(streamNames(group))
|
||||
.as("the retained group survives, but its CloudFormation-managed stream is deleted")
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void movingNamedStreamToAnotherGroupRemovesTheOldStreamAndPreservesUnrelatedStreams()
|
||||
throws InterruptedException {
|
||||
String firstGroup = createLogGroup("first");
|
||||
String secondGroup = createLogGroup("second");
|
||||
logs.createLogStream(r -> r.logGroupName(firstGroup).logStreamName("unrelated"));
|
||||
logs.createLogStream(r -> r.logGroupName(secondGroup).logStreamName("unrelated"));
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {"GroupName": {"Type": "String"}},
|
||||
"Resources": {
|
||||
"Stream": {
|
||||
"Type": "AWS::Logs::LogStream",
|
||||
"Properties": {
|
||||
"LogGroupName": {"Ref": "GroupName"},
|
||||
"LogStreamName": "application"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {"StreamRef": {"Value": {"Ref": "Stream"}}}
|
||||
}
|
||||
""";
|
||||
|
||||
createStack(template, groupParameter(firstGroup));
|
||||
assertIdentity("application");
|
||||
assertWritable(firstGroup, output(), "before replacement");
|
||||
|
||||
cfn.updateStack(r -> r.stackName(stackName).templateBody(template)
|
||||
.parameters(groupParameter(secondGroup)));
|
||||
awaitStatus("UPDATE_COMPLETE");
|
||||
assertIdentity("application");
|
||||
assertThat(streamNames(firstGroup)).containsExactly("unrelated");
|
||||
assertThat(streamNames(secondGroup)).containsExactlyInAnyOrder("application", "unrelated");
|
||||
assertWritable(secondGroup, output(), "after replacement");
|
||||
|
||||
deleteStack();
|
||||
assertThat(streamNames(firstGroup)).containsExactly("unrelated");
|
||||
assertThat(streamNames(secondGroup)).containsExactly("unrelated");
|
||||
}
|
||||
|
||||
@Test
|
||||
void noValueGeneratesANameUntilTheConditionSelectsAnExplicitName() throws InterruptedException {
|
||||
String group = createLogGroup("conditional");
|
||||
String template = """
|
||||
{
|
||||
"Parameters": {"UseName": {"Type": "String"}},
|
||||
"Conditions": {"Named": {"Fn::Equals": [{"Ref": "UseName"}, "true"]}},
|
||||
"Resources": {
|
||||
"Stream": {
|
||||
"Type": "AWS::Logs::LogStream",
|
||||
"Properties": {
|
||||
"LogGroupName": "%s",
|
||||
"LogStreamName": {"Fn::If": ["Named", "application", {"Ref": "AWS::NoValue"}]}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {"StreamRef": {"Value": {"Ref": "Stream"}}}
|
||||
}
|
||||
""".formatted(group);
|
||||
|
||||
createStack(template, List.of(Parameter.builder().parameterKey("UseName").parameterValue("false").build()));
|
||||
String generated = output();
|
||||
assertThat(generated).startsWith(stackName + "-Stream-");
|
||||
assertIdentity(generated);
|
||||
assertThat(streamNames(group)).containsExactly(generated);
|
||||
assertWritable(group, generated, "generated from NoValue");
|
||||
|
||||
cfn.updateStack(r -> r.stackName(stackName).templateBody(template)
|
||||
.parameters(Parameter.builder().parameterKey("UseName").parameterValue("true").build()));
|
||||
awaitStatus("UPDATE_COMPLETE");
|
||||
assertIdentity("application");
|
||||
assertThat(streamNames(group)).containsExactly("application");
|
||||
|
||||
deleteStack();
|
||||
assertThat(streamNames(group)).isEmpty();
|
||||
}
|
||||
|
||||
private void createStack(String template, List<Parameter> parameters) throws InterruptedException {
|
||||
cfn.createStack(r -> r.stackName(stackName).templateBody(template).parameters(parameters));
|
||||
stackCreated = true;
|
||||
awaitStatus("CREATE_COMPLETE");
|
||||
}
|
||||
|
||||
private String createLogGroup(String suffix) {
|
||||
String group = "/test/" + stackName + "/" + suffix;
|
||||
logs.createLogGroup(r -> r.logGroupName(group));
|
||||
logGroups.add(group);
|
||||
return group;
|
||||
}
|
||||
|
||||
private static List<Parameter> groupParameter(String group) {
|
||||
return List.of(Parameter.builder().parameterKey("GroupName").parameterValue(group).build());
|
||||
}
|
||||
|
||||
private List<String> streamNames(String group) {
|
||||
return logs.describeLogStreamsPaginator(r -> r.logGroupName(group)).logStreams().stream()
|
||||
.map(LogStream::logStreamName).toList();
|
||||
}
|
||||
|
||||
private String output() {
|
||||
return cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0).outputs().stream()
|
||||
.filter(o -> "StreamRef".equals(o.outputKey())).map(Output::outputValue)
|
||||
.findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
private void assertIdentity(String streamName) {
|
||||
assertThat(output()).as("Ref is the log stream name").isEqualTo(streamName);
|
||||
assertThat(cfn.describeStackResource(r -> r.stackName(stackName).logicalResourceId("Stream"))
|
||||
.stackResourceDetail().physicalResourceId()).isEqualTo(streamName);
|
||||
}
|
||||
|
||||
private void assertWritable(String group, String stream, String message) throws InterruptedException {
|
||||
logs.putLogEvents(r -> r.logGroupName(group).logStreamName(stream)
|
||||
.logEvents(InputLogEvent.builder().timestamp(Instant.now().toEpochMilli()).message(message).build()));
|
||||
await(() -> logs.getLogEvents(r -> r.logGroupName(group).logStreamName(stream).startFromHead(true))
|
||||
.events().stream().map(OutputLogEvent::message).toList().equals(List.of(message)),
|
||||
"the event written to " + group + "/" + stream);
|
||||
}
|
||||
|
||||
private void awaitStatus(String expected) throws InterruptedException {
|
||||
await(() -> {
|
||||
Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);
|
||||
String status = stack.stackStatusAsString();
|
||||
if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) {
|
||||
throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason());
|
||||
}
|
||||
return expected.equals(status);
|
||||
}, expected);
|
||||
}
|
||||
|
||||
private void deleteStack() throws InterruptedException {
|
||||
if (!stackCreated) {
|
||||
return;
|
||||
}
|
||||
cfn.deleteStack(r -> r.stackName(stackName));
|
||||
await(() -> {
|
||||
try {
|
||||
List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks();
|
||||
if (stacks.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
Stack stack = stacks.get(0);
|
||||
if ("DELETE_FAILED".equals(stack.stackStatusAsString())) {
|
||||
throw new AssertionError(stackName + " deletion failed: " + stack.stackStatusReason());
|
||||
}
|
||||
return "DELETE_COMPLETE".equals(stack.stackStatusAsString());
|
||||
} catch (CloudFormationException e) {
|
||||
if ("ValidationError".equals(e.awsErrorDetails().errorCode())
|
||||
&& e.getMessage().contains("does not exist")) {
|
||||
return true;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}, "stack deletion");
|
||||
stackCreated = false;
|
||||
}
|
||||
|
||||
private void await(BooleanSupplier condition, String expected) throws InterruptedException {
|
||||
long deadline = System.nanoTime() + 60_000_000_000L;
|
||||
while (System.nanoTime() < deadline) {
|
||||
if (condition.getAsBoolean()) {
|
||||
return;
|
||||
}
|
||||
Thread.sleep(100);
|
||||
}
|
||||
throw new AssertionError(stackName + " timed out waiting for " + expected);
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,18 @@ StackSets support both `SELF_MANAGED` and the Cloud Launchpad `SERVICE_MANAGED`
|
||||
|
||||
Operation IDs are recorded and validated. Duplicate IDs return `OperationIdAlreadyExistsException`, missing stack sets return `StackSetNotFoundException`, and missing operation IDs return `OperationNotFoundException`. Invalid targets and request shapes use the CloudFormation query-protocol validation errors. Operations complete locally, so `OperationInProgressException` is only reachable when local operation state actually overlaps; Floci does not inject concurrency failures solely to exercise an error code.
|
||||
|
||||
## CloudWatch Logs log streams
|
||||
|
||||
`AWS::Logs::LogStream` creates a stream in the required `LogGroupName`. `LogStreamName` is optional;
|
||||
when omitted, including through `Fn::If` returning `AWS::NoValue`, CloudFormation generates a name
|
||||
and keeps it across updates. An explicit empty name remains invalid. `Ref` returns the stream name.
|
||||
The resource has no `Fn::GetAtt` attributes.
|
||||
|
||||
Changing either name replaces the stream. The previous stream and its events remain available
|
||||
until the update commits; a failed stack update restores the previous stream. `UpdateReplacePolicy:
|
||||
Retain` keeps a displaced stream. Stack deletion removes the current stream and its events, and
|
||||
tolerates a stream that was already deleted.
|
||||
|
||||
## CloudWatch Logs metric filters
|
||||
|
||||
`AWS::Logs::MetricFilter` returns the filter name alone for both `Ref` and
|
||||
@@ -149,7 +161,7 @@ cross-resource references.
|
||||
| IoT Core | `DomainConfiguration` (`ServerCertificates` resolves to a JSON string), `Policy` (deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached), `Thing`, `TopicRule` |
|
||||
| CloudFront | `CachePolicy`, `Distribution`, `OriginAccessControl`, `OriginRequestPolicy`, `ResponseHeadersPolicy` |
|
||||
| CloudWatch | `Alarm`, `Dashboard` |
|
||||
| CloudWatch Logs | `LogGroup`, `MetricFilter` |
|
||||
| CloudWatch Logs | `LogGroup`, `LogStream`, `MetricFilter` |
|
||||
| WAFv2 | `WebACL` |
|
||||
| Config | `ConfigRule` |
|
||||
| CloudFormation | `CustomResource`, `Custom::DynamoDBReplica` (applied natively against DynamoDB, not via a provider Lambda), `Stack` (nested stacks), `Custom::*` (Lambda-backed) |
|
||||
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.MissingNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/** Log streams have a name-only Ref, but their lifecycle identity also includes the log group. */
|
||||
@ApplicationScoped
|
||||
public class LogsLogStreamCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final String TYPE = "AWS::Logs::LogStream";
|
||||
private static final String GROUP_ATTR = "__FlociLogStreamGroup";
|
||||
private static final String NAME_MODE_ATTR = "__FlociLogStreamNameMode";
|
||||
private static final String UPDATE_ATTR = "__FlociLogStreamUpdate";
|
||||
private static final String CLEANUP_ATTR = "__FlociLogStreamCleanup";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private final CloudWatchLogsService logs;
|
||||
|
||||
public LogsLogStreamCfnProvisioner(CloudWatchLogsService logs) {
|
||||
this.logs = logs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) {
|
||||
JsonNode resolved = ctx.engine().resolveNode(markNoValue(properties));
|
||||
String group = property(resolved, "LogGroupName", true);
|
||||
String explicitName = property(resolved, "LogStreamName", false);
|
||||
if (!group.matches("[.\\-_/#A-Za-z0-9]+")) {
|
||||
throw invalid("LogGroupName contains invalid characters");
|
||||
}
|
||||
if (explicitName != null && (explicitName.contains(":") || explicitName.contains("*"))) {
|
||||
throw invalid("LogStreamName cannot contain ':' or '*'");
|
||||
}
|
||||
|
||||
// An earlier failed cleanup must not be forgotten when this update records a new one.
|
||||
deletePending(resource);
|
||||
Identity prior = ctx.isUpdate() ? identity(resource, ctx.priorPhysicalId()) : null;
|
||||
String priorMode = resource.getAttributes().get(NAME_MODE_ATTR);
|
||||
String name = explicitName != null ? explicitName
|
||||
: prior != null && "generated".equals(priorMode) ? prior.name()
|
||||
: ctx.generatePhysicalName(resource.getLogicalId(), 512, false);
|
||||
Identity target = new Identity(group, name);
|
||||
boolean replacement = prior != null && !prior.equals(target);
|
||||
|
||||
// Set ownership only after creation succeeds. A duplicate belongs to another resource.
|
||||
if (prior == null || replacement) {
|
||||
logs.createLogStream(group, name, ctx.region());
|
||||
}
|
||||
if (prior != null) {
|
||||
ObjectNode snapshot = address(prior, ctx.region());
|
||||
snapshot.put("nameMode", priorMode);
|
||||
snapshot.put("replacement", replacement);
|
||||
resource.getAttributes().put(UPDATE_ATTR, snapshot.toString());
|
||||
if (replacement) {
|
||||
setCleanup(resource, prior, ctx.region(), true);
|
||||
}
|
||||
}
|
||||
setIdentity(resource, target, explicitName == null ? "generated" : "explicit");
|
||||
resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
|
||||
}
|
||||
|
||||
// Keep conditional omission distinct from an explicitly empty name during intrinsic resolution.
|
||||
private static JsonNode markNoValue(JsonNode node) {
|
||||
if (node == null) {
|
||||
return null;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
if ("AWS::NoValue".equals(node.path("Ref").asText())) {
|
||||
return MissingNode.getInstance();
|
||||
}
|
||||
ObjectNode marked = MAPPER.createObjectNode();
|
||||
node.fields().forEachRemaining(entry -> marked.set(entry.getKey(), markNoValue(entry.getValue())));
|
||||
return marked;
|
||||
}
|
||||
if (node.isArray()) {
|
||||
ArrayNode marked = MAPPER.createArrayNode();
|
||||
node.forEach(item -> marked.add(markNoValue(item)));
|
||||
return marked;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private static String property(JsonNode properties, String key, boolean required) {
|
||||
JsonNode value = properties == null ? null : properties.get(key);
|
||||
if (value == null || value.isNull() || value.isMissingNode()) {
|
||||
if (required) {
|
||||
throw invalid(key + " is required");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (!value.isTextual() || value.textValue().isEmpty() || value.textValue().length() > 512) {
|
||||
throw invalid(key + " must be a string between 1 and 512 characters");
|
||||
}
|
||||
return value.textValue();
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("ValidationError", message, 400);
|
||||
}
|
||||
|
||||
private record Identity(String group, String name) {}
|
||||
|
||||
private static Identity identity(StackResource resource, String name) {
|
||||
String group = resource.getAttributes().get(GROUP_ATTR);
|
||||
if (group == null || name == null) {
|
||||
throw new IllegalStateException("Missing log stream identity for " + resource.getLogicalId());
|
||||
}
|
||||
return new Identity(group, name);
|
||||
}
|
||||
|
||||
private static Identity identity(JsonNode address) {
|
||||
return new Identity(address.path("group").asText(), address.path("name").asText());
|
||||
}
|
||||
|
||||
private static void setIdentity(StackResource resource, Identity identity, String mode) {
|
||||
resource.setPhysicalId(identity.name());
|
||||
resource.getAttributes().put(GROUP_ATTR, identity.group());
|
||||
resource.getAttributes().put(NAME_MODE_ATTR, mode);
|
||||
}
|
||||
|
||||
private static ObjectNode address(Identity identity, String region) {
|
||||
return MAPPER.createObjectNode().put("group", identity.group()).put("name", identity.name())
|
||||
.put("region", region);
|
||||
}
|
||||
|
||||
private static void setCleanup(StackResource resource, Identity identity, String region, boolean retainable) {
|
||||
ObjectNode cleanup = address(identity, region).put("retainable", retainable).put("attempts", 0);
|
||||
resource.getAttributes().put(CLEANUP_ATTR, cleanup.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(StackResource resource, String region) {
|
||||
deletePending(resource);
|
||||
if (resource.getPhysicalId() != null) {
|
||||
delete(identity(resource, resource.getPhysicalId()), region);
|
||||
}
|
||||
resource.getAttributes().remove(UPDATE_ATTR);
|
||||
resource.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
|
||||
}
|
||||
|
||||
private void delete(Identity identity, String region) {
|
||||
CfnDeletes.safeDelete("Log stream", identity.name(),
|
||||
() -> logs.deleteLogStream(identity.group(), identity.name(), region),
|
||||
"ResourceNotFoundException");
|
||||
}
|
||||
|
||||
private void deletePending(StackResource resource) {
|
||||
ObjectNode cleanup = read(resource, CLEANUP_ATTR);
|
||||
if (cleanup != null) {
|
||||
delete(identity(cleanup), cleanup.path("region").asText());
|
||||
resource.getAttributes().remove(CLEANUP_ATTR);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
ObjectNode snapshot = read(resource, UPDATE_ATTR);
|
||||
if (snapshot == null) {
|
||||
return false;
|
||||
}
|
||||
Identity replacement = identity(resource, resource.getPhysicalId());
|
||||
Identity prior = identity(snapshot);
|
||||
boolean replaced = snapshot.path("replacement").asBoolean();
|
||||
// Restore the old address before a delete can fail; retain the new address for a retry.
|
||||
setIdentity(resource, prior, snapshot.path("nameMode").asText());
|
||||
resource.getAttributes().remove(UPDATE_ATTR);
|
||||
resource.getAttributes().remove(CLEANUP_ATTR);
|
||||
if (replaced) {
|
||||
setCleanup(resource, replacement, snapshot.path("region").asText(), false);
|
||||
deletePending(resource);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPendingRollbackCleanup(StackResource resource) {
|
||||
return "true".equals(resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR))
|
||||
|| resource.getAttributes().containsKey(CLEANUP_ATTR);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return resource.getAttributes().containsKey(CLEANUP_ATTR);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
ObjectNode cleanup = read(resource, CLEANUP_ATTR);
|
||||
return cleanup == null || retained(resource, cleanup) ? null : cleanup.path("name").asText();
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
ObjectNode cleanup = read(resource, CLEANUP_ATTR);
|
||||
if (cleanup == null) {
|
||||
return resource.getAttributes().containsKey(UPDATE_ATTR)
|
||||
? new UpdateCleanupResult(true, true, null, 0, null)
|
||||
: UpdateCleanupResult.notApplicable();
|
||||
}
|
||||
String name = cleanup.path("name").asText();
|
||||
if (retained(resource, cleanup)) {
|
||||
resource.getAttributes().remove(CLEANUP_ATTR);
|
||||
return new UpdateCleanupResult(true, true, name, 0, null);
|
||||
}
|
||||
try {
|
||||
deletePending(resource);
|
||||
return new UpdateCleanupResult(true, true, name, 0, null);
|
||||
} catch (RuntimeException failure) {
|
||||
int attempts = cleanup.path("attempts").asInt() + 1;
|
||||
cleanup.put("attempts", attempts);
|
||||
resource.getAttributes().put(CLEANUP_ATTR, cleanup.toString());
|
||||
return new UpdateCleanupResult(true, false, name, attempts, failure.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean retained(StackResource resource, JsonNode cleanup) {
|
||||
return cleanup.path("retainable").asBoolean() && "Retain".equals(resource.getUpdateReplacePolicy());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(UPDATE_ATTR);
|
||||
// Failed deletes stay addressable by a later update or DeleteStack.
|
||||
}
|
||||
|
||||
private static ObjectNode read(StackResource resource, String attribute) {
|
||||
String raw = resource.getAttributes().get(attribute);
|
||||
if (raw == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode record = MAPPER.readTree(raw);
|
||||
if (record.isObject()) {
|
||||
return (ObjectNode) record;
|
||||
}
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Invalid log stream lifecycle record for " + resource.getLogicalId(), e);
|
||||
}
|
||||
throw new IllegalStateException("Invalid log stream lifecycle record for " + resource.getLogicalId());
|
||||
}
|
||||
}
|
||||
+2
@@ -69,6 +69,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEve
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEventSourceMappingCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaVersionAliasCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsLogStreamCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsMetricFilterCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.PipesCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.RdsCfnProvisioner;
|
||||
@@ -271,6 +272,7 @@ final class CfnProvisionerFixture {
|
||||
}
|
||||
if (logsService != null) {
|
||||
discovered.add(new LogsCfnProvisioner(logsService));
|
||||
discovered.add(new LogsLogStreamCfnProvisioner(logsService));
|
||||
}
|
||||
if (logsMetricFilterService != null) {
|
||||
discovered.add(new LogsMetricFilterCfnProvisioner(logsMetricFilterService));
|
||||
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.mockito.InjectSpy;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.doCallRealMethod;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationLogStreamIntegrationTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260918/us-east-1/cloudformation/aws4_request";
|
||||
private static final String LOGS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260918/us-east-1/logs/aws4_request";
|
||||
private final List<String> stacks = new ArrayList<>();
|
||||
private final List<String> groups = new ArrayList<>();
|
||||
|
||||
@InjectSpy
|
||||
CloudWatchLogsService logsService;
|
||||
|
||||
@BeforeAll
|
||||
static void configureContentTypes() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() throws Exception {
|
||||
for (String stack : List.copyOf(stacks)) {
|
||||
deleteStack(stack);
|
||||
}
|
||||
for (String group : groups) {
|
||||
logs("DeleteLogGroup", Map.of("logGroupName", group)).then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedStreamNameAndEventsSurviveAnUnrelatedStackUpdate() throws Exception {
|
||||
String group = createGroup();
|
||||
String stack = createStack(template(group, null, "first", false, false), "CREATE_COMPLETE");
|
||||
String stream = streamRef(awaitStatus(stack, "CREATE_COMPLETE"));
|
||||
assertTrue(stream.startsWith(stack + "-Stream-"), stream);
|
||||
assertTrue(stream.length() <= 512);
|
||||
assertEquals(List.of(stream), streams(group));
|
||||
putEvent(group, stream, "keep this event");
|
||||
|
||||
updateStack(stack, template(group, null, "second", false, false));
|
||||
assertEquals(stream, streamRef(awaitStatus(stack, "UPDATE_COMPLETE")));
|
||||
assertEquals(List.of("keep this event"), messages(group, stream));
|
||||
|
||||
deleteStack(stack);
|
||||
assertTrue(streams(group).isEmpty(), "Deleting the stack must delete the stream in the external group");
|
||||
logs("CreateLogStream", Map.of("logGroupName", group, "logStreamName", stream))
|
||||
.then().statusCode(200);
|
||||
assertTrue(messages(group, stream).isEmpty(), "Deleted stream events must not reappear on recreation");
|
||||
}
|
||||
|
||||
@Test
|
||||
void conditionalNameOmissionReplacesExplicitNameAndKeepsGeneratedNameStable() throws Exception {
|
||||
String group = createGroup();
|
||||
String stack = createStack(conditionalTemplate(group, true, "first"), "CREATE_COMPLETE");
|
||||
assertEquals("application", streamRef(awaitStatus(stack, "CREATE_COMPLETE")));
|
||||
|
||||
updateStack(stack, conditionalTemplate(group, false, "first"));
|
||||
String generated = streamRef(awaitStatus(stack, "UPDATE_COMPLETE"));
|
||||
assertTrue(generated.startsWith(stack + "-Stream-"), generated);
|
||||
assertEquals(List.of(generated), streams(group));
|
||||
putEvent(group, generated, "keep conditional stream");
|
||||
|
||||
updateStack(stack, conditionalTemplate(group, false, "second"));
|
||||
assertEquals(generated, streamRef(awaitStatus(stack, "UPDATE_COMPLETE")));
|
||||
assertEquals(List.of("keep conditional stream"), messages(group, generated));
|
||||
|
||||
updateStack(stack, conditionalTemplate(group, true, "second"));
|
||||
assertEquals("application", streamRef(awaitStatus(stack, "UPDATE_COMPLETE")));
|
||||
assertEquals(List.of("application"), streams(group));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedConditionCanOmitTheStreamName() throws Exception {
|
||||
String group = createGroup();
|
||||
ObjectNode document = (ObjectNode) MAPPER.readTree(conditionalTemplate(group, false, null));
|
||||
document.withObject("/Conditions").set("Outer", MAPPER.valueToTree(Map.of("Fn::Equals", List.of(1, 1))));
|
||||
ObjectNode properties = document.withObject("/Resources/Stream/Properties");
|
||||
properties.set("LogStreamName", MAPPER.valueToTree(Map.of("Fn::If", List.of("Outer",
|
||||
properties.get("LogStreamName"), "unused"))));
|
||||
|
||||
String stack = createStack(document.toString(), "CREATE_COMPLETE");
|
||||
String generated = streamRef(awaitStatus(stack, "CREATE_COMPLETE"));
|
||||
assertTrue(generated.startsWith(stack + "-Stream-"), generated);
|
||||
assertEquals(List.of(generated), streams(group));
|
||||
}
|
||||
|
||||
@Test
|
||||
void conditionalEmptyNameAndOmittedRequiredGroupStillFailValidation() throws Exception {
|
||||
String group = createGroup();
|
||||
ObjectNode emptyName = (ObjectNode) MAPPER.readTree(conditionalTemplate(group, true, null));
|
||||
emptyName.withObject("/Resources/Stream/Properties").set("LogStreamName",
|
||||
MAPPER.valueToTree(Map.of("Fn::If", List.of("UseName", "", Map.of("Ref", "AWS::NoValue")))));
|
||||
createStack(emptyName.toString(), "ROLLBACK_COMPLETE");
|
||||
|
||||
ObjectNode missingGroup = (ObjectNode) MAPPER.readTree(conditionalTemplate(group, false, null));
|
||||
missingGroup.withObject("/Resources/Stream/Properties").set("LogGroupName",
|
||||
MAPPER.valueToTree(Map.of("Fn::If", List.of("UseName", group, Map.of("Ref", "AWS::NoValue")))));
|
||||
createStack(missingGroup.toString(), "ROLLBACK_COMPLETE");
|
||||
assertTrue(streams(group).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedGroupReplacementRestoresTheOriginalStreamAndEvents() throws Exception {
|
||||
String originalGroup = createGroup();
|
||||
String targetGroup = createGroup();
|
||||
String stream = "application";
|
||||
String stack = createStack(template(originalGroup, stream, null, false, false), "CREATE_COMPLETE");
|
||||
putEvent(originalGroup, stream, "original event");
|
||||
|
||||
updateStack(stack, template(targetGroup, stream, null, false, true));
|
||||
assertEquals(stream, streamRef(awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE")));
|
||||
assertEquals(List.of(stream), streams(originalGroup));
|
||||
assertEquals(List.of("original event"), messages(originalGroup, stream));
|
||||
assertTrue(streams(targetGroup).isEmpty(), "The failed replacement must be removed");
|
||||
|
||||
deleteStack(stack);
|
||||
assertTrue(streams(originalGroup).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainPolicyKeepsTheDisplacedStreamAndItsEvents() throws Exception {
|
||||
String group = createGroup();
|
||||
String stack = createStack(template(group, "original", null, true, false), "CREATE_COMPLETE");
|
||||
putEvent(group, "original", "retained event");
|
||||
|
||||
updateStack(stack, template(group, "replacement", null, true, false));
|
||||
assertEquals("replacement", streamRef(awaitStatus(stack, "UPDATE_COMPLETE")));
|
||||
assertEquals(List.of("original", "replacement"), streams(group));
|
||||
assertEquals(List.of("retained event"), messages(group, "original"));
|
||||
|
||||
deleteStack(stack);
|
||||
assertEquals(List.of("original"), streams(group));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteStackAfterFailedRollbackCleansBothOwnedStreams() throws Exception {
|
||||
String originalGroup = createGroup();
|
||||
String targetGroup = createGroup();
|
||||
String stream = "application";
|
||||
String stack = createStack(template(originalGroup, stream, null, false, false), "CREATE_COMPLETE");
|
||||
putEvent(originalGroup, stream, "original event");
|
||||
doThrow(new AwsException("ServiceUnavailableException", "temporary delete failure", 503))
|
||||
.when(logsService).deleteLogStream(targetGroup, stream, "us-east-1");
|
||||
try {
|
||||
updateStack(stack, template(targetGroup, stream, null, false, true));
|
||||
awaitStatus(stack, "UPDATE_ROLLBACK_FAILED");
|
||||
assertEquals(List.of("original event"), messages(originalGroup, stream));
|
||||
assertEquals(List.of(stream), streams(targetGroup));
|
||||
} finally {
|
||||
doCallRealMethod().when(logsService).deleteLogStream(targetGroup, stream, "us-east-1");
|
||||
}
|
||||
|
||||
deleteStack(stack);
|
||||
assertTrue(streams(originalGroup).isEmpty(), "The original stream remains owned after failed rollback");
|
||||
assertTrue(streams(targetGroup).isEmpty(), "The failed replacement still needs cleanup");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDuplicateStreamDoesNotBecomeOwnedByTheFailedStack() throws Exception {
|
||||
String group = createGroup();
|
||||
logs("CreateLogStream", Map.of("logGroupName", group, "logStreamName", "external"))
|
||||
.then().statusCode(200);
|
||||
putEvent(group, "external", "external event");
|
||||
|
||||
String stack = createStack(template(group, "external", null, false, false), "ROLLBACK_COMPLETE");
|
||||
assertEquals(List.of("external event"), messages(group, "external"));
|
||||
deleteStack(stack);
|
||||
assertEquals(List.of("external"), streams(group));
|
||||
assertEquals(List.of("external event"), messages(group, "external"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAStackToleratesAnAlreadyRemovedStream() throws Exception {
|
||||
String group = createGroup();
|
||||
String stack = createStack(template(group, "removed", null, false, false), "CREATE_COMPLETE");
|
||||
logs("DeleteLogStream", Map.of("logGroupName", group, "logStreamName", "removed"))
|
||||
.then().statusCode(200);
|
||||
|
||||
deleteStack(stack);
|
||||
assertTrue(streams(group).isEmpty());
|
||||
}
|
||||
|
||||
private String createGroup() throws Exception {
|
||||
String group = "/cfn/log-stream/" + Long.toString(System.nanoTime(), 36);
|
||||
logs("CreateLogGroup", Map.of("logGroupName", group)).then().statusCode(200);
|
||||
groups.add(group);
|
||||
return group;
|
||||
}
|
||||
|
||||
private String createStack(String template, String status) {
|
||||
String stack = "cfn-log-stream-" + Long.toString(System.nanoTime(), 36);
|
||||
cfn(stack, "CreateStack", template).then().statusCode(200);
|
||||
stacks.add(stack);
|
||||
awaitStatus(stack, status);
|
||||
return stack;
|
||||
}
|
||||
|
||||
private static void updateStack(String stack, String template) {
|
||||
cfn(stack, "UpdateStack", template).then().statusCode(200);
|
||||
}
|
||||
|
||||
private void deleteStack(String stack) {
|
||||
cfn(stack, "DeleteStack", null).then().statusCode(200);
|
||||
await().atMost(Duration.ofSeconds(15)).untilAsserted(() -> {
|
||||
Response response = cfn(stack, "DescribeStacks", null);
|
||||
assertEquals(400, response.statusCode(), response.asString());
|
||||
assertTrue(response.asString().contains("does not exist"), response.asString());
|
||||
});
|
||||
stacks.remove(stack);
|
||||
}
|
||||
|
||||
private static String awaitStatus(String stack, String status) {
|
||||
return await().atMost(Duration.ofSeconds(15)).until(
|
||||
() -> cfn(stack, "DescribeStacks", null).then().statusCode(200).extract().asString(),
|
||||
body -> status.equals(XmlParser.extractFirst(body, "StackStatus", null)));
|
||||
}
|
||||
|
||||
private static String streamRef(String body) {
|
||||
String stream = XmlParser.extractPairs(body, "Outputs", "OutputKey", "OutputValue").get("StreamName");
|
||||
assertFalse(stream == null || stream.isBlank(), body);
|
||||
return stream;
|
||||
}
|
||||
|
||||
private static Response cfn(String stack, String action, String template) {
|
||||
RequestSpecification request = given().contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH).formParam("Action", action).formParam("StackName", stack);
|
||||
if (template != null) {
|
||||
request.formParam("TemplateBody", template);
|
||||
}
|
||||
return request.post("/");
|
||||
}
|
||||
|
||||
private static Response logs(String action, Map<String, ?> body) throws Exception {
|
||||
return given().contentType("application/x-amz-json-1.1").header("Authorization", LOGS_AUTH)
|
||||
.header("X-Amz-Target", "Logs_20140328." + action).body(MAPPER.writeValueAsString(body)).post("/");
|
||||
}
|
||||
|
||||
private static List<String> streams(String group) throws Exception {
|
||||
return logs("DescribeLogStreams", Map.of("logGroupName", group)).then().statusCode(200)
|
||||
.extract().jsonPath().getList("logStreams.logStreamName", String.class).stream().sorted().toList();
|
||||
}
|
||||
|
||||
private static void putEvent(String group, String stream, String message) throws Exception {
|
||||
logs("PutLogEvents", Map.of("logGroupName", group, "logStreamName", stream,
|
||||
"logEvents", List.of(Map.of("timestamp", System.currentTimeMillis(), "message", message))))
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
private static List<String> messages(String group, String stream) throws Exception {
|
||||
return logs("GetLogEvents", Map.of("logGroupName", group, "logStreamName", stream, "startFromHead", true))
|
||||
.then().statusCode(200).extract().jsonPath().getList("events.message", String.class);
|
||||
}
|
||||
|
||||
private static String conditionalTemplate(String group, boolean useName, String revision) throws Exception {
|
||||
ObjectNode document = (ObjectNode) MAPPER.readTree(template(group, null, revision, false, false));
|
||||
document.set("Conditions", MAPPER.valueToTree(Map.of("UseName",
|
||||
Map.of("Fn::Equals", List.of(useName, true)))));
|
||||
document.withObject("/Resources/Stream/Properties").set("LogStreamName",
|
||||
MAPPER.valueToTree(Map.of("Fn::If", List.of("UseName", "application", Map.of("Ref", "AWS::NoValue")))));
|
||||
return document.toString();
|
||||
}
|
||||
|
||||
private static String template(String group, String name, String revision, boolean retain, boolean fail)
|
||||
throws Exception {
|
||||
Map<String, Object> properties = new LinkedHashMap<>();
|
||||
properties.put("LogGroupName", group);
|
||||
if (name != null) {
|
||||
properties.put("LogStreamName", name);
|
||||
}
|
||||
Map<String, Object> resources = new LinkedHashMap<>();
|
||||
resources.put("Stream", Map.of("Type", "AWS::Logs::LogStream", "Properties", properties,
|
||||
"UpdateReplacePolicy", retain ? "Retain" : "Delete"));
|
||||
if (revision != null) {
|
||||
resources.put("Revision", Map.of("Type", "AWS::SSM::Parameter",
|
||||
"Properties", Map.of("Type", "String", "Value", revision)));
|
||||
}
|
||||
if (fail) {
|
||||
resources.put("BadSecret", Map.of("Type", "AWS::SecretsManager::Secret", "DependsOn", "Stream",
|
||||
"Properties", Map.of("SecretString", "explicit",
|
||||
"GenerateSecretString", Map.of("PasswordLength", 32))));
|
||||
}
|
||||
return MAPPER.writeValueAsString(Map.of("Resources", resources,
|
||||
"Outputs", Map.of("StreamName", Map.of("Value", Map.of("Ref", "Stream")))));
|
||||
}
|
||||
}
|
||||
+441
@@ -0,0 +1,441 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class LogsLogStreamCfnProvisionerTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
private CloudWatchLogsService logs;
|
||||
private CloudFormationTemplateEngine engine;
|
||||
private LogsLogStreamCfnProvisioner provisioner;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
logs = mock(CloudWatchLogsService.class);
|
||||
engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolveNode(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
provisioner = new LogsLogStreamCfnProvisioner(logs);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsARealStreamAndRefIsItsName() {
|
||||
StackResource resource = create("/app/logs", "events");
|
||||
|
||||
assertEquals(Set.of("AWS::Logs::LogStream"), provisioner.resourceTypes());
|
||||
assertEquals("events", resource.getPhysicalId());
|
||||
assertFalse(resource.getAttributes().containsKey("Arn"));
|
||||
verify(logs).createLogStream("/app/logs", "events", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesPropertyIntrinsicsBeforeCallingLogs() {
|
||||
ObjectNode properties = MAPPER.createObjectNode();
|
||||
properties.putObject("LogGroupName").put("Ref", "Group");
|
||||
properties.putObject("LogStreamName").put("Ref", "Name");
|
||||
when(engine.resolveNode(properties)).thenReturn(props("/resolved", "resolved-name"));
|
||||
StackResource resource = resource();
|
||||
|
||||
provisioner.provision(resource, properties, context(null));
|
||||
|
||||
assertEquals("resolved-name", resource.getPhysicalId());
|
||||
verify(logs).createLogStream("/resolved", "resolved-name", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void omittedNameIsGeneratedAndBounded() {
|
||||
StackResource resource = resource();
|
||||
provisioner.provision(resource, props("group", null),
|
||||
new ProvisionContext(engine, REGION, ACCOUNT, "stack".repeat(150)));
|
||||
|
||||
String name = resource.getPhysicalId();
|
||||
assertEquals(512, name.length());
|
||||
assertTrue(name.matches(".*-[0-9a-f]{12}"));
|
||||
verify(logs).createLogStream("group", name, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidPropertiesBeforeCreatingAnything() {
|
||||
List<ObjectNode> invalid = List.of(
|
||||
MAPPER.createObjectNode(),
|
||||
props("", "events"),
|
||||
props("invalid:group", "events"),
|
||||
props("g".repeat(513), "events"),
|
||||
props("group", ""),
|
||||
props("group", "events:one"),
|
||||
props("group", "events*"),
|
||||
props("group", "s".repeat(513)),
|
||||
MAPPER.createObjectNode().put("LogGroupName", "group").put("LogStreamName", 5));
|
||||
|
||||
for (ObjectNode properties : invalid) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource(), properties, context(null)));
|
||||
assertEquals("ValidationError", error.getErrorCode());
|
||||
}
|
||||
verifyNoInteractions(logs);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unchangedExplicitNameDoesNotRecreateOrDeleteTheStream() {
|
||||
StackResource resource = create("group", "events");
|
||||
clearInvocations(logs);
|
||||
|
||||
update(resource, "group", "events");
|
||||
commit(resource);
|
||||
|
||||
assertEquals("events", resource.getPhysicalId());
|
||||
verifyNoInteractions(logs);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unchangedGeneratedNameIsStable() {
|
||||
StackResource resource = create("group", null);
|
||||
String name = resource.getPhysicalId();
|
||||
clearInvocations(logs);
|
||||
|
||||
update(resource, "group", null);
|
||||
commit(resource);
|
||||
|
||||
assertEquals(name, resource.getPhysicalId());
|
||||
verifyNoInteractions(logs);
|
||||
}
|
||||
|
||||
@Test
|
||||
void removingAnExplicitNameCreatesAReplacementBeforeCleanup() {
|
||||
StackResource resource = create("group", "chosen");
|
||||
clearInvocations(logs);
|
||||
|
||||
update(resource, "group", null);
|
||||
|
||||
String replacement = resource.getPhysicalId();
|
||||
assertNotEquals("chosen", replacement);
|
||||
verify(logs).createLogStream("group", replacement, REGION);
|
||||
verify(logs, never()).deleteLogStream(anyString(), anyString(), anyString());
|
||||
assertTrue(provisioner.hasReplacementUpdate(resource));
|
||||
assertEquals("chosen", provisioner.updateCleanupPhysicalId(resource));
|
||||
|
||||
commit(resource);
|
||||
verify(logs).deleteLogStream("group", "chosen", REGION);
|
||||
assertFalse(provisioner.hasReplacementUpdate(resource));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingGroupWithTheSameStreamNameStillRequiresReplacement() {
|
||||
StackResource resource = create("old-group", "events");
|
||||
clearInvocations(logs);
|
||||
|
||||
update(resource, "new-group", "events");
|
||||
|
||||
assertEquals("events", resource.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(resource));
|
||||
verify(logs).createLogStream("new-group", "events", REGION);
|
||||
verify(logs, never()).deleteLogStream(anyString(), anyString(), anyString());
|
||||
|
||||
commit(resource);
|
||||
verify(logs).deleteLogStream("old-group", "events", REGION);
|
||||
verify(logs, never()).deleteLogStream("new-group", "events", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedStackUpdateRestoresThePriorGroupWithoutDeletingItsEvents() {
|
||||
StackResource resource = create("old-group", "events");
|
||||
update(resource, "new-group", "events");
|
||||
clearInvocations(logs);
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
|
||||
assertEquals("events", resource.getPhysicalId());
|
||||
verify(logs).deleteLogStream("new-group", "events", REGION);
|
||||
verify(logs, never()).deleteLogStream("old-group", "events", REGION);
|
||||
assertTrue(provisioner.hasPendingRollbackCleanup(resource));
|
||||
clearInvocations(logs);
|
||||
provisioner.delete(resource, REGION);
|
||||
verify(logs).deleteLogStream("old-group", "events", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noOpUpdateCanRollbackWithoutTouchingLogEvents() {
|
||||
StackResource resource = create("group", "events");
|
||||
clearInvocations(logs);
|
||||
update(resource, "group", "events");
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
|
||||
assertEquals("events", resource.getPhysicalId());
|
||||
verifyNoInteractions(logs);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackRestoresGeneratedNameModeWhenExplicitNameEqualsGeneratedName() {
|
||||
StackResource resource = create("group", null);
|
||||
String generated = resource.getPhysicalId();
|
||||
clearInvocations(logs);
|
||||
update(resource, "group", generated);
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
update(resource, "group", null);
|
||||
|
||||
assertEquals(generated, resource.getPhysicalId());
|
||||
verifyNoInteractions(logs);
|
||||
}
|
||||
|
||||
@Test
|
||||
void committedExplicitNameModeMakesLaterOmissionReplaceTheStream() {
|
||||
StackResource resource = create("group", null);
|
||||
String generated = resource.getPhysicalId();
|
||||
update(resource, "group", generated);
|
||||
commit(resource);
|
||||
clearInvocations(logs);
|
||||
|
||||
update(resource, "group", null);
|
||||
|
||||
assertNotEquals(generated, resource.getPhysicalId());
|
||||
verify(logs).createLogStream("group", resource.getPhysicalId(), REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateCreateDoesNotClaimOrDeleteAnExistingStream() {
|
||||
AwsException duplicate = new AwsException("ResourceAlreadyExistsException", "exists", 400);
|
||||
doThrow(duplicate).when(logs).createLogStream("group", "taken", REGION);
|
||||
StackResource resource = resource();
|
||||
|
||||
assertSame(duplicate, assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource, props("group", "taken"), context(null))));
|
||||
assertNull(resource.getPhysicalId());
|
||||
provisioner.delete(resource, REGION);
|
||||
|
||||
verify(logs, never()).deleteLogStream(anyString(), anyString(), anyString());
|
||||
assertFalse(provisioner.hasPendingRollbackCleanup(resource));
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateReplacementLeavesPriorIdentityAndExternalStreamAlone() {
|
||||
StackResource resource = create("group", "old");
|
||||
doThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400))
|
||||
.when(logs).createLogStream("group", "taken", REGION);
|
||||
clearInvocations(logs);
|
||||
|
||||
assertThrows(AwsException.class, () -> update(resource, "group", "taken"));
|
||||
|
||||
assertEquals("old", resource.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(resource));
|
||||
verify(logs, never()).deleteLogStream(anyString(), anyString(), anyString());
|
||||
provisioner.delete(resource, REGION);
|
||||
verify(logs).deleteLogStream("group", "old", REGION);
|
||||
verify(logs, never()).deleteLogStream("group", "taken", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReplacePolicyRetainKeepsOnlyTheDisplacedStream() {
|
||||
StackResource resource = create("old-group", "events");
|
||||
update(resource, "new-group", "events");
|
||||
resource.setUpdateReplacePolicy("Retain");
|
||||
clearInvocations(logs);
|
||||
|
||||
assertNull(provisioner.updateCleanupPhysicalId(resource));
|
||||
commit(resource);
|
||||
provisioner.delete(resource, REGION);
|
||||
|
||||
verify(logs).deleteLogStream("new-group", "events", REGION);
|
||||
verify(logs, never()).deleteLogStream("old-group", "events", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReplacePolicyRetainDoesNotKeepAFailedReplacement() {
|
||||
StackResource resource = create("old-group", "events");
|
||||
update(resource, "new-group", "events");
|
||||
resource.setUpdateReplacePolicy("Retain");
|
||||
clearInvocations(logs);
|
||||
|
||||
assertTrue(provisioner.rollbackUpdate(resource));
|
||||
|
||||
verify(logs).deleteLogStream("new-group", "events", REGION);
|
||||
verify(logs, never()).deleteLogStream("old-group", "events", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingStreamIsToleratedDuringDelete() {
|
||||
StackResource resource = create("group", "events");
|
||||
doThrow(new AwsException("ResourceNotFoundException", "gone", 400))
|
||||
.when(logs).deleteLogStream("group", "events", REGION);
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(resource, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePropagatesRealServiceFailures() {
|
||||
StackResource resource = create("group", "events");
|
||||
AwsException unavailable = new AwsException("ServiceUnavailableException", "retry", 500);
|
||||
doThrow(unavailable).when(logs).deleteLogStream("group", "events", REGION);
|
||||
|
||||
assertSame(unavailable, assertThrows(AwsException.class, () -> provisioner.delete(resource, REGION)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanupRetriesAndKeepsTheCurrentStreamSafe() {
|
||||
StackResource resource = create("old-group", "events");
|
||||
update(resource, "new-group", "events");
|
||||
doThrow(new AwsException("ServiceUnavailableException", "retry", 500)).doNothing()
|
||||
.when(logs).deleteLogStream("old-group", "events", REGION);
|
||||
|
||||
UpdateCleanupResult first = provisioner.completeUpdate(resource);
|
||||
assertTrue(first.applicable());
|
||||
assertFalse(first.complete());
|
||||
assertEquals(1, first.attempts());
|
||||
assertEquals("retry", first.failureReason());
|
||||
assertEquals("events", first.previousPhysicalId());
|
||||
|
||||
assertTrue(provisioner.completeUpdate(resource).complete());
|
||||
provisioner.clearUpdate(resource);
|
||||
verify(logs, times(2)).deleteLogStream("old-group", "events", REGION);
|
||||
verify(logs, never()).deleteLogStream("new-group", "events", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void exhaustedCleanupRemainsAddressableByStackDeletion() {
|
||||
StackResource resource = create("old-group", "events");
|
||||
update(resource, "new-group", "events");
|
||||
doThrow(new AwsException("ServiceUnavailableException", "retry", 500))
|
||||
.when(logs).deleteLogStream("old-group", "events", REGION);
|
||||
for (int attempt = 1; attempt <= 3; attempt++) {
|
||||
assertEquals(attempt, provisioner.completeUpdate(resource).attempts());
|
||||
}
|
||||
provisioner.clearUpdate(resource);
|
||||
doNothing().when(logs).deleteLogStream("old-group", "events", REGION);
|
||||
clearInvocations(logs);
|
||||
|
||||
provisioner.delete(resource, REGION);
|
||||
|
||||
verify(logs).deleteLogStream("old-group", "events", REGION);
|
||||
verify(logs).deleteLogStream("new-group", "events", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedRollbackDeletionPreservesBothAddressesForStackDeletion() {
|
||||
StackResource resource = create("old-group", "events");
|
||||
update(resource, "new-group", "events");
|
||||
doThrow(new AwsException("ServiceUnavailableException", "retry", 500))
|
||||
.when(logs).deleteLogStream("new-group", "events", REGION);
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(resource));
|
||||
assertEquals("events", resource.getPhysicalId());
|
||||
assertTrue(provisioner.hasPendingRollbackCleanup(resource));
|
||||
doNothing().when(logs).deleteLogStream("new-group", "events", REGION);
|
||||
clearInvocations(logs);
|
||||
|
||||
provisioner.delete(resource, REGION);
|
||||
|
||||
verify(logs).deleteLogStream("new-group", "events", REGION);
|
||||
verify(logs).deleteLogStream("old-group", "events", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void finishingFailedRollbackCleanupDoesNotForgetOwnershipOfThePriorStream() {
|
||||
StackResource resource = create("old-group", "events");
|
||||
update(resource, "new-group", "events");
|
||||
doThrow(new AwsException("ServiceUnavailableException", "retry", 500))
|
||||
.when(logs).deleteLogStream("new-group", "events", REGION);
|
||||
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(resource));
|
||||
resource.setStatus("UPDATE_FAILED");
|
||||
doNothing().when(logs).deleteLogStream("new-group", "events", REGION);
|
||||
clearInvocations(logs);
|
||||
|
||||
assertTrue(provisioner.completeUpdate(resource).complete());
|
||||
provisioner.clearUpdate(resource);
|
||||
|
||||
assertTrue(provisioner.hasPendingRollbackCleanup(resource));
|
||||
provisioner.delete(resource, REGION);
|
||||
assertFalse(provisioner.hasPendingRollbackCleanup(resource));
|
||||
verify(logs).deleteLogStream("new-group", "events", REGION);
|
||||
verify(logs).deleteLogStream("old-group", "events", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void newUpdateCleansEarlierPendingReplacementBeforeRecordingAnother() {
|
||||
StackResource resource = create("first-group", "events");
|
||||
update(resource, "second-group", "events");
|
||||
doThrow(new AwsException("ServiceUnavailableException", "retry", 500))
|
||||
.when(logs).deleteLogStream("first-group", "events", REGION);
|
||||
provisioner.completeUpdate(resource);
|
||||
provisioner.clearUpdate(resource);
|
||||
doNothing().when(logs).deleteLogStream("first-group", "events", REGION);
|
||||
clearInvocations(logs);
|
||||
|
||||
update(resource, "third-group", "events");
|
||||
commit(resource);
|
||||
|
||||
verify(logs).deleteLogStream("first-group", "events", REGION);
|
||||
verify(logs).deleteLogStream("second-group", "events", REGION);
|
||||
verify(logs).createLogStream("third-group", "events", REGION);
|
||||
verify(logs, never()).deleteLogStream("third-group", "events", REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void persistedMetadataKeepsTheGroupWhenNamesAreEqual() {
|
||||
StackResource resource = create("old-group", "events");
|
||||
update(resource, "new-group", "events");
|
||||
StackResource restored = resource();
|
||||
restored.setPhysicalId(resource.getPhysicalId());
|
||||
restored.setAttributes(new HashMap<>(resource.getAttributes()));
|
||||
LogsLogStreamCfnProvisioner restarted = new LogsLogStreamCfnProvisioner(logs);
|
||||
clearInvocations(logs);
|
||||
|
||||
assertTrue(restarted.rollbackUpdate(restored));
|
||||
restarted.delete(restored, REGION);
|
||||
|
||||
verify(logs).deleteLogStream("new-group", "events", REGION);
|
||||
verify(logs).deleteLogStream("old-group", "events", REGION);
|
||||
}
|
||||
|
||||
private StackResource create(String group, String name) {
|
||||
StackResource resource = resource();
|
||||
provisioner.provision(resource, props(group, name), context(null));
|
||||
return resource;
|
||||
}
|
||||
|
||||
private void update(StackResource resource, String group, String name) {
|
||||
provisioner.provision(resource, props(group, name), context(resource.getPhysicalId()));
|
||||
}
|
||||
|
||||
private void commit(StackResource resource) {
|
||||
assertTrue(provisioner.completeUpdate(resource).complete());
|
||||
provisioner.clearUpdate(resource);
|
||||
}
|
||||
|
||||
private ProvisionContext context(String prior) {
|
||||
return new ProvisionContext(engine, REGION, ACCOUNT, "my-stack", prior);
|
||||
}
|
||||
|
||||
private static StackResource resource() {
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId("LogStream");
|
||||
resource.setResourceType("AWS::Logs::LogStream");
|
||||
return resource;
|
||||
}
|
||||
|
||||
private static ObjectNode props(String group, String name) {
|
||||
ObjectNode properties = MAPPER.createObjectNode().put("LogGroupName", group);
|
||||
if (name != null) {
|
||||
properties.put("LogStreamName", name);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
@@ -111,6 +111,7 @@ AWS::Lambda::Permission LambdaAddressingCfnProvisioner
|
||||
AWS::Lambda::Url LambdaAddressingCfnProvisioner
|
||||
AWS::Lambda::Version LambdaVersionAliasCfnProvisioner
|
||||
AWS::Logs::LogGroup LogsCfnProvisioner
|
||||
AWS::Logs::LogStream LogsLogStreamCfnProvisioner
|
||||
AWS::Logs::MetricFilter LogsMetricFilterCfnProvisioner
|
||||
AWS::Organizations::Account OrganizationsCfnProvisioner
|
||||
AWS::Organizations::Organization OrganizationsCfnProvisioner
|
||||
|
||||
|
Reference in new issue
Block a user