mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(redshift): provision AWS::Redshift::Cluster through CloudFormation (#3427)
* feat(cloudformation): provision AWS::Redshift::Cluster (create path) * feat(cloudformation): AWS::Redshift::Cluster update and replacement * feat(cloudformation): force replacement on Redshift cluster createOnly property change * feat(cloudformation): force replacement on Redshift cluster DBName change * feat(cloudformation): provision Redshift parameter, subnet and security groups * chore(cloudformation): register Redshift provisioner in inventory and docs * test(cloudformation): end-to-end AWS::Redshift::Cluster stack * docs(redshift): document CloudFormation cluster provisioning * test(cloudformation): assert ClusterSubnetGroupNotFound error code on subnet group deletion * fix(cloudformation): correct attribute handling for Redshift security group provisioning * fix(cloudformation): apply Redshift parameter group Parameters and fix docs ClusterParameterGroup silently dropped Properties.Parameters on both create and update instead of calling ModifyClusterParameterGroup, and did not replace the entity when Description or ParameterGroupFamily changed, even though AWS marks both as replacement properties. Also remove the Id GetAtt claim from the Cluster docs: neither the provisioner nor AWS's own schema expose it for AWS::Redshift::Cluster.
This commit is contained in:
1 parent
55ada9b8a3
commit
e5bd8be405
11 files changed
+1461
-1
No files matched your search
+169
@@ -0,0 +1,169 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.core.waiters.WaiterResponse;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CreateStackRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;
|
||||
import software.amazon.awssdk.services.cloudformation.model.DescribeStacksResponse;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Output;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/**
|
||||
* End-to-end compatibility test provisioning an AWS::Redshift::Cluster
|
||||
* via CloudFormationClient and validating connectivity over JDBC.
|
||||
*/
|
||||
@DisplayName("CloudFormation AWS::Redshift::Cluster")
|
||||
class CloudFormationRedshiftClusterTest {
|
||||
|
||||
private static CloudFormationClient cloudFormation;
|
||||
private static String stackName;
|
||||
private static String clusterId;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
assumeTrue(TestFixtures.isLambdaDispatchAvailable(),
|
||||
"Docker dispatch is unavailable for the Redshift container compatibility test");
|
||||
cloudFormation = TestFixtures.cloudFormationClient();
|
||||
stackName = TestFixtures.uniqueName("compat-cfn-rs");
|
||||
clusterId = stackName + "-wh";
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (cloudFormation != null && stackName != null) {
|
||||
try {
|
||||
cloudFormation.deleteStack(DeleteStackRequest.builder().stackName(stackName).build());
|
||||
waitForDeleted(stackName, 60);
|
||||
} catch (Exception e) {
|
||||
System.err.println("CloudFormation Redshift cleanup skipped: " + e.getMessage());
|
||||
}
|
||||
cloudFormation.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionsRedshiftClusterAndConnectsViaJdbc() throws Exception {
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Warehouse": {
|
||||
"Type": "AWS::Redshift::Cluster",
|
||||
"Properties": {
|
||||
"ClusterIdentifier": "%s",
|
||||
"NodeType": "ra3.large",
|
||||
"MasterUsername": "admin",
|
||||
"MasterUserPassword": "Secret12345",
|
||||
"ClusterType": "single-node",
|
||||
"DBName": "dev"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"Addr": {"Value": {"Fn::GetAtt": ["Warehouse", "Endpoint.Address"]}},
|
||||
"Port": {"Value": {"Fn::GetAtt": ["Warehouse", "Endpoint.Port"]}},
|
||||
"Ns": {"Value": {"Fn::GetAtt": ["Warehouse", "ClusterNamespaceArn"]}}
|
||||
}
|
||||
}""".formatted(clusterId);
|
||||
|
||||
cloudFormation.createStack(CreateStackRequest.builder()
|
||||
.stackName(stackName)
|
||||
.templateBody(template)
|
||||
.build());
|
||||
|
||||
WaiterResponse<DescribeStacksResponse> waiterResponse = cloudFormation.waiter()
|
||||
.waitUntilStackCreateComplete(r -> r.stackName(stackName));
|
||||
|
||||
Stack stack = waiterResponse.matched().response()
|
||||
.orElseGet(() -> cloudFormation.describeStacks(
|
||||
DescribeStacksRequest.builder().stackName(stackName).build()))
|
||||
.stacks().get(0);
|
||||
|
||||
Map<String, String> outputs = stack.outputs().stream()
|
||||
.collect(Collectors.toMap(Output::outputKey, Output::outputValue));
|
||||
|
||||
String addr = outputs.get("Addr");
|
||||
String portStr = outputs.get("Port");
|
||||
String ns = outputs.get("Ns");
|
||||
|
||||
assertThat(addr).isNotBlank();
|
||||
assertThat(portStr).isNotBlank();
|
||||
int port = Integer.parseInt(portStr);
|
||||
assertThat(port).isPositive();
|
||||
assertThat(ns).startsWith("arn:aws:redshift:");
|
||||
|
||||
String connectHost = "host.docker.internal".equalsIgnoreCase(addr)
|
||||
? TestFixtures.proxyHost()
|
||||
: addr;
|
||||
|
||||
try (Connection conn = awaitPostgresConnection(connectHost, port, "admin", "Secret12345");
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet rs = stmt.executeQuery("SELECT 1")) {
|
||||
assertThat(rs.next()).isTrue();
|
||||
assertThat(rs.getInt(1)).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
|
||||
private static Connection awaitPostgresConnection(String host, int port, String username, String password) throws Exception {
|
||||
Instant deadline = Instant.now().plus(Duration.ofSeconds(60));
|
||||
SQLException lastFailure = null;
|
||||
while (Instant.now().isBefore(deadline)) {
|
||||
try {
|
||||
Properties properties = new Properties();
|
||||
properties.setProperty("user", username);
|
||||
properties.setProperty("password", password);
|
||||
properties.setProperty("sslmode", "disable");
|
||||
properties.setProperty("connectTimeout", "5");
|
||||
return DriverManager.getConnection(
|
||||
"jdbc:postgresql://" + host + ":" + port + "/dev",
|
||||
properties);
|
||||
} catch (SQLException e) {
|
||||
lastFailure = e;
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
}
|
||||
throw lastFailure != null
|
||||
? lastFailure
|
||||
: new SQLException("Timed out waiting for Redshift connection at " + host + ":" + port);
|
||||
}
|
||||
|
||||
private static void waitForDeleted(String name, int maxSeconds) throws InterruptedException {
|
||||
long deadline = System.currentTimeMillis() + maxSeconds * 1000L;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
try {
|
||||
List<Stack> stacks = cloudFormation.describeStacks(
|
||||
DescribeStacksRequest.builder().stackName(name).build()).stacks();
|
||||
if (stacks.isEmpty()
|
||||
|| "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString())) {
|
||||
return;
|
||||
}
|
||||
} catch (CloudFormationException e) {
|
||||
if (e.getMessage() != null && e.getMessage().contains("does not exist")) {
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
Thread.sleep(500);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,7 @@ cross-resource references.
|
||||
| ECS | `Cluster`, `TaskDefinition`, `Service`, `CapacityProvider`, `ClusterCapacityProviderAssociations` |
|
||||
| EKS | `Cluster`, `Nodegroup` |
|
||||
| RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` |
|
||||
| Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model) |
|
||||
| EC2 | `VPC`, `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` |
|
||||
| Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` |
|
||||
| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` |
|
||||
|
||||
@@ -71,7 +71,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [Lake Formation](lakeformation.md) | `POST /<Action>` | REST JSON | 16 |
|
||||
| [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 |
|
||||
| [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 8 |
|
||||
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire | 23 |
|
||||
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 23 |
|
||||
| [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 11 |
|
||||
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 24 |
|
||||
| [EMR Serverless](emr-serverless.md) | `/applications/*` | REST JSON | 7 |
|
||||
|
||||
@@ -42,6 +42,35 @@ For running SQL without a PostgreSQL wire connection (the way Lambda and Step Fu
|
||||
| `GetClusterCredentialsWithIAM` | Issue short-lived credentials with the DbUser derived from the caller's IAM identity |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
## CloudFormation
|
||||
|
||||
Floci provisions these resource types:
|
||||
|
||||
- `AWS::Redshift::Cluster`
|
||||
- `AWS::Redshift::ClusterParameterGroup`
|
||||
- `AWS::Redshift::ClusterSubnetGroup`
|
||||
- `AWS::Redshift::ClusterSecurityGroup`
|
||||
|
||||
### Cluster Provisioning and References
|
||||
|
||||
For `AWS::Redshift::Cluster`:
|
||||
|
||||
- `Ref` returns the cluster identifier.
|
||||
- `Fn::GetAtt` exposes `Endpoint.Address`, `Endpoint.Port`, and `ClusterNamespaceArn` (synthesised, stable).
|
||||
|
||||
Replacement occurs if `ClusterIdentifier`, `DBName`, `MasterUsername`, or `ClusterSubnetGroupName` changes. Other properties (such as `NodeType`, `MasterUserPassword`, `ClusterParameterGroupName`, and `VpcSecurityGroupIds`) update in place.
|
||||
|
||||
For `AWS::Redshift::ClusterParameterGroup`, `Parameters` is applied via `ModifyClusterParameterGroup` on both create and update. `Description` and `ParameterGroupFamily` are replacement properties, matching AWS: changing either creates a new parameter group instead of reusing the prior one.
|
||||
|
||||
### Gaps and Limitations
|
||||
|
||||
- `Port` is ignored: Floci assigns the dynamic host proxy port returned in `Endpoint.Port`.
|
||||
- `DBName` other than `dev` is ignored: the emulated PostgreSQL container database is always `dev`.
|
||||
- `NumberOfNodes` is not stored on cluster create: every emulated cluster is backed by a single PostgreSQL container.
|
||||
- `ManageMasterPassword` is rejected: set `MasterUserPassword` instead.
|
||||
- `SnapshotIdentifier` is ignored: a fresh cluster is created instead of restoring from a snapshot.
|
||||
- `AWS::Redshift::ClusterSecurityGroup` is accepted as metadata: Floci does not emulate the legacy EC2-Classic security group model.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Parameter;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Provisions AWS::Redshift::Cluster and its metadata companion types, replacing the generic
|
||||
* unsupported-type stub for AWS::Redshift::*. Injects only RedshiftService; discovered by
|
||||
* CloudFormationResourceRegistry via CDI.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class RedshiftClusterCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftClusterCfnProvisioner.class);
|
||||
|
||||
private static final String CLUSTER = "AWS::Redshift::Cluster";
|
||||
private static final String PARAMETER_GROUP = "AWS::Redshift::ClusterParameterGroup";
|
||||
private static final String SUBNET_GROUP = "AWS::Redshift::ClusterSubnetGroup";
|
||||
private static final String SECURITY_GROUP = "AWS::Redshift::ClusterSecurityGroup";
|
||||
private static final int IDENTIFIER_MAX_LENGTH = 63;
|
||||
private static final int METADATA_NAME_MAX_LENGTH = 255;
|
||||
|
||||
private final RedshiftService redshiftService;
|
||||
|
||||
@Inject
|
||||
public RedshiftClusterCfnProvisioner(RedshiftService redshiftService) {
|
||||
this.redshiftService = redshiftService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(CLUSTER, PARAMETER_GROUP, SUBNET_GROUP, SECURITY_GROUP);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
switch (r.getResourceType()) {
|
||||
case CLUSTER -> {
|
||||
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
|
||||
provisionCluster(r, props, ctx, attributesBefore);
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
case PARAMETER_GROUP -> {
|
||||
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
|
||||
provisionParameterGroup(r, props, ctx);
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
case SUBNET_GROUP -> provisionSubnetGroup(r, props, ctx);
|
||||
case SECURITY_GROUP -> provisionSecurityGroup(r, props, ctx);
|
||||
default -> throw new IllegalStateException(
|
||||
"RedshiftClusterCfnProvisioner cannot provision " + r.getResourceType());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.rollback(resource, this::delete);
|
||||
}
|
||||
|
||||
private void provisionCluster(StackResource r, JsonNode props, ProvisionContext ctx,
|
||||
Map<String, String> attributesBefore) {
|
||||
if (Boolean.parseBoolean(ctx.resolveOptional(props, "ManageMasterPassword"))) {
|
||||
throw new AwsException("ValidationException",
|
||||
"ManageMasterPassword is not emulated by Floci; set MasterUserPassword instead", 400);
|
||||
}
|
||||
String nodeType = ctx.resolveOptional(props, "NodeType");
|
||||
String masterUsername = ctx.resolveOptional(props, "MasterUsername");
|
||||
String masterUserPassword = ctx.resolveOptional(props, "MasterUserPassword");
|
||||
if (masterUserPassword == null || masterUserPassword.isBlank()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"MasterUserPassword is required unless ManageMasterPassword is set", 400);
|
||||
}
|
||||
String subnetGroup = ctx.resolveOptional(props, "ClusterSubnetGroupName");
|
||||
List<String> securityGroups = ctx.resolveStringList(props, "VpcSecurityGroupIds");
|
||||
|
||||
String dbName = ctx.resolveOptional(props, "DBName");
|
||||
String priorDbName = attributesBefore.get("Floci::DBName");
|
||||
boolean dbNameChanged = ctx.isUpdate() && dbName != null && priorDbName != null && !dbName.equals(priorDbName);
|
||||
|
||||
String explicitId = ctx.resolveOptional(props, "ClusterIdentifier");
|
||||
Cluster prior = ctx.isUpdate() ? findExistingCluster(ctx.priorPhysicalId()) : null;
|
||||
boolean createOnlyChanged = dbNameChanged || (prior != null && (
|
||||
(masterUsername != null && !masterUsername.equals(prior.getMasterUsername()))
|
||||
|| (subnetGroup != null && !Objects.equals(subnetGroup, prior.getClusterSubnetGroupName()))
|
||||
));
|
||||
|
||||
String id;
|
||||
if (createOnlyChanged && (explicitId == null || explicitId.equals(ctx.priorPhysicalId()))) {
|
||||
if (explicitId != null && !explicitId.isBlank()) {
|
||||
id = replacementId(explicitId, IDENTIFIER_MAX_LENGTH, true);
|
||||
} else {
|
||||
id = ctx.generatePhysicalName(r.getLogicalId(), IDENTIFIER_MAX_LENGTH, true);
|
||||
}
|
||||
} else {
|
||||
id = ctx.stablePhysicalName(explicitId, r.getLogicalId(), IDENTIFIER_MAX_LENGTH, true);
|
||||
}
|
||||
|
||||
warnUnsupported(props, ctx, id);
|
||||
|
||||
// provision() is the update path too. A same-id cluster already on file is reconciled;
|
||||
// a derived id that differs from the prior physical id is a replacement handled via ReplacementCleanup.
|
||||
Cluster cluster = ctx.reusesPriorEntity(id)
|
||||
? redshiftService.modifyCluster(id, nodeType, numberOfNodes(props, ctx),
|
||||
masterUserPassword, ctx.resolveOptional(props, "ClusterParameterGroupName"),
|
||||
securityGroups)
|
||||
: redshiftService.createCluster(id, nodeType, masterUsername, masterUserPassword,
|
||||
subnetGroup, securityGroups);
|
||||
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
if (!tags.isEmpty()) {
|
||||
redshiftService.createTags(id, tags);
|
||||
}
|
||||
|
||||
r.setPhysicalId(id);
|
||||
if (dbName != null && !dbName.isBlank()) {
|
||||
r.getAttributes().put("Floci::DBName", dbName);
|
||||
}
|
||||
if (cluster.getEndpoint() != null) {
|
||||
r.getAttributes().put("Endpoint.Address", cluster.getEndpoint().getAddress());
|
||||
r.getAttributes().put("Endpoint.Port", String.valueOf(cluster.getEndpoint().getPort()));
|
||||
}
|
||||
r.getAttributes().put("ClusterNamespaceArn", namespaceArn(ctx, id));
|
||||
}
|
||||
|
||||
private Integer numberOfNodes(JsonNode props, ProvisionContext ctx) {
|
||||
String raw = ctx.resolveOptional(props, "NumberOfNodes");
|
||||
return raw == null || raw.isBlank() ? null : Integer.valueOf(raw);
|
||||
}
|
||||
|
||||
/** Deterministic from the cluster identity: enough for a template that feeds it to a policy. */
|
||||
private String namespaceArn(ProvisionContext ctx, String clusterId) {
|
||||
UUID ns = UUID.nameUUIDFromBytes(
|
||||
(ctx.accountId() + ":" + clusterId).getBytes(StandardCharsets.UTF_8));
|
||||
return "arn:aws:redshift:" + ctx.region() + ":" + ctx.accountId() + ":namespace:" + ns;
|
||||
}
|
||||
|
||||
private void warnUnsupported(JsonNode props, ProvisionContext ctx, String id) {
|
||||
String dbName = ctx.resolveOptional(props, "DBName");
|
||||
if (dbName != null && !dbName.isBlank() && !"dev".equals(dbName)) {
|
||||
LOG.warnv("Cluster {0}: DBName={1} ignored, the emulated container database is always dev", id, dbName);
|
||||
}
|
||||
if (ctx.resolveOptional(props, "Port") != null) {
|
||||
LOG.warnv("Cluster {0}: Port ignored, Floci assigns the host proxy port", id);
|
||||
}
|
||||
if (!ctx.isUpdate() && ctx.resolveOptional(props, "ClusterParameterGroupName") != null) {
|
||||
LOG.warnv("Cluster {0}: ClusterParameterGroupName is only applied on update", id);
|
||||
}
|
||||
}
|
||||
|
||||
private void provisionParameterGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String explicitName = ctx.resolveOptional(props, "ParameterGroupName");
|
||||
String family = ctx.resolveOptional(props, "ParameterGroupFamily");
|
||||
String description = ctx.resolveOptional(props, "Description");
|
||||
|
||||
// Description and ParameterGroupFamily are AWS replacement properties; ParameterGroupName
|
||||
// already forces replacement because a changed explicit name yields a different id below.
|
||||
ClusterParameterGroup prior = ctx.isUpdate() ? findExistingParameterGroup(ctx.priorPhysicalId()) : null;
|
||||
boolean createOnlyChanged = prior != null && (
|
||||
(family != null && !family.equals(prior.getParameterGroupFamily()))
|
||||
|| (description != null && !description.equals(prior.getDescription())));
|
||||
|
||||
String id;
|
||||
if (createOnlyChanged && (explicitName == null || explicitName.equals(ctx.priorPhysicalId()))) {
|
||||
String base = explicitName != null && !explicitName.isBlank() ? explicitName : r.getLogicalId();
|
||||
id = replacementId(base, METADATA_NAME_MAX_LENGTH, false);
|
||||
} else {
|
||||
id = ctx.stablePhysicalName(explicitName, r.getLogicalId(), METADATA_NAME_MAX_LENGTH, false);
|
||||
}
|
||||
|
||||
if (!ctx.reusesPriorEntity(id)) {
|
||||
redshiftService.createClusterParameterGroup(id, family, description);
|
||||
}
|
||||
|
||||
List<Parameter> parameters = parseParameters(props);
|
||||
if (!parameters.isEmpty()) {
|
||||
redshiftService.modifyClusterParameterGroup(id, parameters);
|
||||
}
|
||||
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
if (!tags.isEmpty()) {
|
||||
redshiftService.createTags(id, tags);
|
||||
}
|
||||
|
||||
r.setPhysicalId(id);
|
||||
}
|
||||
|
||||
private ClusterParameterGroup findExistingParameterGroup(String parameterGroupName) {
|
||||
if (parameterGroupName == null || parameterGroupName.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return redshiftService.getClusterParameterGroup(parameterGroupName).orElse(null);
|
||||
}
|
||||
|
||||
private List<Parameter> parseParameters(JsonNode props) {
|
||||
JsonNode params = props != null ? props.get("Parameters") : null;
|
||||
if (params == null || !params.isArray()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Parameter> parsed = new ArrayList<>();
|
||||
for (JsonNode p : params) {
|
||||
String name = p.path("ParameterName").asText(null);
|
||||
if (name == null || name.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
parsed.add(new Parameter(name, p.path("ParameterValue").asText(null)));
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private void provisionSubnetGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String explicitName = ctx.resolveOptional(props, "ClusterSubnetGroupName");
|
||||
String id = ctx.stablePhysicalName(explicitName, r.getLogicalId(), METADATA_NAME_MAX_LENGTH, false);
|
||||
String description = ctx.resolveOptional(props, "Description");
|
||||
List<String> subnetIds = ctx.resolveStringList(props, "SubnetIds");
|
||||
|
||||
if (ctx.reusesPriorEntity(id)) {
|
||||
redshiftService.modifyClusterSubnetGroup(id, description, subnetIds);
|
||||
} else {
|
||||
redshiftService.createClusterSubnetGroup(id, description, null, subnetIds);
|
||||
}
|
||||
|
||||
r.setPhysicalId(id);
|
||||
r.getAttributes().put("ClusterSubnetGroupName", id);
|
||||
}
|
||||
|
||||
private void provisionSecurityGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String id = ctx.stablePhysicalName(null, r.getLogicalId(), METADATA_NAME_MAX_LENGTH, false);
|
||||
r.setPhysicalId(id);
|
||||
r.getAttributes().put("Id", id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
if (resourceType == null || physicalId == null) {
|
||||
return;
|
||||
}
|
||||
switch (resourceType) {
|
||||
case CLUSTER -> CfnDeletes.safeDelete("Redshift cluster", physicalId,
|
||||
() -> redshiftService.deleteCluster(physicalId), "ClusterNotFound");
|
||||
case PARAMETER_GROUP -> CfnDeletes.safeDelete("Redshift parameter group", physicalId,
|
||||
() -> redshiftService.deleteClusterParameterGroup(physicalId),
|
||||
"ClusterParameterGroupNotFound", "ClusterParameterGroupNotFoundFault");
|
||||
case SUBNET_GROUP -> CfnDeletes.safeDelete("Redshift subnet group", physicalId,
|
||||
() -> redshiftService.deleteClusterSubnetGroup(physicalId),
|
||||
"ClusterSubnetGroupNotFound", "ClusterSubnetGroupNotFoundFault");
|
||||
case SECURITY_GROUP -> {
|
||||
// Accept-only, delete is a no-op
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Cluster findExistingCluster(String clusterIdentifier) {
|
||||
if (clusterIdentifier == null || clusterIdentifier.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
List<Cluster> list = redshiftService.describeClusters(clusterIdentifier);
|
||||
return (list != null && !list.isEmpty()) ? list.get(0) : null;
|
||||
} catch (AwsException e) {
|
||||
if ("ClusterNotFound".equals(e.getErrorCode())) {
|
||||
return null;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private String replacementId(String baseId, int maxLength, boolean lowercase) {
|
||||
String suffix = "-" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
|
||||
int keep = Math.max(0, maxLength - suffix.length());
|
||||
String prefix = baseId.length() > keep ? baseId.substring(0, keep) : baseId;
|
||||
while (prefix.endsWith("-")) {
|
||||
prefix = prefix.substring(0, prefix.length() - 1);
|
||||
}
|
||||
String result = prefix + suffix;
|
||||
return lowercase ? result.toLowerCase() : result;
|
||||
}
|
||||
}
|
||||
+15
@@ -65,6 +65,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaVer
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.PipesCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.RdsCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.RedshiftClusterCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.Route53CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.S3CfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.SchedulerScheduleGroupCfnProvisioner;
|
||||
@@ -98,6 +99,7 @@ import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.pipes.PipesService;
|
||||
import io.github.hectorvent.floci.services.rds.RdsService;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.route53.Route53Service;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.scheduler.SchedulerService;
|
||||
@@ -184,6 +186,7 @@ final class CfnProvisionerFixture {
|
||||
private SqsService sqsService;
|
||||
private WafV2Service wafV2Service;
|
||||
private BackupService backupService;
|
||||
private RedshiftService redshiftService;
|
||||
private CloudFormationResourceRegistry resourceRegistry;
|
||||
private boolean registryChosenByTest;
|
||||
private CfnDynamicReferences dynamicReferences;
|
||||
@@ -355,6 +358,9 @@ final class CfnProvisionerFixture {
|
||||
if (schedulerService != null) {
|
||||
discovered.add(new SchedulerScheduleGroupCfnProvisioner(schedulerService));
|
||||
}
|
||||
if (redshiftService != null) {
|
||||
discovered.add(new RedshiftClusterCfnProvisioner(redshiftService));
|
||||
}
|
||||
return discovered;
|
||||
}
|
||||
|
||||
@@ -593,6 +599,15 @@ final class CfnProvisionerFixture {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder redshiftService(RedshiftService s) {
|
||||
this.redshiftService = s;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder redshift(RedshiftService s) {
|
||||
return redshiftService(s);
|
||||
}
|
||||
|
||||
public Builder registry(CloudFormationResourceRegistry v) {
|
||||
this.resourceRegistry = v;
|
||||
this.registryChosenByTest = true;
|
||||
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.awaitility.core.ConditionTimeoutException;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* End-to-end integration test provisioning AWS::Redshift::Cluster,
|
||||
* AWS::Redshift::ClusterParameterGroup, AWS::Redshift::ClusterSubnetGroup,
|
||||
* and AWS::Redshift::ClusterSecurityGroup through CloudFormation stacks.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class RedshiftClusterCfnIntegrationTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftClusterCfnIntegrationTest.class);
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260903/us-east-1/cloudformation/aws4_request";
|
||||
private static final String REDSHIFT_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260903/us-east-1/redshift/aws4_request";
|
||||
|
||||
private final List<String> stacksToCleanup = new ArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void configure() {
|
||||
Assumptions.assumeTrue(dockerAvailable(), "Docker is required for this integration test");
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private static boolean dockerAvailable() {
|
||||
try {
|
||||
Process p = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
|
||||
.redirectErrorStream(true).start();
|
||||
return p.waitFor() == 0;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUp() {
|
||||
for (String stack : stacksToCleanup) {
|
||||
try {
|
||||
cloudFormation(stack, "DeleteStack", null);
|
||||
awaitStackDeleted(stack);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to clean up stack {0}: {1}", stack, e.getMessage());
|
||||
}
|
||||
}
|
||||
stacksToCleanup.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStackProvisionsRealClusterWithEndpointOutputs() throws Exception {
|
||||
String stackName = "rs-cfn-it-" + System.currentTimeMillis();
|
||||
String clusterId = stackName + "-wh";
|
||||
stacksToCleanup.add(stackName);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Warehouse": {
|
||||
"Type": "AWS::Redshift::Cluster",
|
||||
"Properties": {
|
||||
"ClusterIdentifier": "%s",
|
||||
"NodeType": "ra3.large",
|
||||
"MasterUsername": "admin",
|
||||
"MasterUserPassword": "Secret12345",
|
||||
"ClusterType": "single-node",
|
||||
"DBName": "dev"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"Addr": {"Value": {"Fn::GetAtt": ["Warehouse", "Endpoint.Address"]}},
|
||||
"Port": {"Value": {"Fn::GetAtt": ["Warehouse", "Endpoint.Port"]}},
|
||||
"Ns": {"Value": {"Fn::GetAtt": ["Warehouse", "ClusterNamespaceArn"]}}
|
||||
}
|
||||
}""".formatted(clusterId);
|
||||
|
||||
cloudFormation(stackName, "CreateStack", template);
|
||||
|
||||
String stacks = describeStacks(stackName, "CREATE_COMPLETE");
|
||||
String addr = outputValue(stacks, "Addr");
|
||||
String portStr = outputValue(stacks, "Port");
|
||||
String ns = outputValue(stacks, "Ns");
|
||||
|
||||
assertNotNull(addr, "Endpoint.Address output must not be null");
|
||||
assertFalse(addr.isBlank(), "Endpoint.Address output must not be blank");
|
||||
assertNotNull(portStr, "Endpoint.Port output must not be null");
|
||||
int port = Integer.parseInt(portStr);
|
||||
assertTrue(port > 0, "Endpoint.Port must be a positive integer: " + port);
|
||||
assertNotNull(ns, "ClusterNamespaceArn output must not be null");
|
||||
assertTrue(ns.startsWith("arn:aws:redshift:"),
|
||||
"ClusterNamespaceArn output must start with arn:aws:redshift:, got: " + ns);
|
||||
|
||||
// Fall back to 127.0.0.1 when hostname is host.docker.internal to avoid CI resolution issues
|
||||
String connectHost = "host.docker.internal".equalsIgnoreCase(addr) ? "127.0.0.1" : addr;
|
||||
try (Connection conn = waitForConnection(connectHost, port, "admin", "Secret12345");
|
||||
Statement st = conn.createStatement();
|
||||
ResultSet rs = st.executeQuery("SELECT 1")) {
|
||||
assertTrue(rs.next());
|
||||
assertEquals(1, rs.getInt(1));
|
||||
}
|
||||
|
||||
cloudFormation(stackName, "DeleteStack", null);
|
||||
awaitStackDeleted(stackName);
|
||||
stacksToCleanup.remove(stackName);
|
||||
|
||||
assertClusterNotFound(clusterId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStackProvisionsParameterAndSubnetGroups() throws Exception {
|
||||
String stackName = "rs-groups-it-" + System.currentTimeMillis();
|
||||
String pgName = stackName + "-pg";
|
||||
String sgName = stackName + "-sg";
|
||||
stacksToCleanup.add(stackName);
|
||||
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"ParamGroup": {
|
||||
"Type": "AWS::Redshift::ClusterParameterGroup",
|
||||
"Properties": {
|
||||
"ParameterGroupName": "%s",
|
||||
"ParameterGroupFamily": "redshift-1.0",
|
||||
"Description": "Test parameter group for CFN integration"
|
||||
}
|
||||
},
|
||||
"SubnetGroup": {
|
||||
"Type": "AWS::Redshift::ClusterSubnetGroup",
|
||||
"Properties": {
|
||||
"ClusterSubnetGroupName": "%s",
|
||||
"Description": "Test subnet group for CFN integration",
|
||||
"SubnetIds": ["subnet-12345678", "subnet-87654321"]
|
||||
}
|
||||
},
|
||||
"SecurityGroup": {
|
||||
"Type": "AWS::Redshift::ClusterSecurityGroup",
|
||||
"Properties": {
|
||||
"Description": "Test security group for CFN integration"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"PgRef": {"Value": {"Ref": "ParamGroup"}},
|
||||
"SgRef": {"Value": {"Ref": "SubnetGroup"}},
|
||||
"SgName": {"Value": {"Fn::GetAtt": ["SubnetGroup", "ClusterSubnetGroupName"]}},
|
||||
"SecurityGroupRef": {"Value": {"Ref": "SecurityGroup"}},
|
||||
"SecurityGroupId": {"Value": {"Fn::GetAtt": ["SecurityGroup", "Id"]}}
|
||||
}
|
||||
}""".formatted(pgName, sgName);
|
||||
|
||||
cloudFormation(stackName, "CreateStack", template);
|
||||
|
||||
String stacks = describeStacks(stackName, "CREATE_COMPLETE");
|
||||
assertEquals(pgName, outputValue(stacks, "PgRef"));
|
||||
assertEquals(sgName, outputValue(stacks, "SgRef"));
|
||||
assertEquals(sgName, outputValue(stacks, "SgName"));
|
||||
assertEquals(outputValue(stacks, "SecurityGroupRef"), outputValue(stacks, "SecurityGroupId"));
|
||||
|
||||
assertParameterGroupExists(pgName, "redshift-1.0");
|
||||
assertSubnetGroupExists(sgName);
|
||||
|
||||
cloudFormation(stackName, "DeleteStack", null);
|
||||
awaitStackDeleted(stackName);
|
||||
stacksToCleanup.remove(stackName);
|
||||
|
||||
assertParameterGroupNotFound(pgName);
|
||||
assertSubnetGroupNotFound(sgName);
|
||||
}
|
||||
|
||||
private static Connection waitForConnection(String host, int port, String username, String password) throws SQLException {
|
||||
try {
|
||||
return Awaitility.await()
|
||||
.atMost(Duration.ofSeconds(30))
|
||||
.pollInterval(Duration.ofMillis(500))
|
||||
.ignoreExceptions()
|
||||
.until(() -> DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/dev", username, password), Objects::nonNull);
|
||||
} catch (ConditionTimeoutException e) {
|
||||
return DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/dev", username, password);
|
||||
}
|
||||
}
|
||||
|
||||
private static void cloudFormation(String stack, String action, String templateBody) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", stack);
|
||||
if (templateBody != null) {
|
||||
request.formParam("TemplateBody", templateBody);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String describeStacks(String stack, String expectedStatus) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stack)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private static void awaitStackDeleted(String stack) throws InterruptedException {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
String body = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stack)
|
||||
.when().post("/").then().extract().asString();
|
||||
if (body.contains("does not exist")) {
|
||||
return;
|
||||
}
|
||||
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
|
||||
fail("Stack delete failed: " + body);
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
fail("Stack " + stack + " was not deleted within the timeout");
|
||||
}
|
||||
|
||||
private static void assertClusterNotFound(String clusterId) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", REDSHIFT_AUTH)
|
||||
.formParam("Action", "DescribeClusters")
|
||||
.formParam("ClusterIdentifier", clusterId)
|
||||
.when().post("/").then()
|
||||
.statusCode(404)
|
||||
.body(containsString("<Code>ClusterNotFound</Code>"));
|
||||
}
|
||||
|
||||
private static void assertParameterGroupExists(String pgName, String expectedFamily) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", REDSHIFT_AUTH)
|
||||
.formParam("Action", "DescribeClusterParameterGroups")
|
||||
.formParam("ParameterGroupName", pgName)
|
||||
.when().post("/").then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<ParameterGroupName>" + pgName + "</ParameterGroupName>"))
|
||||
.body(containsString("<ParameterGroupFamily>" + expectedFamily + "</ParameterGroupFamily>"));
|
||||
}
|
||||
|
||||
private static void assertParameterGroupNotFound(String pgName) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", REDSHIFT_AUTH)
|
||||
.formParam("Action", "DescribeClusterParameterGroups")
|
||||
.formParam("ParameterGroupName", pgName)
|
||||
.when().post("/").then()
|
||||
.statusCode(404)
|
||||
.body(containsString("<Code>ClusterParameterGroupNotFound</Code>"));
|
||||
}
|
||||
|
||||
private static void assertSubnetGroupExists(String sgName) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", REDSHIFT_AUTH)
|
||||
.formParam("Action", "DescribeClusterSubnetGroups")
|
||||
.formParam("ClusterSubnetGroupName", sgName)
|
||||
.when().post("/").then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<ClusterSubnetGroupName>" + sgName + "</ClusterSubnetGroupName>"));
|
||||
}
|
||||
|
||||
private static void assertSubnetGroupNotFound(String sgName) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", REDSHIFT_AUTH)
|
||||
.formParam("Action", "DescribeClusterSubnetGroups")
|
||||
.formParam("ClusterSubnetGroupName", sgName)
|
||||
.when().post("/").then()
|
||||
.statusCode(404)
|
||||
.body(containsString("<Code>ClusterSubnetGroupNotFound</Code>"));
|
||||
}
|
||||
|
||||
private static String outputValue(String xml, String key) {
|
||||
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
|
||||
}
|
||||
}
|
||||
+606
@@ -0,0 +1,606 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Parameter;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RedshiftClusterCfnProvisionerTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode n = inv.getArgument(0);
|
||||
return n == null || n.isNull() ? null : n.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
when(engine.resolveStringList(any())).thenAnswer(inv -> {
|
||||
JsonNode n = inv.getArgument(0);
|
||||
List<String> out = new ArrayList<>();
|
||||
if (n != null && n.isArray()) {
|
||||
n.forEach(e -> out.add(e.asText()));
|
||||
}
|
||||
return out;
|
||||
});
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "test-stack", priorPhysicalId);
|
||||
}
|
||||
|
||||
private Cluster availableCluster(String id) {
|
||||
Cluster c = new Cluster();
|
||||
c.setClusterIdentifier(id);
|
||||
c.setEndpoint(new Endpoint("host-" + id, 5439));
|
||||
return c;
|
||||
}
|
||||
|
||||
private JsonNode json(String raw) {
|
||||
try {
|
||||
return MAPPER.readTree(raw);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void resourceTypesCoversAllFour() {
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(mock(RedshiftService.class));
|
||||
assertEquals(Set.of("AWS::Redshift::Cluster", "AWS::Redshift::ClusterParameterGroup",
|
||||
"AWS::Redshift::ClusterSubnetGroup", "AWS::Redshift::ClusterSecurityGroup"),
|
||||
p.resourceTypes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionThrowsOnUnknownResourceType() {
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(mock(RedshiftService.class));
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::UnknownType");
|
||||
r.setLogicalId("Unknown");
|
||||
assertThrows(IllegalStateException.class, () -> p.provision(r, json("{}"), ctx(null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionParameterGroupMapsToService() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
|
||||
r.setLogicalId("Params");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"ParameterGroupName":"pg1","ParameterGroupFamily":"redshift-1.0","Description":"d"}"""), ctx(null));
|
||||
|
||||
verify(service).createClusterParameterGroup("pg1", "redshift-1.0", "d");
|
||||
assertEquals("pg1", r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionParameterGroupWithGeneratedNameAndTags() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
|
||||
r.setLogicalId("Params");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"ParameterGroupFamily":"redshift-1.0","Description":"d",
|
||||
"Tags":[{"Key":"env","Value":"test"}]}"""), ctx(null));
|
||||
|
||||
assertNotNull(r.getPhysicalId());
|
||||
verify(service).createClusterParameterGroup(eq(r.getPhysicalId()), eq("redshift-1.0"), eq("d"));
|
||||
verify(service).createTags(r.getPhysicalId(), Map.of("env", "test"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionParameterGroupReusesPriorEntityWithoutCallingCreate() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
ClusterParameterGroup existing = new ClusterParameterGroup("pg1", "redshift-1.0", "d");
|
||||
when(service.getClusterParameterGroup("pg1")).thenReturn(Optional.of(existing));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
|
||||
r.setLogicalId("Params");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"ParameterGroupName":"pg1","ParameterGroupFamily":"redshift-1.0","Description":"d",
|
||||
"Parameters":[{"ParameterName":"wlm_json_configuration","ParameterValue":"[]"}]}"""), ctx("pg1"));
|
||||
|
||||
verify(service, never()).createClusterParameterGroup(anyString(), anyString(), anyString());
|
||||
assertEquals("pg1", r.getPhysicalId());
|
||||
ArgumentCaptor<List<Parameter>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(service).modifyClusterParameterGroup(eq("pg1"), captor.capture());
|
||||
assertEquals(1, captor.getValue().size());
|
||||
assertEquals("wlm_json_configuration", captor.getValue().get(0).getParameterName());
|
||||
assertEquals("[]", captor.getValue().get(0).getParameterValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionParameterGroupAppliesParametersOnCreate() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
|
||||
r.setLogicalId("Params");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"ParameterGroupName":"pg1","ParameterGroupFamily":"redshift-1.0","Description":"d",
|
||||
"Parameters":[{"ParameterName":"enable_user_activity_logging","ParameterValue":"true"}]}"""), ctx(null));
|
||||
|
||||
verify(service).createClusterParameterGroup("pg1", "redshift-1.0", "d");
|
||||
ArgumentCaptor<List<Parameter>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(service).modifyClusterParameterGroup(eq("pg1"), captor.capture());
|
||||
assertEquals(1, captor.getValue().size());
|
||||
assertEquals("enable_user_activity_logging", captor.getValue().get(0).getParameterName());
|
||||
assertEquals("true", captor.getValue().get(0).getParameterValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingParameterGroupDescriptionTriggersReplacement() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
ClusterParameterGroup existing = new ClusterParameterGroup("pg1", "redshift-1.0", "old description");
|
||||
when(service.getClusterParameterGroup("pg1")).thenReturn(Optional.of(existing));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
|
||||
r.setLogicalId("Params");
|
||||
r.setPhysicalId("pg1");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"ParameterGroupName":"pg1","ParameterGroupFamily":"redshift-1.0","Description":"new description"}"""),
|
||||
ctx("pg1"));
|
||||
|
||||
assertNotEquals("pg1", r.getPhysicalId());
|
||||
assertEquals("pg1", p.updateCleanupPhysicalId(r));
|
||||
assertTrue(p.hasReplacementUpdate(r));
|
||||
verify(service).createClusterParameterGroup(eq(r.getPhysicalId()), eq("redshift-1.0"), eq("new description"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingParameterGroupFamilyTriggersReplacement() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
ClusterParameterGroup existing = new ClusterParameterGroup("pg1", "redshift-1.0", "d");
|
||||
when(service.getClusterParameterGroup("pg1")).thenReturn(Optional.of(existing));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
|
||||
r.setLogicalId("Params");
|
||||
r.setPhysicalId("pg1");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"ParameterGroupName":"pg1","ParameterGroupFamily":"redshift-2.0","Description":"d"}"""), ctx("pg1"));
|
||||
|
||||
assertNotEquals("pg1", r.getPhysicalId());
|
||||
assertEquals("pg1", p.updateCleanupPhysicalId(r));
|
||||
assertTrue(p.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteParameterGroupToleratesNotFound() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
doThrow(new AwsException("ClusterParameterGroupNotFound", "gone", 404))
|
||||
.when(service).deleteClusterParameterGroup("pg1");
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
assertDoesNotThrow(() -> p.delete("AWS::Redshift::ClusterParameterGroup", "pg1", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteParameterGroupAndSubnetGroupTolerateFaultSuffix() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
doThrow(new AwsException("ClusterParameterGroupNotFoundFault", "gone", 404))
|
||||
.when(service).deleteClusterParameterGroup("pg1");
|
||||
doThrow(new AwsException("ClusterSubnetGroupNotFoundFault", "gone", 404))
|
||||
.when(service).deleteClusterSubnetGroup("sg1");
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
assertDoesNotThrow(() -> p.delete("AWS::Redshift::ClusterParameterGroup", "pg1", "us-east-1"));
|
||||
assertDoesNotThrow(() -> p.delete("AWS::Redshift::ClusterSubnetGroup", "sg1", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteParameterGroupPropagatesUnexpectedError() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
doThrow(new AwsException("InternalFailure", "boom", 500))
|
||||
.when(service).deleteClusterParameterGroup("pg1");
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> p.delete("AWS::Redshift::ClusterParameterGroup", "pg1", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionSubnetGroupMapsToServiceAndReconcilesOnUpdate() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::ClusterSubnetGroup");
|
||||
r.setLogicalId("Subnets");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"ClusterSubnetGroupName":"sg1","Description":"d","SubnetIds":["subnet-a","subnet-b"]}"""), ctx(null));
|
||||
verify(service).createClusterSubnetGroup("sg1", "d", null, List.of("subnet-a", "subnet-b"));
|
||||
assertEquals("sg1", r.getPhysicalId());
|
||||
assertEquals("sg1", r.getAttributes().get("ClusterSubnetGroupName"));
|
||||
|
||||
p.provision(r, json("""
|
||||
{"ClusterSubnetGroupName":"sg1","Description":"d2","SubnetIds":["subnet-a"]}"""), ctx("sg1"));
|
||||
verify(service).modifyClusterSubnetGroup("sg1", "d2", List.of("subnet-a"));
|
||||
assertEquals("sg1", r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionSubnetGroupWithGeneratedName() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::ClusterSubnetGroup");
|
||||
r.setLogicalId("Subnets");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"Description":"d","SubnetIds":["subnet-1"]}"""), ctx(null));
|
||||
|
||||
assertNotNull(r.getPhysicalId());
|
||||
assertEquals(r.getPhysicalId(), r.getAttributes().get("ClusterSubnetGroupName"));
|
||||
verify(service).createClusterSubnetGroup(eq(r.getPhysicalId()), eq("d"), isNull(), eq(List.of("subnet-1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSubnetGroupToleratesNotFound() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
doThrow(new AwsException("ClusterSubnetGroupNotFound", "gone", 404))
|
||||
.when(service).deleteClusterSubnetGroup("sg1");
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
assertDoesNotThrow(() -> p.delete("AWS::Redshift::ClusterSubnetGroup", "sg1", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSubnetGroupPropagatesUnexpectedError() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
doThrow(new AwsException("InternalFailure", "boom", 500))
|
||||
.when(service).deleteClusterSubnetGroup("sg1");
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> p.delete("AWS::Redshift::ClusterSubnetGroup", "sg1", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionSecurityGroupIsAcceptOnly() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::ClusterSecurityGroup");
|
||||
r.setLogicalId("SecGroup");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"Description":"sg desc"}"""), ctx(null));
|
||||
|
||||
assertNotNull(r.getPhysicalId());
|
||||
assertEquals(r.getPhysicalId(), r.getAttributes().get("Id"));
|
||||
verifyNoInteractions(service);
|
||||
assertDoesNotThrow(() -> p.delete("AWS::Redshift::ClusterSecurityGroup", r.getPhysicalId(), "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionCreatesClusterAndSetsRefAndEndpointAttributes() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
when(service.createCluster(eq("my-cluster"), eq("ra3.large"), eq("admin"), eq("Secret123"),
|
||||
isNull(), anyList())).thenReturn(availableCluster("my-cluster"));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("Warehouse");
|
||||
JsonNode props = json("""
|
||||
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.large",
|
||||
"MasterUsername":"admin","MasterUserPassword":"Secret123",
|
||||
"ClusterType":"single-node","DBName":"dev"}""");
|
||||
|
||||
p.provision(r, props, ctx(null));
|
||||
|
||||
assertEquals("my-cluster", r.getPhysicalId());
|
||||
assertEquals("host-my-cluster", r.getAttributes().get("Endpoint.Address"));
|
||||
assertEquals("5439", r.getAttributes().get("Endpoint.Port"));
|
||||
assertFalse(r.getAttributes().containsKey("Id"));
|
||||
assertTrue(r.getAttributes().get("ClusterNamespaceArn")
|
||||
.startsWith("arn:aws:redshift:us-east-1:000000000000:namespace:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionGeneratesLowercaseIdentifierWhenAbsent() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
when(service.createCluster(anyString(), anyString(), anyString(), anyString(), any(), anyList()))
|
||||
.thenAnswer(inv -> availableCluster(inv.getArgument(0)));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("MyWarehouse");
|
||||
p.provision(r, json("""
|
||||
{"NodeType":"ra3.large","MasterUsername":"admin","MasterUserPassword":"Secret123"}"""),
|
||||
ctx(null));
|
||||
|
||||
assertEquals(r.getPhysicalId().toLowerCase(), r.getPhysicalId());
|
||||
assertTrue(r.getPhysicalId().length() <= 63);
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionRejectsManageMasterPassword() {
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(mock(RedshiftService.class));
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("W");
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> p.provision(r, json("""
|
||||
{"NodeType":"ra3.large","MasterUsername":"admin","ManageMasterPassword":true}"""), ctx(null)));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionRejectsMissingMasterPassword() {
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(mock(RedshiftService.class));
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("W");
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> p.provision(r, json("""
|
||||
{"NodeType":"ra3.large","MasterUsername":"admin"}"""), ctx(null)));
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provisionAppliesTags() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
when(service.createCluster(anyString(), anyString(), anyString(), anyString(), any(), anyList()))
|
||||
.thenReturn(availableCluster("my-cluster"));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("W");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.large","MasterUsername":"admin",
|
||||
"MasterUserPassword":"Secret123","Tags":[{"Key":"env","Value":"dev"}]}"""), ctx(null));
|
||||
|
||||
verify(service).createTags("my-cluster", Map.of("env", "dev"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteCallsDeleteClusterAndToleratesNotFound() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
doThrow(new AwsException("ClusterNotFound", "gone", 404)).when(service).deleteCluster("my-cluster");
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
assertDoesNotThrow(() -> p.delete("AWS::Redshift::Cluster", "my-cluster", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePropagatesUnexpectedError() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
doThrow(new AwsException("InternalFailure", "boom", 500)).when(service).deleteCluster("my-cluster");
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> p.delete("AWS::Redshift::Cluster", "my-cluster", "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateInPlaceCallsModifyCluster() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
when(service.modifyCluster(eq("my-cluster"), eq("ra3.4xlarge"), isNull(), eq("NewSecret9"),
|
||||
isNull(), anyList())).thenReturn(availableCluster("my-cluster"));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("W");
|
||||
p.provision(r, json("""
|
||||
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.4xlarge","MasterUsername":"admin",
|
||||
"MasterUserPassword":"NewSecret9"}"""), ctx("my-cluster"));
|
||||
|
||||
verify(service).modifyCluster(eq("my-cluster"), eq("ra3.4xlarge"), isNull(), eq("NewSecret9"),
|
||||
isNull(), anyList());
|
||||
verify(service, never()).createCluster(anyString(), anyString(), anyString(), anyString(), any(), anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementCreatesNewClusterAndReportsOldIdForCleanup() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
when(service.createCluster(eq("new-name"), anyString(), anyString(), anyString(), any(), anyList()))
|
||||
.thenReturn(availableCluster("new-name"));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("W");
|
||||
// prior id "old-name" differs from the template's new ClusterIdentifier "new-name"
|
||||
p.provision(r, json("""
|
||||
{"ClusterIdentifier":"new-name","NodeType":"ra3.large","MasterUsername":"admin",
|
||||
"MasterUserPassword":"Secret123"}"""), ctx("old-name"));
|
||||
|
||||
assertEquals("new-name", r.getPhysicalId());
|
||||
assertEquals("old-name", p.updateCleanupPhysicalId(r));
|
||||
assertTrue(p.hasReplacementUpdate(r));
|
||||
|
||||
when(service.deleteCluster("old-name")).thenReturn(null);
|
||||
UpdateCleanupResult result = p.completeUpdate(r);
|
||||
verify(service).deleteCluster("old-name");
|
||||
assertEquals(new UpdateCleanupResult(true, true, "old-name", 0, null), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementCleanupToleratesAlreadyDeletedOldCluster() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
when(service.createCluster(anyString(), anyString(), anyString(), anyString(), any(), anyList()))
|
||||
.thenReturn(availableCluster("new-name"));
|
||||
doThrow(new AwsException("ClusterNotFound", "gone", 404)).when(service).deleteCluster("old-name");
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("W");
|
||||
p.provision(r, json("""
|
||||
{"ClusterIdentifier":"new-name","NodeType":"ra3.large","MasterUsername":"admin",
|
||||
"MasterUserPassword":"Secret123"}"""), ctx("old-name"));
|
||||
|
||||
assertDoesNotThrow(() -> p.completeUpdate(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearUpdateDropsCleanupRecord() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
when(service.createCluster(eq("new-name"), anyString(), anyString(), anyString(), any(), anyList()))
|
||||
.thenReturn(availableCluster("new-name"));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("W");
|
||||
p.provision(r, json("""
|
||||
{"ClusterIdentifier":"new-name","NodeType":"ra3.large","MasterUsername":"admin",
|
||||
"MasterUserPassword":"Secret123"}"""), ctx("old-name"));
|
||||
|
||||
assertTrue(p.hasReplacementUpdate(r));
|
||||
p.completeUpdate(r);
|
||||
p.clearUpdate(r);
|
||||
assertFalse(p.hasReplacementUpdate(r));
|
||||
assertNull(p.updateCleanupPhysicalId(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollbackUpdateRestoresPriorPhysicalIdAndDeletesReplacement() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
when(service.createCluster(eq("new-name"), anyString(), anyString(), anyString(), any(), anyList()))
|
||||
.thenReturn(availableCluster("new-name"));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("W");
|
||||
r.setPhysicalId("old-name");
|
||||
r.getAttributes().put("Id", "old-name");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"ClusterIdentifier":"new-name","NodeType":"ra3.large","MasterUsername":"admin",
|
||||
"MasterUserPassword":"Secret123"}"""), ctx("old-name"));
|
||||
|
||||
assertEquals("new-name", r.getPhysicalId());
|
||||
assertTrue(p.rollbackUpdate(r));
|
||||
assertEquals("old-name", r.getPhysicalId());
|
||||
verify(service).deleteCluster("new-name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingMasterUsernameTriggersReplacement() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
Cluster existing = availableCluster("my-cluster");
|
||||
existing.setMasterUsername("admin");
|
||||
when(service.describeClusters("my-cluster")).thenReturn(List.of(existing));
|
||||
when(service.createCluster(anyString(), anyString(), eq("newadmin"), anyString(), any(), anyList()))
|
||||
.thenAnswer(inv -> availableCluster(inv.getArgument(0)));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("W");
|
||||
p.provision(r, json("""
|
||||
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.large","MasterUsername":"newadmin",
|
||||
"MasterUserPassword":"Secret123"}"""), ctx("my-cluster"));
|
||||
|
||||
assertNotEquals("my-cluster", r.getPhysicalId());
|
||||
assertTrue(r.getPhysicalId().startsWith("my-cluster-"));
|
||||
assertEquals("my-cluster", p.updateCleanupPhysicalId(r));
|
||||
assertTrue(p.hasReplacementUpdate(r));
|
||||
|
||||
when(service.deleteCluster("my-cluster")).thenReturn(null);
|
||||
UpdateCleanupResult result = p.completeUpdate(r);
|
||||
verify(service).deleteCluster("my-cluster");
|
||||
assertEquals(new UpdateCleanupResult(true, true, "my-cluster", 0, null), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingClusterSubnetGroupTriggersReplacement() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
Cluster existing = availableCluster("my-cluster");
|
||||
existing.setMasterUsername("admin");
|
||||
existing.setClusterSubnetGroupName("subnet-group-1");
|
||||
when(service.describeClusters("my-cluster")).thenReturn(List.of(existing));
|
||||
when(service.createCluster(anyString(), anyString(), anyString(), anyString(), eq("subnet-group-2"), anyList()))
|
||||
.thenAnswer(inv -> availableCluster(inv.getArgument(0)));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("W");
|
||||
p.provision(r, json("""
|
||||
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.large","MasterUsername":"admin",
|
||||
"MasterUserPassword":"Secret123","ClusterSubnetGroupName":"subnet-group-2"}"""), ctx("my-cluster"));
|
||||
|
||||
assertNotEquals("my-cluster", r.getPhysicalId());
|
||||
assertEquals("my-cluster", p.updateCleanupPhysicalId(r));
|
||||
assertTrue(p.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changingDBNameTriggersReplacement() {
|
||||
RedshiftService service = mock(RedshiftService.class);
|
||||
Cluster existing = availableCluster("my-cluster");
|
||||
existing.setMasterUsername("admin");
|
||||
when(service.describeClusters("my-cluster")).thenReturn(List.of(existing));
|
||||
when(service.createCluster(anyString(), anyString(), anyString(), anyString(), any(), anyList()))
|
||||
.thenAnswer(inv -> availableCluster(inv.getArgument(0)));
|
||||
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
|
||||
|
||||
StackResource r = new StackResource();
|
||||
r.setResourceType("AWS::Redshift::Cluster");
|
||||
r.setLogicalId("W");
|
||||
r.setPhysicalId("my-cluster");
|
||||
r.getAttributes().put("Floci::DBName", "dev");
|
||||
|
||||
p.provision(r, json("""
|
||||
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.large","MasterUsername":"admin",
|
||||
"MasterUserPassword":"Secret123","DBName":"analytics"}"""), ctx("my-cluster"));
|
||||
|
||||
assertNotEquals("my-cluster", r.getPhysicalId());
|
||||
assertEquals("my-cluster", p.updateCleanupPhysicalId(r));
|
||||
assertTrue(p.hasReplacementUpdate(r));
|
||||
assertEquals("analytics", r.getAttributes().get("Floci::DBName"));
|
||||
}
|
||||
}
|
||||
@@ -44,5 +44,7 @@ AWS::RDS::DBInstance ReadReplicaDBInstanceIdentifiers read replicas are not emul
|
||||
AWS::RDS::DBInstance ResumeFullAutomationModeTime RDS Custom automation mode is not emulated
|
||||
AWS::RDS::DBInstance SecondaryAvailabilityZone multi-AZ secondary placement is not emulated
|
||||
AWS::RDS::DBInstance StatusInfos read-replica status detail is not emulated
|
||||
AWS::Redshift::Cluster DeferMaintenanceIdentifier Floci does not emulate deferred maintenance windows
|
||||
AWS::Redshift::Cluster MasterPasswordSecretArn only set when ManageMasterPassword is true, which Floci rejects
|
||||
AWS::SQS::QueuePolicy Id schema gives no description; the policy has no backing entity to take an id from
|
||||
AWS::SecretsManager::Secret Id Fn::GetAtt Id on a secret is its ARN, which the provisioner already sets as the physical id and as Arn; closable, deferred to a follow-up PR to keep this one a pure move
|
||||
|
@@ -123,6 +123,10 @@ AWS::RDS::DBParameterGroup RdsCfnProvisioner
|
||||
AWS::RDS::DBProxy RdsCfnProvisioner
|
||||
AWS::RDS::DBProxyTargetGroup RdsCfnProvisioner
|
||||
AWS::RDS::DBSubnetGroup RdsCfnProvisioner
|
||||
AWS::Redshift::Cluster RedshiftClusterCfnProvisioner
|
||||
AWS::Redshift::ClusterParameterGroup RedshiftClusterCfnProvisioner
|
||||
AWS::Redshift::ClusterSecurityGroup RedshiftClusterCfnProvisioner
|
||||
AWS::Redshift::ClusterSubnetGroup RedshiftClusterCfnProvisioner
|
||||
AWS::Route53::HostedZone Route53CfnProvisioner
|
||||
AWS::Route53::RecordSet LEGACY_SWITCH
|
||||
AWS::S3::Bucket S3CfnProvisioner
|
||||
|
||||
|
@@ -24,6 +24,7 @@ order:
|
||||
- AWS::ECS
|
||||
- AWS::EKS
|
||||
- AWS::RDS
|
||||
- AWS::Redshift
|
||||
- AWS::EC2
|
||||
- AWS::ElasticLoadBalancingV2
|
||||
- AWS::AutoScaling
|
||||
@@ -80,6 +81,8 @@ type_order:
|
||||
AWS::EKS: [Cluster, Nodegroup]
|
||||
AWS::RDS:
|
||||
[DBInstance, DBCluster, DBSubnetGroup, DBParameterGroup, DBClusterParameterGroup]
|
||||
AWS::Redshift:
|
||||
[Cluster, ClusterParameterGroup, ClusterSubnetGroup, ClusterSecurityGroup]
|
||||
AWS::EC2:
|
||||
[VPC, Subnet, SecurityGroup, SecurityGroupIngress, SecurityGroupEgress, InternetGateway,
|
||||
RouteTable, SubnetRouteTableAssociation, Route, NatGateway, EIP, Instance, LaunchTemplate,
|
||||
@@ -132,6 +135,7 @@ service_labels:
|
||||
AWS::Organizations: Organizations
|
||||
AWS::Pipes: Pipes
|
||||
AWS::RDS: RDS
|
||||
AWS::Redshift: Redshift
|
||||
AWS::Route53: Route 53
|
||||
AWS::S3: S3
|
||||
AWS::SNS: SNS
|
||||
@@ -153,6 +157,8 @@ notes:
|
||||
AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported
|
||||
AWS::RDS::DBInstance: starts a real container
|
||||
AWS::RDS::DBCluster: starts a real container
|
||||
AWS::Redshift::ClusterSecurityGroup: accepted; no EC2-Classic security group model
|
||||
AWS::Redshift::Cluster: single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported
|
||||
AWS::CDK::Metadata: accepted; no-op
|
||||
AWS::IoT::DomainConfiguration: '`ServerCertificates` resolves to a JSON string'
|
||||
AWS::IoT::Policy: 'deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached'
|
||||
|
||||
Reference in new issue
Block a user