fix(ec2): preserve security group deletion scope and dependencies (#7920)

* fix(ec2): preserve security group deletion scope and dependencies

Coordinate group publication, attachment and deletion, preserve instance/interface group state, and reject invalid DryRun values before deletion.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(ec2): tolerate absent persisted group dependency fields

Keep unknown-state instance attachments blocking deletion while treating absent dependency collections as empty. Cover all nullable scan fields and missing identifiers without changing normal dependency semantics.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>

* fix(ec2): roll back failed security group creation

Retain the default rule identity before publication and compensate both group and rule writes when either store fails. Preserve the original exception and record cleanup failures without skipping the remaining cleanup.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>

* fix(ec2): serialize group rule references with deletion

Acquire the regional topology monitor before the source group monitor while resolving and publishing ingress and egress rules. Keep runtime reconciliation outside the mutation locks and preserve existing unknown-reference compatibility.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>

* fix(ec2): retain groups used by Instance Connect endpoints

Reject deletion before mutation when an Instance Connect endpoint uses the group. Return CannotDelete for default groups and reuse shared SDK clients in the existing fixtures.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* refactor(ec2): share resource locks and deletion race helpers

Reuse the reference-counted lock lifecycle for volume operations and instance group assignments. Keep scoped keys and lock ordering unchanged. Reuse deletion tasks and blocked-or-done observations without weakening race assertions.

Signed-off-by: Andre Kurait <akurait@amazon.com>

---------

Signed-off-by: Andre Kurait <akurait@amazon.com>
Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-12 20:31:14 -04:00
1 parent 4b3b5cc211
commit 1820d6470d
12 files changed
+2205 -286

No files matched your search

@@ -3649,10 +3649,15 @@ public class Ec2QueryHandler {
}
private Response handleDeleteSecurityGroup(MultivaluedMap<String, String> p, String region) {
String groupId = p.getFirst("GroupId");
if (groupId == null) groupId = p.getFirst("GroupName");
service.deleteSecurityGroup(region, groupId);
return booleanResponse("DeleteSecurityGroup");
String dryRun = p.getFirst("DryRun");
if (dryRun != null && dryRun.isBlank()) {
throw new AwsException("InvalidParameterValue", "DryRun is not a valid boolean.", 400);
}
String groupId = service.deleteSecurityGroup(region, p.getFirst("GroupId"), p.getFirst("GroupName"),
Boolean.TRUE.equals(parseOptionalBoolean(dryRun, "DryRun")));
return xmlResponse(new XmlBuilder().start("DeleteSecurityGroupResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString()).elem("return", "true")
.elem("groupId", groupId).end("DeleteSecurityGroupResponse").build());
}
private Response handleAuthorizeSecurityGroupIngress(MultivaluedMap<String, String> p, String region) {
@@ -341,6 +341,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// released between the launch's availability check and the store of its instance.
private final Object hostLock = new Object();
private final Set<String> seededAccountRegions = ConcurrentHashMap.newKeySet();
// References held while a group assignment applies firewall state before publishing its instance.
private final Map<String, Integer> pendingSecurityGroupAssignments = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, RefCountedLock> instanceGroupLocks = new ConcurrentHashMap<>();
// region::subnetId → offset the next synthesised address is tried at. Only an ordering hint:
// restart forgets it, and privateIpsInUse is what keeps addresses from being handed out twice.
private final Map<String, Long> subnetIpCursors = new HashMap<>();
@@ -4156,141 +4159,149 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
if (dryRun) {
throw new AwsException("DryRunOperation", "Request would have succeeded, but DryRun flag is set.", 412);
}
synchronized (privateIpAllocationLock) {
int admitted = !config.services().ec2().enforceVcpuQuotas() || spot || "host".equals(tenancy)
? count : admittedInstanceCount(region, effectiveInstanceType, minCount, capacityMaxCount);
synchronized (hostLock) {
if (hostId != null) {
// Re-checked under hostLock: a ReleaseHosts or ModifyHosts may have landed
// since the unlocked check above.
validateHostPlacement(getRequiredAvailableHost(region, hostId), az, effectiveInstanceType, tenancy);
}
List<String> privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni,
privateIpAddress, admitted);
for (int i = 0; i < admitted; i++) {
String instanceId = "i-" + randomHex(17);
String privateIp = privateIps.get(i);
synchronized (attachmentTopologyLock(region)) {
if (finalSubnetId != null) {
requireSubnet(region, finalSubnetId);
}
for (GroupIdentifier group : sgIdentifiers) {
getRequiredSecurityGroup(region, group.getGroupId());
}
synchronized (privateIpAllocationLock) {
int admitted = !config.services().ec2().enforceVcpuQuotas() || spot || "host".equals(tenancy)
? count : admittedInstanceCount(region, effectiveInstanceType, minCount, capacityMaxCount);
synchronized (hostLock) {
if (hostId != null) {
// Re-checked under hostLock: a ReleaseHosts or ModifyHosts may have landed
// since the unlocked check above.
validateHostPlacement(getRequiredAvailableHost(region, hostId), az, effectiveInstanceType, tenancy);
}
List<String> privateIps = allocateLaunchAddresses(region, finalSubnetId, suppliedEni,
privateIpAddress, admitted);
for (int i = 0; i < admitted; i++) {
String instanceId = "i-" + randomHex(17);
String privateIp = privateIps.get(i);
Instance inst = new Instance();
inst.setInstanceId(instanceId);
inst.setOwnerId(callerAccountId());
inst.setImageId(imageId);
inst.setState(InstanceState.pending());
inst.setInstanceType(effectiveInstanceType);
inst.setSpot(spot);
inst.setCapacityReservationPlatform(capacityReservationPlatform(region, imageId));
inst.setCapacityReservationPreference(capacityTargetId == null ? capacityPreference : null);
inst.setCapacityReservationTarget(capacityTargetId);
inst.setCapacityReservationGroupArn(capacityGroupArn);
Placement placement = new Placement(az);
placement.setHostId(hostId);
if (tenancy != null && !tenancy.isBlank()) {
placement.setTenancy(tenancy);
}
inst.setPlacement(placement);
inst.setSubnetId(finalSubnetId);
inst.setVpcId(vpcId);
// AWS precedence (#1984): the launch-time AssociatePublicIpAddress
// override wins in both directions; the subnet's MapPublicIpOnLaunch
// attribute is only the default when the launch does not specify it. An
// interface the caller created never takes an automatic address.
inst.setAssociatePublicIp(suppliedEni == null && (associatePublicIp != null
? associatePublicIp
: subnet != null && subnet.isMapPublicIpOnLaunch()));
inst.setPrivateIpAddress(privateIp);
inst.setPrivateDnsName(AwsRegions.ec2PrivateIpDnsName(privateIp, region));
inst.setKeyName(keyName);
inst.setSecurityGroups(new ArrayList<>(sgIdentifiers));
inst.setArchitecture(architecture);
inst.setLaunchTime(Instant.now());
inst.setAmiLaunchIndex(i);
inst.setClientToken(clientToken);
inst.setRegion(region);
inst.setUserData(userData);
inst.setEncodedUserData(encodedUserData);
inst.setIamInstanceProfileArn(iamInstanceProfileArn);
if (launchProfile != null) {
inst.setIamInstanceProfileId(launchProfile.getInstanceProfileId());
inst.setIamInstanceProfileAssociationTime(inst.getLaunchTime());
}
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null));
inst.setCreditSpecificationCpuCredits(
acquiredCpuCredits(effectiveInstanceType, creditSpecificationCpuCredits));
if (instanceTags != null && !instanceTags.isEmpty()) {
inst.setTags(new ArrayList<>(instanceTags));
putTags(region, instanceId, new ArrayList<>(instanceTags));
}
// Network interface, either the caller-supplied standalone ENI (override-default-eni,
// floci-kt9) or a freshly-minted implicit primary interface.
InstanceNetworkInterface eni = new InstanceNetworkInterface();
eni.setNetworkInterfaceId(suppliedEni != null
? suppliedEni.getNetworkInterfaceId()
: "eni-" + randomHex(17));
eni.setSubnetId(finalSubnetId);
eni.setVpcId(vpcId);
eni.setOwnerId(callerAccountId());
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
eni.setPrivateIpAddress(privateIp);
eni.setPrivateDnsName(inst.getPrivateDnsName());
eni.setGroups(new ArrayList<>(sgIdentifiers));
eni.setAttachmentId("eni-attach-" + randomHex(17));
eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0);
if (inst.getLaunchTime() != null) {
eni.setAttachTime(ISO_FMT.format(inst.getLaunchTime()));
}
inst.getNetworkInterfaces().add(eni);
if (suppliedEni != null) {
// The standalone record stays authoritative rather than being folded into the
// instance: AWS defaults deleteOnTermination to false for an interface the caller
// created and handed to a launch, so it outlives the instance and returns to
// "available" on termination instead of vanishing with it. Double-counting is
// avoided in describeNetworkInterfaces, which skips the instance-side copy of any
// id the standalone store owns.
NetworkInterfaceAttachment launchAttachment = new NetworkInterfaceAttachment();
launchAttachment.setAttachmentId(eni.getAttachmentId());
launchAttachment.setDeviceIndex(eni.getDeviceIndex());
launchAttachment.setStatus("attached");
launchAttachment.setInstanceId(instanceId);
launchAttachment.setInstanceOwnerId(callerAccountId());
launchAttachment.setAttachTime(eni.getAttachTime());
launchAttachment.setDeleteOnTermination(false);
suppliedEni.setAttachment(launchAttachment);
suppliedEni.setStatus("in-use");
networkInterfaces.put(key(region, suppliedEni.getNetworkInterfaceId()), suppliedEni);
// An Elastic IP the interface kept from an earlier instance is this one's
// public address; with a container, the launch re-points it once it runs.
Address carried = primaryElasticAddress(region, inst);
if (carried != null) {
setPublicAddress(inst, carried.getPublicIp());
Instance inst = new Instance();
inst.setInstanceId(instanceId);
inst.setOwnerId(callerAccountId());
inst.setImageId(imageId);
inst.setState(InstanceState.pending());
inst.setInstanceType(effectiveInstanceType);
inst.setSpot(spot);
inst.setCapacityReservationPlatform(capacityReservationPlatform(region, imageId));
inst.setCapacityReservationPreference(capacityTargetId == null ? capacityPreference : null);
inst.setCapacityReservationTarget(capacityTargetId);
inst.setCapacityReservationGroupArn(capacityGroupArn);
Placement placement = new Placement(az);
placement.setHostId(hostId);
if (tenancy != null && !tenancy.isBlank()) {
placement.setTenancy(tenancy);
}
}
inst.setRootDeviceName(rootDeviceName);
for (LaunchVolume planned : launchVolumes) {
Volume volume = newVolume(region, az, planned.volumeType(), planned.size(),
planned.encrypted(), planned.kmsKeyId(), planned.iops(), planned.throughput(),
planned.snapshotId());
volume.setState("in-use");
VolumeAttachment attachment = new VolumeAttachment();
attachment.setVolumeId(volume.getVolumeId());
attachment.setInstanceId(instanceId);
attachment.setDevice(planned.deviceName());
attachment.setState("attached");
attachment.setDeleteOnTermination(planned.deleteOnTermination());
attachment.setAttachTime(inst.getLaunchTime());
volume.getAttachments().add(attachment);
volumes.put(key(region, volume.getVolumeId()), volume);
reservation.getLaunchVolumeIds().add(volume.getVolumeId());
if (rootDeviceName.equals(planned.deviceName())) {
inst.setRootVolumeId(volume.getVolumeId());
inst.setPlacement(placement);
inst.setSubnetId(finalSubnetId);
inst.setVpcId(vpcId);
// AWS precedence (#1984): the launch-time AssociatePublicIpAddress
// override wins in both directions; the subnet's MapPublicIpOnLaunch
// attribute is only the default when the launch does not specify it. An
// interface the caller created never takes an automatic address.
inst.setAssociatePublicIp(suppliedEni == null && (associatePublicIp != null
? associatePublicIp
: subnet != null && subnet.isMapPublicIpOnLaunch()));
inst.setPrivateIpAddress(privateIp);
inst.setPrivateDnsName(AwsRegions.ec2PrivateIpDnsName(privateIp, region));
inst.setKeyName(keyName);
inst.setSecurityGroups(new ArrayList<>(sgIdentifiers));
inst.setArchitecture(architecture);
inst.setLaunchTime(Instant.now());
inst.setAmiLaunchIndex(i);
inst.setClientToken(clientToken);
inst.setRegion(region);
inst.setUserData(userData);
inst.setEncodedUserData(encodedUserData);
inst.setIamInstanceProfileArn(iamInstanceProfileArn);
if (launchProfile != null) {
inst.setIamInstanceProfileId(launchProfile.getInstanceProfileId());
inst.setIamInstanceProfileAssociationTime(inst.getLaunchTime());
}
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null));
inst.setCreditSpecificationCpuCredits(
acquiredCpuCredits(effectiveInstanceType, creditSpecificationCpuCredits));
if (instanceTags != null && !instanceTags.isEmpty()) {
inst.setTags(new ArrayList<>(instanceTags));
putTags(region, instanceId, new ArrayList<>(instanceTags));
}
}
instances.put(key(region, instanceId), inst);
launched.add(inst);
reservation.getInstances().add(inst);
// Network interface, either the caller-supplied standalone ENI (override-default-eni,
// floci-kt9) or a freshly-minted implicit primary interface.
InstanceNetworkInterface eni = new InstanceNetworkInterface();
eni.setNetworkInterfaceId(suppliedEni != null
? suppliedEni.getNetworkInterfaceId()
: "eni-" + randomHex(17));
eni.setSubnetId(finalSubnetId);
eni.setVpcId(vpcId);
eni.setOwnerId(callerAccountId());
eni.setDescription(suppliedEni != null ? suppliedEni.getDescription() : null);
eni.setMacAddress(suppliedEni != null ? suppliedEni.getMacAddress() : null);
eni.setPrivateIpAddress(privateIp);
eni.setPrivateDnsName(inst.getPrivateDnsName());
eni.setGroups(new ArrayList<>(sgIdentifiers));
eni.setAttachmentId("eni-attach-" + randomHex(17));
eni.setDeviceIndex(suppliedEni != null ? networkInterfaceDeviceIndex : 0);
if (inst.getLaunchTime() != null) {
eni.setAttachTime(ISO_FMT.format(inst.getLaunchTime()));
}
inst.getNetworkInterfaces().add(eni);
if (suppliedEni != null) {
// The standalone record stays authoritative rather than being folded into the
// instance: AWS defaults deleteOnTermination to false for an interface the caller
// created and handed to a launch, so it outlives the instance and returns to
// "available" on termination instead of vanishing with it. Double-counting is
// avoided in describeNetworkInterfaces, which skips the instance-side copy of any
// id the standalone store owns.
NetworkInterfaceAttachment launchAttachment = new NetworkInterfaceAttachment();
launchAttachment.setAttachmentId(eni.getAttachmentId());
launchAttachment.setDeviceIndex(eni.getDeviceIndex());
launchAttachment.setStatus("attached");
launchAttachment.setInstanceId(instanceId);
launchAttachment.setInstanceOwnerId(callerAccountId());
launchAttachment.setAttachTime(eni.getAttachTime());
launchAttachment.setDeleteOnTermination(false);
suppliedEni.setAttachment(launchAttachment);
suppliedEni.setStatus("in-use");
networkInterfaces.put(key(region, suppliedEni.getNetworkInterfaceId()), suppliedEni);
// An Elastic IP the interface kept from an earlier instance is this one's
// public address; with a container, the launch re-points it once it runs.
Address carried = primaryElasticAddress(region, inst);
if (carried != null) {
setPublicAddress(inst, carried.getPublicIp());
}
}
inst.setRootDeviceName(rootDeviceName);
for (LaunchVolume planned : launchVolumes) {
Volume volume = newVolume(region, az, planned.volumeType(), planned.size(),
planned.encrypted(), planned.kmsKeyId(), planned.iops(), planned.throughput(),
planned.snapshotId());
volume.setState("in-use");
VolumeAttachment attachment = new VolumeAttachment();
attachment.setVolumeId(volume.getVolumeId());
attachment.setInstanceId(instanceId);
attachment.setDevice(planned.deviceName());
attachment.setState("attached");
attachment.setDeleteOnTermination(planned.deleteOnTermination());
attachment.setAttachTime(inst.getLaunchTime());
volume.getAttachments().add(attachment);
volumes.put(key(region, volume.getVolumeId()), volume);
reservation.getLaunchVolumeIds().add(volume.getVolumeId());
if (rootDeviceName.equals(planned.deviceName())) {
inst.setRootVolumeId(volume.getVolumeId());
}
}
instances.put(key(region, instanceId), inst);
launched.add(inst);
reservation.getInstances().add(inst);
}
}
}
}
@@ -5834,37 +5845,69 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
*/
public void modifyInstanceGroups(String region, String instanceId, List<String> groupIds) {
ensureDefaultResources(region);
String instanceKey = callerAccountId() + "::" + key(region, instanceId);
// This per-instance lock precedes the topology lock; external I/O holds only this lock.
withResourceLock(instanceGroupLocks, instanceKey, () -> {
modifyInstanceGroupsLocked(region, instanceId, groupIds);
return null;
});
}
private void modifyInstanceGroupsLocked(String region, String instanceId, List<String> groupIds) {
Instance inst = getRequiredInstance(region, instanceId);
List<GroupIdentifier> identifiers = new ArrayList<>();
for (String groupId : groupIds) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
if (!Objects.equals(inst.getVpcId(), sg.getVpcId())) {
throw new AwsException("InvalidGroup.NotFound", "Security group is not in the instance VPC", 400);
List<String> protectedGroups = new ArrayList<>();
synchronized (attachmentTopologyLock(region)) {
for (String groupId : groupIds) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
if (!Objects.equals(inst.getVpcId(), sg.getVpcId())) {
throw new AwsException("InvalidGroup.NotFound", "Security group is not in the instance VPC", 400);
}
identifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
protectedGroups.add(callerAccountId() + "::" + key(region, sg.getGroupId()));
}
identifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
protectedGroups.forEach(group -> pendingSecurityGroupAssignments.merge(group, 1, Integer::sum));
}
if (securityGroupEnforcementEnabled() && !config.services().ec2().mock()
&& inst.getState() != null && "running".equals(inst.getState().getName())
&& inst.getNetworkInterfaces() != null && !inst.getNetworkInterfaces().isEmpty()) {
List<SecurityGroup> current = securityGroups.scan(k -> k.startsWith(region + "::"));
Map<String, SecurityGroup> byId = current.stream().collect(Collectors.toMap(
SecurityGroup::getGroupId, Function.identity()));
containerManager.updateSecurityGroups(inst.getNetworkInterfaces().getFirst().getNetworkInterfaceId(),
new HashSet<>(groupIds), byId, policyPrefixLists(region, current));
}
try {
if (securityGroupEnforcementEnabled() && !config.services().ec2().mock()
&& inst.getState() != null && "running".equals(inst.getState().getName())
&& inst.getNetworkInterfaces() != null && !inst.getNetworkInterfaces().isEmpty()) {
List<SecurityGroup> current = securityGroups.scan(k -> k.startsWith(region + "::"));
Map<String, SecurityGroup> byId = current.stream().collect(Collectors.toMap(
SecurityGroup::getGroupId, Function.identity()));
containerManager.updateSecurityGroups(inst.getNetworkInterfaces().getFirst().getNetworkInterfaceId(),
new HashSet<>(groupIds), byId, policyPrefixLists(region, current));
}
inst.setSecurityGroups(new ArrayList<>(identifiers));
if (inst.getNetworkInterfaces() != null) {
inst.getNetworkInterfaces().forEach(eni -> eni.setGroups(new ArrayList<>(identifiers)));
}
instances.put(key(region, instanceId), inst);
synchronized (attachmentTopologyLock(region)) {
inst.setSecurityGroups(new ArrayList<>(identifiers));
if (inst.getNetworkInterfaces() != null) {
for (InstanceNetworkInterface eni : inst.getNetworkInterfaces()) {
eni.setGroups(new ArrayList<>(identifiers));
networkInterfaces.get(key(region, eni.getNetworkInterfaceId())).ifPresent(stored -> {
NetworkInterfaceAttachment attachment = stored.getAttachment();
if (attachment != null && instanceId.equals(attachment.getInstanceId())) {
stored.setGroups(new ArrayList<>(identifiers));
networkInterfaces.put(key(region, stored.getNetworkInterfaceId()), stored);
}
});
}
}
instances.put(key(region, instanceId), inst);
}
if (config.services().ec2().publishSecurityGroupPorts() && !config.services().ec2().mock()
&& inst.getDockerContainerId() != null
&& inst.getState() != null && "running".equals(inst.getState().getName())) {
portForwardManager.reconcile(inst, desiredPublishedPorts(region, inst));
if (config.services().ec2().publishSecurityGroupPorts() && !config.services().ec2().mock()
&& inst.getDockerContainerId() != null
&& inst.getState() != null && "running".equals(inst.getState().getName())) {
portForwardManager.reconcile(inst, desiredPublishedPorts(region, inst));
}
} finally {
synchronized (attachmentTopologyLock(region)) {
protectedGroups.forEach(group -> pendingSecurityGroupAssignments.computeIfPresent(
group, (ignored, count) -> count == 1 ? null : count - 1));
}
}
}
@@ -6864,10 +6907,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
endpoint.setPolicyDocument(policyDocument);
if (endpointTags != null && !endpointTags.isEmpty()) {
endpoint.setTags(new ArrayList<>(endpointTags));
putTags(region, endpoint.getVpcEndpointId(), new ArrayList<>(endpointTags));
}
synchronized (attachmentTopologyLock(region)) {
getRequiredVpc(region, vpcId);
for (String securityGroupId : securityGroupIds) {
getRequiredSecurityGroup(region, securityGroupId);
}
if (endpointTags != null && !endpointTags.isEmpty()) {
putTags(region, endpoint.getVpcEndpointId(), new ArrayList<>(endpointTags));
}
vpcEndpoints.put(key(region, endpoint.getVpcEndpointId()), endpoint);
}
return endpoint;
@@ -6931,11 +6979,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// each caller reads the same association list, adds its own id, and the last write
// wins -- leaving the other caller's waiter polling for an association that was
// silently dropped.
synchronized (lockFor(key(region, endpointId))) {
return modifyVpcEndpointLocked(region, endpointId,
addRouteTableIds, removeRouteTableIds, addSubnetIds, removeSubnetIds,
addSecurityGroupIds, removeSecurityGroupIds,
policyDocument, resetPolicy, privateDnsEnabled, subnetConfigurations, ipAddressType);
synchronized (attachmentTopologyLock(region)) {
synchronized (lockFor(key(region, endpointId))) {
return modifyVpcEndpointLocked(region, endpointId,
addRouteTableIds, removeRouteTableIds, addSubnetIds, removeSubnetIds,
addSecurityGroupIds, removeSecurityGroupIds,
policyDocument, resetPolicy, privateDnsEnabled, subnetConfigurations, ipAddressType);
}
}
}
@@ -7083,11 +7133,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
ensureDefaultResources(region);
List<VpcEndpoint> deleted = new ArrayList<>();
for (String endpointId : endpointIds) {
VpcEndpoint endpoint = getRequiredVpcEndpoint(region, endpointId);
endpoint.setState("deleted");
vpcEndpoints.delete(key(region, endpointId));
removeTags(region, endpointId);
deleted.add(endpoint);
synchronized (attachmentTopologyLock(region)) {
synchronized (lockFor(key(region, endpointId))) {
VpcEndpoint endpoint = getRequiredVpcEndpoint(region, endpointId);
endpoint.setState("deleted");
vpcEndpoints.delete(key(region, endpointId));
removeTags(region, endpointId);
deleted.add(endpoint);
}
}
}
return deleted;
}
@@ -7804,14 +7858,6 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public SecurityGroup createSecurityGroup(String region, String groupName, String description, String vpcId) {
vpcId = requireSecurityGroupVpc(region, vpcId).getVpcId();
// Check duplicate
String finalVpcId = vpcId;
boolean exists = securityGroups.scan(k -> true).stream()
.anyMatch(sg -> sg.getRegion().equals(region) && Objects.equals(sg.getGroupName(), groupName)
&& finalVpcId.equals(sg.getVpcId()));
if (exists) {
throw new AwsException("InvalidGroup.Duplicate", "The security group '" + groupName + "' already exists", 400);
}
String sgId = "sg-" + randomHex(17);
SecurityGroup sg = new SecurityGroup();
sg.setGroupId(sgId);
@@ -7827,14 +7873,46 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
sg.getIpPermissionsEgress().add(egressAll);
synchronized (attachmentTopologyLock(region)) {
getRequiredVpc(region, sg.getVpcId());
securityGroups.put(key(region, sgId), sg);
boolean exists = securityGroups.scan(k -> true).stream()
.anyMatch(existing -> existing.getRegion().equals(region)
&& Objects.equals(existing.getGroupName(), groupName)
&& sg.getVpcId().equals(existing.getVpcId()));
if (exists) {
throw new AwsException("InvalidGroup.Duplicate",
"The security group '" + groupName + "' already exists", 400);
}
SecurityGroupRule defaultRule = newRule(sgId, egressAll, true);
defaultRule.setCidrIpv4("0.0.0.0/0");
try {
securityGroups.put(key(region, sgId), sg);
// Publish the default rule before a concurrent delete can remove this group.
securityGroupRules.put(key(region, defaultRule.getSecurityGroupRuleId()), defaultRule);
} catch (RuntimeException failure) {
rollbackSecurityGroupCreation(region, sgId, defaultRule.getSecurityGroupRuleId(), failure);
throw failure;
}
}
// Persist the default egress rule as a SecurityGroupRule so that
// DescribeSecurityGroupRules can find it immediately (#1093).
createRules(region, sgId, egressAll, true);
return sg;
}
private void rollbackSecurityGroupCreation(String region, String groupId, String ruleId,
RuntimeException failure) {
try {
securityGroupRules.delete(key(region, ruleId));
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
LOG.errorv(cleanupFailure, "Failed to remove default rule {0} after group creation failed in {1}",
ruleId, region);
}
try {
securityGroups.delete(key(region, groupId));
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
LOG.errorv(cleanupFailure, "Failed to remove security group {0} after creation failed in {1}",
groupId, region);
}
}
public List<SecurityGroup> describeSecurityGroups(String region, List<String> groupIds,
List<String> groupNames, Map<String, List<String>> filters) {
return describeSecurityGroups(region, groupIds, groupNames, filterList(filters));
@@ -7879,27 +7957,102 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public void deleteSecurityGroup(String region, String groupId) {
ensureDefaultResources(region);
if (securityGroups.get(key(region, groupId)).isEmpty()) {
throw new AwsException("InvalidGroup.NotFound", "The security group '" + groupId + "' does not exist", 400);
deleteSecurityGroup(region, groupId, null, false);
}
public String deleteSecurityGroup(String region, String groupId, String groupName, boolean dryRun) {
if ((groupId == null || groupId.isBlank()) && (groupName == null || groupName.isBlank())) {
throw new AwsException("MissingParameter", "The request must contain GroupId or GroupName", 400);
}
securityGroups.delete(key(region, groupId));
ensureDefaultResources(region);
String selectedId = groupId;
if (selectedId == null || selectedId.isBlank()) {
Vpc defaultVpc = vpcs.scan(k -> k.startsWith(region + "::")).stream()
.filter(Vpc::isDefault).findFirst().orElseThrow(() ->
new AwsException("VPCIdNotSpecified", "No default VPC for this user", 400));
selectedId = securityGroups.scan(k -> k.startsWith(region + "::")).stream()
.filter(group -> defaultVpc.getVpcId().equals(group.getVpcId())
&& groupName.equals(group.getGroupName()))
.map(SecurityGroup::getGroupId).findFirst().orElseThrow(() ->
new AwsException("InvalidGroup.NotFound",
"The security group '" + groupName + "' does not exist in the default VPC", 400));
}
synchronized (attachmentTopologyLock(region)) {
synchronized (lockFor(key(region, selectedId))) {
SecurityGroup selected = getRequiredSecurityGroup(region, selectedId);
if ("default".equals(selected.getGroupName())) {
throw new AwsException("CannotDelete", "The default security group cannot be deleted", 400);
}
if (hasSecurityGroupDependencies(region, selected)) {
throw new AwsException("DependencyViolation",
"The security group '" + selectedId + "' has a dependent object", 400);
}
if (dryRun) {
throw new AwsException("DryRunOperation",
"Request would have succeeded, but DryRun flag is set.", 412);
}
securityGroups.delete(key(region, selectedId));
removeTags(region, selectedId);
securityGroupRules.scan(k -> k.startsWith(region + "::")).stream()
.filter(rule -> selected.getGroupId().equals(rule.getGroupId()))
.forEach(rule -> {
securityGroupRules.delete(key(region, rule.getSecurityGroupRuleId()));
removeTags(region, rule.getSecurityGroupRuleId());
});
}
}
return selectedId;
}
private boolean hasSecurityGroupDependencies(String region, SecurityGroup selected) {
String groupId = selected.getGroupId();
if (pendingSecurityGroupAssignments.containsKey(callerAccountId() + "::" + key(region, groupId))) {
return true;
}
if (networkInterfaces.scan(k -> k.startsWith(region + "::")).stream()
.anyMatch(eni -> nullToEmpty(eni.getGroups()).stream().anyMatch(group -> groupId.equals(group.getGroupId())))) {
return true;
}
if (instances.scan(k -> k.startsWith(region + "::")).stream()
.filter(instance -> instance.getState() == null || !"terminated".equals(instance.getState().getName()))
.anyMatch(instance -> nullToEmpty(instance.getSecurityGroups()).stream()
.anyMatch(group -> groupId.equals(group.getGroupId())))) {
return true;
}
if (vpcEndpoints.scan(k -> k.startsWith(region + "::")).stream()
.anyMatch(endpoint -> nullToEmpty(endpoint.getSecurityGroupIds()).contains(groupId))) {
return true;
}
if (instanceConnectEndpoints.scan(k -> k.startsWith(region + "::")).stream()
.anyMatch(endpoint -> nullToEmpty(endpoint.getSecurityGroupIds()).contains(groupId))) {
return true;
}
return securityGroups.scan(k -> k.startsWith(region + "::")).stream()
.filter(group -> !groupId.equals(group.getGroupId())
&& Objects.equals(selected.getVpcId(), group.getVpcId()))
.flatMap(group -> Stream.concat(
nullToEmpty(group.getIpPermissions()).stream(), nullToEmpty(group.getIpPermissionsEgress()).stream()))
.flatMap(permission -> nullToEmpty(permission.getUserIdGroupPairs()).stream())
.anyMatch(pair -> groupId.equals(pair.getGroupId())
&& (pair.getUserId() == null || Objects.equals(selected.getOwnerId(), pair.getUserId())));
}
public List<SecurityGroupRule> authorizeSecurityGroupIngress(String region, String groupId, List<IpPermission> permissions) {
ensureDefaultResources(region);
List<SecurityGroupRule> rules = new ArrayList<>();
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
requireKnownPrefixLists(region, permissions);
List<IpPermission> next = new ArrayList<>(sg.getIpPermissions());
for (IpPermission perm : permissions) {
resolveGroupReferences(region, sg.getVpcId(), perm);
next.add(perm);
rules.addAll(createRules(region, groupId, perm, false));
synchronized (attachmentTopologyLock(region)) {
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
requireKnownPrefixLists(region, permissions);
List<IpPermission> next = new ArrayList<>(sg.getIpPermissions());
for (IpPermission perm : permissions) {
resolveGroupReferences(region, sg.getVpcId(), perm);
next.add(perm);
rules.addAll(createRules(region, groupId, perm, false));
}
sg.setIpPermissions(next);
securityGroups.put(key(region, groupId), sg);
}
sg.setIpPermissions(next);
securityGroups.put(key(region, groupId), sg);
}
reconcilePublishedPortsForGroup(region, groupId);
return rules;
@@ -7908,17 +8061,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public List<SecurityGroupRule> authorizeSecurityGroupEgress(String region, String groupId, List<IpPermission> permissions) {
ensureDefaultResources(region);
List<SecurityGroupRule> rules = new ArrayList<>();
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
requireKnownPrefixLists(region, permissions);
List<IpPermission> next = new ArrayList<>(sg.getIpPermissionsEgress());
for (IpPermission perm : permissions) {
resolveGroupReferences(region, sg.getVpcId(), perm);
next.add(perm);
rules.addAll(createRules(region, groupId, perm, true));
synchronized (attachmentTopologyLock(region)) {
synchronized (lockFor(key(region, groupId))) {
SecurityGroup sg = getRequiredSecurityGroup(region, groupId);
requireKnownPrefixLists(region, permissions);
List<IpPermission> next = new ArrayList<>(sg.getIpPermissionsEgress());
for (IpPermission perm : permissions) {
resolveGroupReferences(region, sg.getVpcId(), perm);
next.add(perm);
rules.addAll(createRules(region, groupId, perm, true));
}
sg.setIpPermissionsEgress(next);
securityGroups.put(key(region, groupId), sg);
}
sg.setIpPermissionsEgress(next);
securityGroups.put(key(region, groupId), sg);
}
reconcileFirewallPolicies(region);
return rules;
@@ -14729,10 +14884,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
private record VolumeDevice(String accountId, String region, String instanceId, String device) {}
private <T> T withVolumeLock(String volumeId, Supplier<T> action) {
if (volumeId == null) {
return withResourceLock(volumeLocks, volumeId, action);
}
private <T> T withResourceLock(ConcurrentHashMap<String, RefCountedLock> locks, String resourceId, Supplier<T> action) {
if (resourceId == null) {
return action.get();
}
RefCountedLock refLock = volumeLocks.compute(volumeId, (k, v) -> {
RefCountedLock refLock = locks.compute(resourceId, (k, v) -> {
if (v == null) {
return new RefCountedLock();
}
@@ -14744,7 +14903,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return action.get();
} finally {
refLock.lock.unlock();
volumeLocks.computeIfPresent(volumeId, (k, v) -> {
locks.computeIfPresent(resourceId, (k, v) -> {
if (v.refCount.decrementAndGet() <= 0) {
return null;
}
@@ -15414,86 +15573,88 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
"The request must contain the parameter SubnetId", 400);
}
ensureDefaultResources(region);
Subnet subnet = requireSubnet(region, subnetId);
synchronized (attachmentTopologyLock(region)) {
Subnet subnet = requireSubnet(region, subnetId);
List<GroupIdentifier> sgIdentifiers = new ArrayList<>();
if (securityGroupIds != null && !securityGroupIds.isEmpty()) {
for (String sgId : securityGroupIds) {
SecurityGroup sg = securityGroups.get(key(region, sgId)).orElseThrow(() ->
new AwsException("InvalidSecurityGroupID.NotFound",
"The securityGroup ID '" + sgId + "' does not exist", 400));
if (!subnet.getVpcId().equals(sg.getVpcId())) {
throw new AwsException("InvalidGroup.NotFound",
"Security group " + sgId + " does not belong to the subnet VPC", 400);
List<GroupIdentifier> sgIdentifiers = new ArrayList<>();
if (securityGroupIds != null && !securityGroupIds.isEmpty()) {
for (String sgId : securityGroupIds) {
SecurityGroup sg = securityGroups.get(key(region, sgId)).orElseThrow(() ->
new AwsException("InvalidSecurityGroupID.NotFound",
"The securityGroup ID '" + sgId + "' does not exist", 400));
if (!subnet.getVpcId().equals(sg.getVpcId())) {
throw new AwsException("InvalidGroup.NotFound",
"Security group " + sgId + " does not belong to the subnet VPC", 400);
}
sgIdentifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
}
sgIdentifiers.add(new GroupIdentifier(sg.getGroupId(), sg.getGroupName()));
} else {
defaultSecurityGroupOf(region, subnet.getVpcId()).ifPresent(defaultSg ->
sgIdentifiers.add(new GroupIdentifier(defaultSg.getGroupId(), defaultSg.getGroupName())));
}
} else {
defaultSecurityGroupOf(region, subnet.getVpcId()).ifPresent(defaultSg ->
sgIdentifiers.add(new GroupIdentifier(defaultSg.getGroupId(), defaultSg.getGroupName())));
}
// An explicit address is checked the way RunInstances checks its PrivateIpAddress: it must be
// one the subnet can assign, in canonical form, and no other resource may hold it. Unlike a
// launch it takes no lease on the VPC network (see requireRequestedPrivateIpFree).
String requestedIp = (privateIpAddress != null && !privateIpAddress.isBlank())
? validateRequestedPrivateIp(privateIpAddress, subnet, null, 1) : null;
synchronized (privateIpAllocationLock) {
String eniId = "eni-" + randomHex(17);
if (requestedIp != null) {
requireRequestedPrivateIpFree(region, subnetId, requestedIp);
}
// Secondaries are folded and checked before the primary is allocated, so a refused one
// leaves no lease behind on the VPC network. Their range is not checked, as before.
Set<String> secondaries = new LinkedHashSet<>();
for (String extra : privateIpAddresses == null ? List.<String>of() : privateIpAddresses) {
if (extra == null || extra.isBlank()) {
continue;
// An explicit address is checked the way RunInstances checks its PrivateIpAddress: it must be
// one the subnet can assign, in canonical form, and no other resource may hold it. Unlike a
// launch it takes no lease on the VPC network (see requireRequestedPrivateIpFree).
String requestedIp = (privateIpAddress != null && !privateIpAddress.isBlank())
? validateRequestedPrivateIp(privateIpAddress, subnet, null, 1) : null;
synchronized (privateIpAllocationLock) {
String eniId = "eni-" + randomHex(17);
if (requestedIp != null) {
requireRequestedPrivateIpFree(region, subnetId, requestedIp);
}
String ip = canonicalIpv4(extra).orElse(extra);
if (!ip.equals(requestedIp) && secondaries.add(ip)) {
requireRequestedPrivateIpFree(region, subnetId, ip);
// Secondaries are folded and checked before the primary is allocated, so a refused one
// leaves no lease behind on the VPC network. Their range is not checked, as before.
Set<String> secondaries = new LinkedHashSet<>();
for (String extra : privateIpAddresses == null ? List.<String>of() : privateIpAddresses) {
if (extra == null || extra.isBlank()) {
continue;
}
String ip = canonicalIpv4(extra).orElse(extra);
if (!ip.equals(requestedIp) && secondaries.add(ip)) {
requireRequestedPrivateIpFree(region, subnetId, ip);
}
}
}
String primaryIp = requestedIp != null ? requestedIp : assignPrivateIp(region, subnetId);
String primaryDns = AwsRegions.ec2PrivateIpDnsName(primaryIp, region);
String primaryIp = requestedIp != null ? requestedIp : assignPrivateIp(region, subnetId);
String primaryDns = AwsRegions.ec2PrivateIpDnsName(primaryIp, region);
NetworkInterface ni = new NetworkInterface();
ni.setNetworkInterfaceId(eniId);
ni.setSubnetId(subnetId);
ni.setVpcId(subnet.getVpcId());
ni.setAvailabilityZone(subnet.getAvailabilityZone());
ni.setDescription(description);
ni.setOwnerId(callerAccountId());
ni.setStatus("available");
ni.setMacAddress(randomMac());
ni.setPrivateIpAddress(primaryIp);
ni.setPrivateDnsName(primaryDns);
ni.setGroups(sgIdentifiers);
if (tagList != null) {
ni.getTagSet().addAll(tagList);
}
List<NetworkInterfacePrivateIpAddress> ipList = new ArrayList<>();
NetworkInterfacePrivateIpAddress primary = new NetworkInterfacePrivateIpAddress();
primary.setPrivateIpAddress(primaryIp);
primary.setPrivateDnsName(primaryDns);
primary.setPrimary(true);
ipList.add(primary);
for (String extra : secondaries) {
if (extra.equals(primaryIp)) {
continue;
NetworkInterface ni = new NetworkInterface();
ni.setNetworkInterfaceId(eniId);
ni.setSubnetId(subnetId);
ni.setVpcId(subnet.getVpcId());
ni.setAvailabilityZone(subnet.getAvailabilityZone());
ni.setDescription(description);
ni.setOwnerId(callerAccountId());
ni.setStatus("available");
ni.setMacAddress(randomMac());
ni.setPrivateIpAddress(primaryIp);
ni.setPrivateDnsName(primaryDns);
ni.setGroups(sgIdentifiers);
if (tagList != null) {
ni.getTagSet().addAll(tagList);
}
NetworkInterfacePrivateIpAddress secondary = new NetworkInterfacePrivateIpAddress();
secondary.setPrivateIpAddress(extra);
secondary.setPrivateDnsName(AwsRegions.ec2PrivateIpDnsName(extra, region));
secondary.setPrimary(false);
ipList.add(secondary);
}
ni.setPrivateIpAddresses(ipList);
networkInterfaces.put(key(region, eniId), ni);
return ni;
List<NetworkInterfacePrivateIpAddress> ipList = new ArrayList<>();
NetworkInterfacePrivateIpAddress primary = new NetworkInterfacePrivateIpAddress();
primary.setPrivateIpAddress(primaryIp);
primary.setPrivateDnsName(primaryDns);
primary.setPrimary(true);
ipList.add(primary);
for (String extra : secondaries) {
if (extra.equals(primaryIp)) {
continue;
}
NetworkInterfacePrivateIpAddress secondary = new NetworkInterfacePrivateIpAddress();
secondary.setPrivateIpAddress(extra);
secondary.setPrivateDnsName(AwsRegions.ec2PrivateIpDnsName(extra, region));
secondary.setPrimary(false);
ipList.add(secondary);
}
ni.setPrivateIpAddresses(ipList);
networkInterfaces.put(key(region, eniId), ni);
return ni;
}
}
}