diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index 2bce59988d..550c82aaaa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -140,6 +140,13 @@ public final class CfnRollback { */ public static final String LAUNCH_TEMPLATE_UPDATE_SNAPSHOT_ATTR = "__FlociLaunchTemplateUpdateSnapshot"; + /** + * Holds the settings a Lambda MicroVMs network connector had before an in-place update changed + * them, so a failed stack update can put them back. Written by {@code LambdaMicrovmsCfnProvisioner} + * before its update call and spent by its {@code rollbackUpdate}. + */ + public static final String NETWORK_CONNECTOR_UPDATE_SNAPSHOT_ATTR = "__FlociNetworkConnectorUpdateSnapshot"; + private CfnRollback() { } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisioner.java index 371d7eb668..9a9327fe24 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisioner.java @@ -1,14 +1,22 @@ 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.ObjectNode; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Set; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * CloudFormation provisioning for AWS Lambda MicroVMs: @@ -20,10 +28,22 @@ import java.util.Set; * group's {@code GroupId} — each array element resolves through the engine * individually. An image's {@code EgressNetworkConnectors} likewise arrive as * references to connector ARNs.

+ * + *

Both types are identified by their ARN, the registry schemas' primaryIdentifier, so {@code Ref} + * returns it. {@code Name} is the only createOnly property of either: an update that keeps it + * reconciles the existing entity in place, and one that changes it creates a replacement and the + * displaced entity is deleted once the update commits, through {@link ReplacementCleanup}. Removing + * an explicit {@code Name} is such a change: the resource is replaced under a generated name. An + * in-place connector update is snapshotted first, so a failed stack update puts it back.

*/ @ApplicationScoped public class LambdaMicrovmsCfnProvisioner implements CfnResourceProvisioner { + private static final String NETWORK_CONNECTOR = "AWS::Lambda::NetworkConnector"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + /** The shape {@link ProvisionContext#generatePhysicalName} gives a name: a stack-and-id prefix, a hex token. */ + private static final Pattern GENERATED_NAME = Pattern.compile("(?:(.*)-)?[0-9a-f]{12}"); + private final LambdaMicrovmsService microvmsService; @Inject @@ -49,16 +69,71 @@ public class LambdaMicrovmsCfnProvisioner implements CfnResourceProvisioner { @Override public void delete(String resourceType, String physicalId, String region) { switch (resourceType) { - case "AWS::Lambda::MicrovmImage" -> microvmsService.deleteImage(region, physicalId); - case "AWS::Lambda::NetworkConnector" -> microvmsService.deleteConnector(region, physicalId); + case "AWS::Lambda::MicrovmImage" -> CfnDeletes.safeDelete("MicroVM image", physicalId, + () -> microvmsService.deleteImage(region, physicalId), "ResourceNotFoundException"); + case "AWS::Lambda::NetworkConnector" -> CfnDeletes.safeDelete("network connector", physicalId, + () -> microvmsService.deleteConnector(region, physicalId), "ResourceNotFoundException"); default -> { } } } + @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) { + resource.getAttributes().remove(CfnRollback.NETWORK_CONNECTOR_UPDATE_SNAPSHOT_ATTR); + ReplacementCleanup.clear(resource); + } + + /** + * A replacement is undone through the cleanup record, and an in-place connector update from the + * snapshot taken before it; a connector with neither changed nothing. An image updated in place + * keeps no snapshot and is still reported as not rolled back. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + if (!NETWORK_CONNECTOR.equals(resource.getResourceType())) { + return false; + } + // Spent only once the restore succeeded, so a restore that throws can be retried. + String raw = resource.getAttributes().get(CfnRollback.NETWORK_CONNECTOR_UPDATE_SNAPSHOT_ATTR); + if (raw == null) { + return true; + } + JsonNode snapshot; + try { + snapshot = MAPPER.readTree(raw); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not read the network connector update snapshot for " + + resource.getLogicalId(), e); + } + microvmsService.updateConnector(snapshot.path("region").asText(), snapshot.path("arn").asText(), + textList(snapshot.path("subnetIds")), textList(snapshot.path("securityGroupIds")), + snapshot.path("operatorRole").asText(null), snapshot.path("networkProtocol").asText(null), + textList(snapshot.path("associatedComputeResourceTypes"))); + resource.getAttributes().remove(CfnRollback.NETWORK_CONNECTOR_UPDATE_SNAPSHOT_ATTR); + return true; + } + private void provisionImage(StackResource r, JsonNode props, ProvisionContext ctx) { - // Name is a createOnlyProperty and the physical id, so an unnamed image keeps the name it - // already had across updates instead of a fresh one each time provision runs. - String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "Name"), r.getLogicalId(), 64, false); + String priorName = r.getAttributes().get("Name"); + String name = nameOrPrior(ctx.resolveOptional(props, "Name"), priorName, r, ctx); String codeArtifactUri = null; if (props != null && props.has("CodeArtifact") && props.get("CodeArtifact").has("Uri")) { codeArtifactUri = ctx.engine().resolve(props.get("CodeArtifact").get("Uri")); @@ -70,12 +145,14 @@ public class LambdaMicrovmsCfnProvisioner implements CfnResourceProvisioner { // the service with an image that exists; the registry schema's update handler is // UpdateMicrovmImage, so reconcile through updateImage rather than mint a version through // createImage. A replacing update derives a different name and still creates. - LambdaMicrovmsService.MicrovmImage image = ctx.reusesPriorEntity(name) + boolean reused = ctx.isUpdate() && name.equals(priorName); + Map attributesBefore = new HashMap<>(r.getAttributes()); + LambdaMicrovmsService.MicrovmImage image = reused ? microvmsService.updateImage(ctx.region(), name, baseImageArn, buildRoleArn, codeArtifactUri, description) : microvmsService.createImage(ctx.region(), ctx.accountId(), name, baseImageArn, buildRoleArn, codeArtifactUri, description); - r.setPhysicalId(image.name); + settle(r, ctx, attributesBefore, reused, image.imageArn); r.getAttributes().put("ImageArn", image.imageArn); r.getAttributes().put("Arn", image.imageArn); r.getAttributes().put("Name", image.name); @@ -83,10 +160,10 @@ public class LambdaMicrovmsCfnProvisioner implements CfnResourceProvisioner { } private void provisionConnector(StackResource r, JsonNode props, ProvisionContext ctx) { - String name = ctx.resolveOptional(props, "Name"); - if (name == null || name.isBlank()) { - name = ctx.generatePhysicalName(r.getLogicalId(), 64, false); - } + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(CfnRollback.NETWORK_CONNECTOR_UPDATE_SNAPSHOT_ATTR); + String priorName = r.getAttributes().get("Name"); + String name = nameOrPrior(ctx.resolveOptional(props, "Name"), priorName, r, ctx); JsonNode vpc = props == null ? null : props.path("Configuration").path("VpcEgressConfiguration"); @@ -94,22 +171,96 @@ public class LambdaMicrovmsCfnProvisioner implements CfnResourceProvisioner { if (vpc != null && vpc.has("NetworkProtocol")) { networkProtocol = ctx.engine().resolve(vpc.get("NetworkProtocol")); } - LambdaMicrovmsService.NetworkConnector connector = microvmsService.createConnector( - ctx.region(), - ctx.accountId(), - name, - resolveList(vpc == null ? null : vpc.get("SubnetIds"), ctx), - resolveList(vpc == null ? null : vpc.get("SecurityGroupIds"), ctx), - ctx.resolveOptional(props, "OperatorRole"), - java.util.UUID.randomUUID().toString(), - resolveList(vpc == null ? null : vpc.get("AssociatedComputeResourceTypes"), ctx), - networkProtocol); - r.setPhysicalId(connector.id); + List subnetIds = resolveList(vpc == null ? null : vpc.get("SubnetIds"), ctx); + List securityGroupIds = resolveList(vpc == null ? null : vpc.get("SecurityGroupIds"), ctx); + String operatorRole = ctx.resolveOptional(props, "OperatorRole"); + List computeResourceTypes = + resolveList(vpc == null ? null : vpc.get("AssociatedComputeResourceTypes"), ctx); + // The schema's update handler is UpdateNetworkConnector, so an update that keeps the name + // reconciles the connector it already has instead of creating a second one. + boolean reused = ctx.isUpdate() && name.equals(priorName); + Map attributesBefore = new HashMap<>(r.getAttributes()); + LambdaMicrovmsService.NetworkConnector connector; + if (reused) { + snapshotConnector(r, ctx); + connector = microvmsService.updateConnector(ctx.region(), ctx.priorPhysicalId(), subnetIds, + securityGroupIds, operatorRole, networkProtocol, computeResourceTypes); + } else { + connector = microvmsService.createConnector(ctx.region(), ctx.accountId(), name, subnetIds, + securityGroupIds, operatorRole, UUID.randomUUID().toString(), computeResourceTypes, + networkProtocol); + } + settle(r, ctx, attributesBefore, reused, connector.arn); r.getAttributes().put("Arn", connector.arn); r.getAttributes().put("Id", connector.id); r.getAttributes().put("Name", connector.name); } + /** Records the connector's settings before an in-place update, for {@link #rollbackUpdate}. */ + private void snapshotConnector(StackResource r, ProvisionContext ctx) { + LambdaMicrovmsService.NetworkConnector current = + microvmsService.getConnector(ctx.region(), ctx.priorPhysicalId()); + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("region", ctx.region()); + snapshot.put("arn", current.arn); + current.subnetIds.forEach(snapshot.putArray("subnetIds")::add); + current.securityGroupIds.forEach(snapshot.putArray("securityGroupIds")::add); + snapshot.put("operatorRole", current.operatorRole); + snapshot.put("networkProtocol", current.networkProtocol); + current.associatedComputeResourceTypes.forEach(snapshot.putArray("associatedComputeResourceTypes")::add); + r.getAttributes().put(CfnRollback.NETWORK_CONNECTOR_UPDATE_SNAPSHOT_ATTR, snapshot.toString()); + } + + private static List textList(JsonNode node) { + List out = new ArrayList<>(); + node.forEach(item -> out.add(item.asText())); + return out; + } + + /** + * The template's name when it gives one, otherwise the generated name this resource already had, + * and only failing both a fresh generated one. The physical id is the ARN, so the prior name comes + * from the {@code Name} attribute recorded at create time. A prior name that was declared, not + * generated, is not kept when the template drops it: {@code Name} is createOnly, so removing it + * replaces the resource, as CloudFormation does. + */ + private static String nameOrPrior(String declared, String prior, StackResource r, ProvisionContext ctx) { + if (declared != null && !declared.isBlank()) { + return declared; + } + if (ctx.isUpdate() && prior != null && wasGenerated(prior, ctx.stackName(), r.getLogicalId())) { + return prior; + } + return ctx.generatePhysicalName(r.getLogicalId(), 64, false); + } + + /** Whether {@code name} has the shape this resource's generated names have, truncation included. */ + static boolean wasGenerated(String name, String stackName, String logicalId) { + Matcher matcher = GENERATED_NAME.matcher(name); + if (!matcher.matches()) { + return false; + } + String prefix = matcher.group(1); + return prefix == null || (stackName + "-" + logicalId).startsWith(prefix); + } + + /** + * Sets the ARN as the physical id and records any replacement. A reuse records before the id + * changes: a stack created when the physical id was still the image name or connector id names + * the entity it reuses by that, and recording after the switch would mark it displaced and + * delete it once the update commits. + */ + private static void settle(StackResource r, ProvisionContext ctx, Map attributesBefore, + boolean reused, String arn) { + if (reused) { + ReplacementCleanup.record(r, ctx, attributesBefore); + r.setPhysicalId(arn); + return; + } + r.setPhysicalId(arn); + ReplacementCleanup.record(r, ctx, attributesBefore); + } + /** Resolves each array element through the engine so intrinsic refs work per entry. */ private List resolveList(JsonNode node, ProvisionContext ctx) { if (node == null || !node.isArray()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java index 5cd176d989..e3ff1e5b07 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsService.java @@ -486,8 +486,15 @@ public class LambdaMicrovmsService { .toList(); } + /** + * UpdateNetworkConnector: every member is optional and a null one leaves the connector's value + * as it is. The model lets an update change the operator role, the network protocol and the + * associated compute resource types as well as the subnets and security groups. + */ public NetworkConnector updateConnector(String region, String id, - List subnetIds, List securityGroupIds) { + List subnetIds, List securityGroupIds, + String operatorRole, String networkProtocol, + List computeResourceTypes) { NetworkConnector connector = getConnector(region, id); if (subnetIds != null && !subnetIds.isEmpty()) { if (subnetIds.size() > MAX_CONNECTOR_SUBNETS) { @@ -502,6 +509,18 @@ public class LambdaMicrovmsService { if (securityGroupIds != null) { connector.securityGroupIds = List.copyOf(securityGroupIds); } + if (operatorRole != null && !operatorRole.isBlank()) { + connector.operatorRole = operatorRole; + connector.lastModified = Instant.now(); + } + if (networkProtocol != null && !networkProtocol.isBlank()) { + connector.networkProtocol = networkProtocol; + connector.lastModified = Instant.now(); + } + if (computeResourceTypes != null && !computeResourceTypes.isEmpty()) { + connector.associatedComputeResourceTypes = List.copyOf(computeResourceTypes); + connector.lastModified = Instant.now(); + } persist(connectors, region, connector.id, connector); return connector; } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaNetworkConnectorsController.java b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaNetworkConnectorsController.java index 626e86e9f3..1371b641e2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaNetworkConnectorsController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaNetworkConnectorsController.java @@ -99,7 +99,9 @@ public class LambdaNetworkConnectorsController { JsonNode request = parse(body); JsonNode vpc = request.path("Configuration").path("VpcEgressConfiguration"); NetworkConnector connector = service.updateConnector( - region, identifier, stringList(vpc.path("SubnetIds")), stringList(vpc.path("SecurityGroupIds"))); + region, identifier, stringList(vpc.path("SubnetIds")), stringList(vpc.path("SecurityGroupIds")), + text(request, "OperatorRole"), text(vpc, "NetworkProtocol"), + stringList(vpc.path("AssociatedComputeResourceTypes"))); return Response.status(202).entity(connectorNode(connector, ConnectorShape.UPDATE)).build(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaMicrovmsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaMicrovmsIntegrationTest.java index 6131c351ca..e0037aa9e3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaMicrovmsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaMicrovmsIntegrationTest.java @@ -1,12 +1,17 @@ package io.github.hectorvent.floci.services.cloudformation; +import io.github.hectorvent.floci.core.common.XmlParser; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; +import java.util.Map; + import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * End-to-end check that CloudFormation provisions {@code AWS::Lambda::MicrovmImage} and @@ -118,4 +123,110 @@ class CloudFormationLambdaMicrovmsIntegrationTest { .then() .statusCode(404)); } + + @Test + void refReturnsTheArnsAndAnUpdateKeepsTheConnector() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-microvm-ref-" + suffix; + String connectorName = "cfn-microvm-ref-connector-" + suffix; + + cloudFormation(stackName, "CreateStack", refTemplate(connectorName, "subnet-0cfn000000000001")); + Map created = outputs(describeStacks(stackName, "CREATE_COMPLETE")); + String connectorArn = created.get("ConnectorArn"); + assertTrue(connectorArn.contains(":network-connector:nc-"), connectorArn); + assertEquals(connectorArn, created.get("ConnectorRef"), "Ref is the connector ARN, its primaryIdentifier"); + assertEquals(created.get("ImageArn"), created.get("ImageRef"), "Ref is the image ARN, its primaryIdentifier"); + + cloudFormation(stackName, "UpdateStack", refTemplate(connectorName, "subnet-0cfn000000000002")); + Map updated = outputs(describeStacks(stackName, "UPDATE_COMPLETE")); + assertEquals(connectorArn, updated.get("ConnectorRef"), "a subnet change updates the connector in place"); + given() + .when() + .get("/2026-04-04/network-connectors/" + connectorArn) + .then() + .statusCode(200) + .body("Name", equalTo(connectorName)) + .body("Configuration.VpcEgressConfiguration.SubnetIds[0]", equalTo("subnet-0cfn000000000002")); + + cloudFormation(stackName, "DeleteStack", null); + await().untilAsserted(() -> + given() + .when() + .get("/2026-04-04/network-connectors/" + connectorArn) + .then() + .statusCode(404)); + } + + private static String refTemplate(String connectorName, String subnetId) { + return """ + { + "Resources": { + "Connector": { + "Type": "AWS::Lambda::NetworkConnector", + "Properties": { + "Name": "%s", + "OperatorRole": "arn:aws:iam::000000000000:role/cfn-microvm-connector-operator", + "Configuration": { + "VpcEgressConfiguration": { + "AssociatedComputeResourceTypes": ["MicroVm"], + "SubnetIds": ["%s"], + "SecurityGroupIds": ["sg-0cfn000000000001"], + "NetworkProtocol": "IPv4" + } + } + } + }, + "Image": { + "Type": "AWS::Lambda::MicrovmImage", + "Properties": { + "BaseImageArn": "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1", + "BuildRoleArn": "arn:aws:iam::000000000000:role/cfn-microvm-build", + "CodeArtifact": { "Uri": "s3://cfn-bucket/context.zip" }, + "Description": "cfn ref image" + } + } + }, + "Outputs": { + "ImageRef": {"Value": {"Ref": "Image"}}, + "ImageArn": {"Value": {"Fn::GetAtt": ["Image", "ImageArn"]}}, + "ConnectorRef": {"Value": {"Ref": "Connector"}}, + "ConnectorArn": {"Value": {"Fn::GetAtt": ["Connector", "Arn"]}} + } + } + """.formatted(connectorName, subnetId); + } + + private static void cloudFormation(String stackName, String action, String templateBody) { + if (templateBody == null) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", action) + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200); + return; + } + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", action) + .formParam("StackName", stackName) + .formParam("TemplateBody", templateBody) + .when().post("/").then().statusCode(200); + } + + private static String describeStacks(String stackName, String expectedStatus) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200) + .body(containsString("" + expectedStatus + "")) + .extract().asString(); + } + + private static Map outputs(String describeStacksXml) { + return XmlParser.extractPairs(describeStacksXml, "Outputs", "OutputKey", "OutputValue"); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnStableNameUpdatePathTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnStableNameUpdatePathTest.java index 1ee4520ff6..b7becd13a4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnStableNameUpdatePathTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnStableNameUpdatePathTest.java @@ -273,12 +273,17 @@ class CfnStableNameUpdatePathTest { StackResource created = resource("AWS::Lambda::MicrovmImage", "Image"); provisioner.provision(created, props, ctx(null)); - String generatedName = created.getPhysicalId(); + String generatedName = created.getAttributes().get("Name"); + // The physical id is the image ARN, so the update carries the prior attributes the way + // CfnResourceDispatcher does, and the name comes back from the recorded Name attribute. StackResource updated = resource("AWS::Lambda::MicrovmImage", "Image"); - provisioner.provision(updated, props, ctx(generatedName)); + updated.setPhysicalId(created.getPhysicalId()); + updated.setAttributes(new HashMap<>(created.getAttributes())); + provisioner.provision(updated, props, ctx(created.getPhysicalId())); - assertEquals(generatedName, updated.getPhysicalId(), "the generated name must stay stable"); + assertEquals(created.getPhysicalId(), updated.getPhysicalId(), "the image ARN must stay stable"); + assertEquals(generatedName, updated.getAttributes().get("Name"), "the generated name must stay stable"); // createImage on an existing image silently mints a new version rather than rejecting, so // here the assertion is that the update went to the schema's update handler instead. verify(microvms, times(1)).createImage(anyString(), anyString(), eq(generatedName), any(), any(), any(), any()); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisionerTest.java index 1927251b70..dea3ad3f54 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaMicrovmsCfnProvisionerTest.java @@ -3,16 +3,23 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; import com.fasterxml.jackson.databind.JsonNode; 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.lambdamicrovms.LambdaMicrovmsService; import org.junit.jupiter.api.Test; +import java.util.HashMap; +import java.util.List; + import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +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.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -20,15 +27,19 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** - * {@code AWS::Lambda::MicrovmImage} in isolation. Name is a createOnlyProperty in the registry - * schema and the physical id, so an unnamed image must keep its generated name across updates and - * the update must go through UpdateMicrovmImage, the schema's update handler, rather than mint a - * fresh version through create. + * {@code AWS::Lambda::MicrovmImage} and {@code AWS::Lambda::NetworkConnector} in isolation. Both are + * identified by their ARN (the registry schemas' primaryIdentifier), and {@code Name} is the only + * createOnly property of either: an update that keeps it goes through the schema's update handler, + * one that changes it creates a replacement and deletes the displaced entity after the commit. */ class LambdaMicrovmsCfnProvisionerTest { + private static final String REGION = "us-east-1"; + private static final String IMAGE_TYPE = "AWS::Lambda::MicrovmImage"; + private static final String CONNECTOR_TYPE = "AWS::Lambda::NetworkConnector"; private static final String BASE_IMAGE = "arn:aws:lambda:us-east-1::base-image:nodejs"; private static final String BUILD_ROLE = "arn:aws:iam::000000000000:role/build"; + private static final String OPERATOR_ROLE = "arn:aws:iam::000000000000:role/operator"; private static final String CODE_URI = "s3://bucket/code.zip"; private final LambdaMicrovmsService service = mock(LambdaMicrovmsService.class); @@ -41,17 +52,26 @@ class LambdaMicrovmsCfnProvisionerTest { JsonNode node = inv.getArgument(0); return node == null ? null : node.asText(); }); - return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId); + return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId); } - private StackResource resource() { + private static StackResource resource(String type) { StackResource r = new StackResource(); - r.setLogicalId("MyImage"); - r.setResourceType("AWS::Lambda::MicrovmImage"); + r.setLogicalId("Res"); + r.setResourceType(type); + r.setAttributes(new HashMap<>()); return r; } - private ObjectNode props(String name) { + /** What CfnResourceDispatcher hands provision on UpdateStack: the prior physical id and attributes. */ + private static StackResource updateOf(StackResource prior) { + StackResource r = resource(prior.getResourceType()); + r.setPhysicalId(prior.getPhysicalId()); + r.setAttributes(new HashMap<>(prior.getAttributes())); + return r; + } + + private ObjectNode imageProps(String name) { ObjectNode props = mapper.createObjectNode() .put("BaseImageArn", BASE_IMAGE) .put("BuildRoleArn", BUILD_ROLE) @@ -63,59 +83,257 @@ class LambdaMicrovmsCfnProvisionerTest { return props; } + private ObjectNode connectorProps(String name, String subnet) { + ObjectNode props = mapper.createObjectNode().put("OperatorRole", OPERATOR_ROLE); + if (name != null) { + props.put("Name", name); + } + ObjectNode vpc = props.putObject("Configuration").putObject("VpcEgressConfiguration"); + vpc.put("NetworkProtocol", "IPv4"); + vpc.putArray("SubnetIds").add(subnet); + vpc.putArray("SecurityGroupIds").add("sg-1"); + vpc.putArray("AssociatedComputeResourceTypes").add("MICROVM"); + return props; + } + + private static String imageArn(String name) { + return "arn:aws:lambda:us-east-1:000000000000:microvm-image:" + name; + } + private static LambdaMicrovmsService.MicrovmImage image(String name, String version) { LambdaMicrovmsService.MicrovmImage image = new LambdaMicrovmsService.MicrovmImage(); image.name = name; - image.imageArn = "arn:aws:lambda:us-east-1:000000000000:microvm-image:" + name; + image.imageArn = imageArn(name); image.latestActiveImageVersion = version; return image; } + private static LambdaMicrovmsService.NetworkConnector connector(String id, String name) { + LambdaMicrovmsService.NetworkConnector connector = new LambdaMicrovmsService.NetworkConnector(); + connector.id = id; + connector.name = name; + connector.arn = "arn:aws:lambda:us-east-1:000000000000:network-connector:" + id; + connector.subnetIds = List.of("subnet-1"); + connector.securityGroupIds = List.of("sg-1"); + connector.operatorRole = OPERATOR_ROLE; + connector.networkProtocol = "IPv4"; + connector.associatedComputeResourceTypes = List.of("MICROVM"); + return connector; + } + + private void stubImageCreateAndUpdate() { + when(service.createImage(anyString(), anyString(), anyString(), any(), any(), any(), any())) + .thenAnswer(inv -> image(inv.getArgument(2), "1.0")); + when(service.updateImage(anyString(), anyString(), any(), any(), any(), any())) + .thenAnswer(inv -> image(inv.getArgument(1), "2.0")); + } + @Test - void createSetsThePhysicalIdAndTheGetAttAttributes() { - when(service.createImage(eq("us-east-1"), eq("000000000000"), eq("img"), eq(BASE_IMAGE), + void imageRefIsTheImageArnAndTheGetAttAttributesAreSet() { + when(service.createImage(eq(REGION), eq("000000000000"), eq("img"), eq(BASE_IMAGE), eq(BUILD_ROLE), eq(CODE_URI), eq("an image"))).thenReturn(image("img", "1.0")); - StackResource r = resource(); + StackResource r = resource(IMAGE_TYPE); - provisioner.provision(r, props("img"), ctx(null)); + provisioner.provision(r, imageProps("img"), ctx(null)); - assertEquals("img", r.getPhysicalId()); - assertEquals("arn:aws:lambda:us-east-1:000000000000:microvm-image:img", r.getAttributes().get("ImageArn")); - assertEquals("arn:aws:lambda:us-east-1:000000000000:microvm-image:img", r.getAttributes().get("Arn")); + assertEquals(imageArn("img"), r.getPhysicalId()); + assertEquals(imageArn("img"), r.getAttributes().get("ImageArn")); + assertEquals(imageArn("img"), r.getAttributes().get("Arn")); assertEquals("img", r.getAttributes().get("Name")); assertEquals("1.0", r.getAttributes().get("LatestActiveImageVersion")); } @Test void anUnnamedImageKeepsItsNameAndIsUpdatedRatherThanRecreated() { - when(service.createImage(anyString(), anyString(), anyString(), any(), any(), any(), any())) - .thenAnswer(inv -> image(inv.getArgument(2), "1.0")); - when(service.updateImage(anyString(), anyString(), any(), any(), any(), any())) - .thenAnswer(inv -> image(inv.getArgument(1), "2.0")); - StackResource created = resource(); - provisioner.provision(created, props(null), ctx(null)); - String generatedName = created.getPhysicalId(); - assertTrue(generatedName.startsWith("my-stack-MyImage-"), generatedName); + stubImageCreateAndUpdate(); + StackResource created = resource(IMAGE_TYPE); + provisioner.provision(created, imageProps(null), ctx(null)); + String generatedName = created.getAttributes().get("Name"); + assertTrue(generatedName.startsWith("my-stack-Res-"), generatedName); - StackResource updated = resource(); - provisioner.provision(updated, props(null), ctx(generatedName)); + StackResource updated = updateOf(created); + provisioner.provision(updated, imageProps(null), ctx(created.getPhysicalId())); - assertEquals(generatedName, updated.getPhysicalId()); + assertEquals(imageArn(generatedName), updated.getPhysicalId()); assertEquals("2.0", updated.getAttributes().get("LatestActiveImageVersion")); + assertFalse(provisioner.hasReplacementUpdate(updated)); verify(service, times(1)).createImage(anyString(), anyString(), anyString(), any(), any(), any(), any()); - verify(service).updateImage("us-east-1", generatedName, BASE_IMAGE, BUILD_ROLE, CODE_URI, "an image"); + verify(service).updateImage(REGION, generatedName, BASE_IMAGE, BUILD_ROLE, CODE_URI, "an image"); } @Test - void aRenamedImageIsAReplacingUpdateAndStillCreates() { - when(service.createImage(anyString(), anyString(), anyString(), any(), any(), any(), any())) - .thenAnswer(inv -> image(inv.getArgument(2), "1.0")); - StackResource r = resource(); + void aRenamedImageIsReplacedAndTheDisplacedOneDeletedAfterTheCommit() { + stubImageCreateAndUpdate(); + StackResource created = resource(IMAGE_TYPE); + provisioner.provision(created, imageProps("old-name"), ctx(null)); - provisioner.provision(r, props("renamed"), ctx("old-name")); + StackResource updated = updateOf(created); + provisioner.provision(updated, imageProps("renamed"), ctx(created.getPhysicalId())); - assertEquals("renamed", r.getPhysicalId()); - verify(service).createImage(eq("us-east-1"), eq("000000000000"), eq("renamed"), any(), any(), any(), any()); + assertEquals(imageArn("renamed"), updated.getPhysicalId()); verify(service, never()).updateImage(anyString(), anyString(), any(), any(), any(), any()); + assertTrue(provisioner.hasReplacementUpdate(updated)); + assertEquals(imageArn("old-name"), provisioner.updateCleanupPhysicalId(updated)); + + assertTrue(provisioner.completeUpdate(updated).complete()); + verify(service).deleteImage(REGION, imageArn("old-name")); + } + + @Test + void anImageFromAStackThatStoredItsNameIsReusedAndOnlyItsIdMovesToTheArn() { + stubImageCreateAndUpdate(); + StackResource legacy = resource(IMAGE_TYPE); + legacy.setPhysicalId("img"); + legacy.getAttributes().put("Name", "img"); + legacy.getAttributes().put("ImageArn", imageArn("img")); + + StackResource updated = updateOf(legacy); + provisioner.provision(updated, imageProps("img"), ctx("img")); + + assertEquals(imageArn("img"), updated.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(updated), "the reused image must not be marked displaced"); + verify(service).updateImage(REGION, "img", BASE_IMAGE, BUILD_ROLE, CODE_URI, "an image"); + verify(service, never()).createImage(anyString(), anyString(), anyString(), any(), any(), any(), any()); + } + + @Test + void connectorRefIsTheConnectorArnAndTheGetAttAttributesAreSet() { + when(service.createConnector(eq(REGION), eq("000000000000"), eq("nc"), eq(List.of("subnet-1")), + eq(List.of("sg-1")), eq(OPERATOR_ROLE), anyString(), eq(List.of("MICROVM")), eq("IPv4"))) + .thenReturn(connector("nc-1", "nc")); + StackResource r = resource(CONNECTOR_TYPE); + + provisioner.provision(r, connectorProps("nc", "subnet-1"), ctx(null)); + + String arn = connector("nc-1", "nc").arn; + assertEquals(arn, r.getPhysicalId()); + assertEquals(arn, r.getAttributes().get("Arn")); + assertEquals("nc-1", r.getAttributes().get("Id")); + assertEquals("nc", r.getAttributes().get("Name")); + } + + @Test + void aConnectorUpdateThatKeepsTheNameUpdatesTheExistingConnector() { + when(service.createConnector(anyString(), anyString(), anyString(), any(), any(), any(), anyString(), any(), + any())).thenAnswer(inv -> connector("nc-1", inv.getArgument(2))); + StackResource created = resource(CONNECTOR_TYPE); + provisioner.provision(created, connectorProps(null, "subnet-1"), ctx(null)); + String name = created.getAttributes().get("Name"); + when(service.getConnector(REGION, created.getPhysicalId())).thenReturn(connector("nc-1", name)); + when(service.updateConnector(REGION, created.getPhysicalId(), List.of("subnet-2"), List.of("sg-1"), + OPERATOR_ROLE, "IPv4", List.of("MICROVM"))).thenReturn(connector("nc-1", name)); + + StackResource updated = updateOf(created); + provisioner.provision(updated, connectorProps(null, "subnet-2"), ctx(created.getPhysicalId())); + + assertEquals(created.getPhysicalId(), updated.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(updated)); + verify(service, times(1)).createConnector(anyString(), anyString(), anyString(), any(), any(), any(), + anyString(), any(), any()); + verify(service).updateConnector(REGION, created.getPhysicalId(), List.of("subnet-2"), List.of("sg-1"), + OPERATOR_ROLE, "IPv4", List.of("MICROVM")); + } + + @Test + void anInPlaceConnectorUpdateAppliesEverySettingAndRollsBackFromItsSnapshot() { + String arn = connector("nc-1", "nc").arn; + StackResource prior = resource(CONNECTOR_TYPE); + prior.setPhysicalId(arn); + prior.getAttributes().put("Name", "nc"); + when(service.getConnector(REGION, arn)).thenReturn(connector("nc-1", "nc")); + when(service.updateConnector(anyString(), anyString(), any(), any(), any(), any(), any())) + .thenReturn(connector("nc-1", "nc")); + ObjectNode props = connectorProps("nc", "subnet-2"); + props.put("OperatorRole", "arn:aws:iam::000000000000:role/operator-v2"); + ObjectNode vpc = (ObjectNode) props.path("Configuration").path("VpcEgressConfiguration"); + vpc.put("NetworkProtocol", "DUAL_STACK"); + + StackResource updated = updateOf(prior); + provisioner.provision(updated, props, ctx(arn)); + + verify(service).updateConnector(REGION, arn, List.of("subnet-2"), List.of("sg-1"), + "arn:aws:iam::000000000000:role/operator-v2", "DUAL_STACK", List.of("MICROVM")); + assertTrue(provisioner.rollbackUpdate(updated)); + verify(service).updateConnector(REGION, arn, List.of("subnet-1"), List.of("sg-1"), OPERATOR_ROLE, "IPv4", + List.of("MICROVM")); + assertFalse(updated.getAttributes().containsKey(CfnRollback.NETWORK_CONNECTOR_UPDATE_SNAPSHOT_ATTR), + "the snapshot is spent"); + } + + @Test + void droppingAnExplicitConnectorNameReplacesTheConnector() { + when(service.createConnector(anyString(), anyString(), anyString(), any(), any(), any(), anyString(), any(), + any())).thenAnswer(inv -> connector("nc-2", inv.getArgument(2))); + String arn = connector("nc-1", "explicit-name").arn; + StackResource prior = resource(CONNECTOR_TYPE); + prior.setPhysicalId(arn); + prior.getAttributes().put("Name", "explicit-name"); + + StackResource updated = updateOf(prior); + provisioner.provision(updated, connectorProps(null, "subnet-1"), ctx(arn)); + + String name = updated.getAttributes().get("Name"); + assertTrue(name.startsWith("my-stack-Res-"), name); + assertEquals(arn, provisioner.updateCleanupPhysicalId(updated)); + verify(service, never()).updateConnector(anyString(), anyString(), any(), any(), any(), any(), any()); + } + + @Test + void onlyANameWithTheGeneratedShapeCountsAsGenerated() { + assertTrue(LambdaMicrovmsCfnProvisioner.wasGenerated("my-stack-Res-0123456789ab", "my-stack", "Res")); + assertTrue(LambdaMicrovmsCfnProvisioner.wasGenerated("my-sta-0123456789ab", "my-stack", "Res"), + "a truncated prefix still counts"); + assertFalse(LambdaMicrovmsCfnProvisioner.wasGenerated("explicit-name", "my-stack", "Res")); + assertFalse(LambdaMicrovmsCfnProvisioner.wasGenerated("other-stack-Res-0123456789ab", "my-stack", "Res")); + } + + @Test + void aRenamedConnectorIsReplacedAndTheDisplacedOneDeletedAfterTheCommit() { + when(service.createConnector(anyString(), anyString(), eq("first"), any(), any(), any(), anyString(), any(), + any())).thenReturn(connector("nc-1", "first")); + when(service.createConnector(anyString(), anyString(), eq("second"), any(), any(), any(), anyString(), any(), + any())).thenReturn(connector("nc-2", "second")); + StackResource created = resource(CONNECTOR_TYPE); + provisioner.provision(created, connectorProps("first", "subnet-1"), ctx(null)); + + StackResource updated = updateOf(created); + provisioner.provision(updated, connectorProps("second", "subnet-1"), ctx(created.getPhysicalId())); + + assertEquals(connector("nc-2", "second").arn, updated.getPhysicalId()); + assertEquals(created.getPhysicalId(), provisioner.updateCleanupPhysicalId(updated)); + assertTrue(provisioner.completeUpdate(updated).complete()); + verify(service).deleteConnector(REGION, created.getPhysicalId()); + verify(service, never()).updateConnector(anyString(), anyString(), any(), any(), any(), any(), any()); + } + + @Test + void aConnectorFromAStackThatStoredItsIdIsReusedAndOnlyItsIdMovesToTheArn() { + when(service.getConnector(REGION, "nc-1")).thenReturn(connector("nc-1", "nc")); + when(service.updateConnector(REGION, "nc-1", List.of("subnet-1"), List.of("sg-1"), OPERATOR_ROLE, "IPv4", + List.of("MICROVM"))).thenReturn(connector("nc-1", "nc")); + StackResource legacy = resource(CONNECTOR_TYPE); + legacy.setPhysicalId("nc-1"); + legacy.getAttributes().put("Name", "nc"); + + StackResource updated = updateOf(legacy); + provisioner.provision(updated, connectorProps("nc", "subnet-1"), ctx("nc-1")); + + assertEquals(connector("nc-1", "nc").arn, updated.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(updated), "the reused connector must not be marked displaced"); + verify(service, never()).createConnector(anyString(), anyString(), anyString(), any(), any(), any(), + anyString(), any(), any()); + } + + @Test + void deleteToleratesAnAlreadyDeletedEntityButPropagatesARealFailure() { + String arn = imageArn("img"); + doThrow(new AwsException("ResourceNotFoundException", "gone", 404)) + .when(service).deleteConnector(REGION, "nc-gone"); + doThrow(new AwsException("ValidationException", "Cannot delete microvm image with running microvms.", 400)) + .when(service).deleteImage(REGION, arn); + + provisioner.delete(CONNECTOR_TYPE, "nc-gone", REGION); + AwsException e = assertThrows(AwsException.class, () -> provisioner.delete(IMAGE_TYPE, arn, REGION)); + assertEquals("ValidationException", e.getErrorCode()); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsIntegrationTest.java index 94d0d2988b..da28ff55b5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambdamicrovms/LambdaMicrovmsIntegrationTest.java @@ -248,6 +248,28 @@ class LambdaMicrovmsIntegrationTest { .body("State", equalTo("ACTIVE")) .body("Name", equalTo("microvm-it-connector")); + // UpdateNetworkConnector changes the operator role and protocol as well as the subnets. + given() + .contentType("application/json") + .body(""" + { + "OperatorRole": "arn:aws:iam::000000000000:role/microvm-connector-operator-v2", + "Configuration": { "VpcEgressConfiguration": { "NetworkProtocol": "DUAL_STACK" } } + } + """) + .when() + .put(CORE + "/network-connectors/" + connectorId) + .then() + .statusCode(202); + given() + .when() + .get(CORE + "/network-connectors/" + connectorId) + .then() + .statusCode(200) + .body("OperatorRole", equalTo("arn:aws:iam::000000000000:role/microvm-connector-operator-v2")) + .body("Configuration.VpcEgressConfiguration.NetworkProtocol", equalTo("DUAL_STACK")) + .body("Configuration.VpcEgressConfiguration.SubnetIds[0]", equalTo("subnet-0000000000000it01")); + given() .when() .delete(CORE + "/network-connectors/" + connectorId)