mirror of
https://github.com/floci-io/floci.git
synced 2026-12-03 10:17:48 -05:00
fix(ec2): make CreateVolume idempotent on its client token (#8301)
This commit is contained in:
1 parent
fdb4a811ba
commit
2337c34ef9
12 files changed
+489
-146
No files matched your search
@@ -0,0 +1,40 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/** ClientToken replays, for the EC2 calls that return what an earlier call with the same token made. */
|
||||
final class Ec2ClientTokens {
|
||||
|
||||
private Ec2ClientTokens() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource an earlier create made with {@code clientToken}: the first of {@code candidates} that carries the
|
||||
* token, or empty when the token is unset or unused. The candidates are only read when a token is set. A reused
|
||||
* token whose request differs from the first one ({@code sameRequest} false) fails with
|
||||
* IdempotentParameterMismatch, worded {@code mismatch}, as the EC2 idempotency guide documents.
|
||||
*/
|
||||
static <T> Optional<T> replay(String clientToken, Supplier<Stream<T>> candidates, Function<T, String> tokenOf,
|
||||
Predicate<T> sameRequest, String mismatch) {
|
||||
if (clientToken == null || clientToken.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<T> first = candidates.get().filter(candidate -> clientToken.equals(tokenOf.apply(candidate)))
|
||||
.findFirst();
|
||||
if (first.isPresent() && !sameRequest.test(first.get())) {
|
||||
throw new AwsException("IdempotentParameterMismatch", mismatch, 400);
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
/** As above, for a create whose replay is not compared with the first request. */
|
||||
static <T> Optional<T> replay(String clientToken, Supplier<Stream<T>> candidates, Function<T, String> tokenOf) {
|
||||
return replay(clientToken, candidates, tokenOf, first -> true, null);
|
||||
}
|
||||
}
|
||||
@@ -84,13 +84,10 @@ public class Ec2ClientVpnService implements VpcDependencyProvider {
|
||||
// ── Endpoints ──
|
||||
|
||||
public synchronized ClientVpnEndpoint createEndpoint(String region, EndpointRequest request, List<Tag> tags) {
|
||||
if (request.clientToken() != null) {
|
||||
Optional<ClientVpnEndpoint> replay = all(region).stream()
|
||||
.filter(endpoint -> request.clientToken().equals(endpoint.getClientToken()))
|
||||
.findFirst();
|
||||
if (replay.isPresent()) {
|
||||
return replay.get();
|
||||
}
|
||||
Optional<ClientVpnEndpoint> replay = Ec2ClientTokens.replay(request.clientToken(), () -> all(region).stream(),
|
||||
ClientVpnEndpoint::getClientToken);
|
||||
if (replay.isPresent()) {
|
||||
return replay.get();
|
||||
}
|
||||
if (request.clientCidrBlock() == null || !Ipv4Cidrs.isIpv4(request.clientCidrBlock())) {
|
||||
throw invalid("ClientCidrBlock must be an IPv4 CIDR block.");
|
||||
@@ -278,12 +275,10 @@ public class Ec2ClientVpnService implements VpcDependencyProvider {
|
||||
|
||||
private TargetNetwork associateWithSubnetsHeld(String region, String id, String subnetId, String clientToken) {
|
||||
ClientVpnEndpoint endpoint = require(region, id);
|
||||
if (clientToken != null) {
|
||||
Optional<TargetNetwork> replay = endpoint.getTargetNetworks().stream()
|
||||
.filter(network -> clientToken.equals(network.getClientToken())).findFirst();
|
||||
if (replay.isPresent()) {
|
||||
return replay.get();
|
||||
}
|
||||
Optional<TargetNetwork> replay = Ec2ClientTokens.replay(clientToken, () -> endpoint.getTargetNetworks().stream(),
|
||||
TargetNetwork::getClientToken);
|
||||
if (replay.isPresent()) {
|
||||
return replay.get();
|
||||
}
|
||||
if (blank(subnetId)) {
|
||||
throw missing("SubnetId");
|
||||
|
||||
@@ -258,13 +258,11 @@ public class Ec2IpamService {
|
||||
String ownerId = requestedOwnerId != null ? requestedOwnerId : callerAccountId();
|
||||
requireEnum(tier, TIERS, "Tier");
|
||||
requireEnum(meteredAccount, METERED_ACCOUNTS, "MeteredAccount");
|
||||
if (clientToken != null && !clientToken.isBlank()) {
|
||||
for (Ipam existing : ipams.scan(k -> true)) {
|
||||
if (region.equals(existing.getRegion())
|
||||
&& clientToken.equals(existing.getClientToken())) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
Optional<Ipam> replay = Ec2ClientTokens.replay(clientToken,
|
||||
() -> ipams.scan(k -> true).stream().filter(existing -> region.equals(existing.getRegion())),
|
||||
Ipam::getClientToken);
|
||||
if (replay.isPresent()) {
|
||||
return replay.get();
|
||||
}
|
||||
Ipam ipam = new Ipam();
|
||||
ipam.setIpamId("ipam-" + randomHex(17));
|
||||
@@ -494,14 +492,12 @@ public class Ec2IpamService {
|
||||
if (sourceIpamPoolId != null && sourceIpamPoolId.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "SourceIpamPoolId is required.", 400);
|
||||
}
|
||||
if (clientToken != null && !clientToken.isBlank()) {
|
||||
// Caller-partition scan: an idempotency token is scoped to the account that used it.
|
||||
for (IpamPool existing : pools.scan(k -> true)) {
|
||||
if (region.equals(existing.getRegion())
|
||||
&& clientToken.equals(existing.getClientToken())) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
// Caller-partition scan: an idempotency token is scoped to the account that used it.
|
||||
Optional<IpamPool> replay = Ec2ClientTokens.replay(clientToken,
|
||||
() -> pools.scan(k -> true).stream().filter(existing -> region.equals(existing.getRegion())),
|
||||
IpamPool::getClientToken);
|
||||
if (replay.isPresent()) {
|
||||
return replay.get();
|
||||
}
|
||||
if (sourceIpamPoolId != null) {
|
||||
requirePool(region, sourceIpamPoolId);
|
||||
@@ -676,12 +672,10 @@ public class Ec2IpamService {
|
||||
String clientToken) {
|
||||
OwnedPool ownedPool = requireOwnedPoolForMutation(region, ipamPoolId);
|
||||
IpamPool pool = ownedPool.pool();
|
||||
if (clientToken != null && !clientToken.isBlank()) {
|
||||
for (IpamPoolCidr existing : pool.getProvisionedCidrs()) {
|
||||
if (clientToken.equals(existing.getClientToken())) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
Optional<IpamPoolCidr> replay = Ec2ClientTokens.replay(clientToken, () -> pool.getProvisionedCidrs().stream(),
|
||||
IpamPoolCidr::getClientToken);
|
||||
if (replay.isPresent()) {
|
||||
return replay.get();
|
||||
}
|
||||
if (cidr == null || cidr.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "Cidr is required.", 400);
|
||||
@@ -727,12 +721,10 @@ public class Ec2IpamService {
|
||||
String description, String clientToken) {
|
||||
OwnedPool ownedPool = requireOwnedPool(region, ipamPoolId);
|
||||
IpamPool pool = ownedPool.pool();
|
||||
if (clientToken != null && !clientToken.isBlank()) {
|
||||
for (IpamPoolAllocation existing : pool.getAllocations()) {
|
||||
if (clientToken.equals(existing.getClientToken())) {
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
Optional<IpamPoolAllocation> replay = Ec2ClientTokens.replay(clientToken, () -> pool.getAllocations().stream(),
|
||||
IpamPoolAllocation::getClientToken);
|
||||
if (replay.isPresent()) {
|
||||
return replay.get();
|
||||
}
|
||||
List<String> provisioned = pool.getProvisionedCidrs().stream()
|
||||
.map(IpamPoolCidr::getCidr).toList();
|
||||
|
||||
@@ -6790,7 +6790,7 @@ public class Ec2QueryHandler {
|
||||
checkDryRun(p);
|
||||
|
||||
Volume vol = service.createVolume(region, availabilityZone, volumeType, size,
|
||||
encrypted, kmsKeyId, iops, throughput, snapshotId, volumeTags);
|
||||
encrypted, kmsKeyId, iops, throughput, snapshotId, volumeTags, p.getFirst("ClientToken"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("CreateVolumeResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
|
||||
@@ -6551,18 +6551,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
String token = clientToken != null && !clientToken.isBlank() ? clientToken : null;
|
||||
synchronized (attachmentTopologyLock(region)) {
|
||||
if (token != null) {
|
||||
for (EgressOnlyInternetGateway existing : egressOnlyInternetGateways.scan(
|
||||
k -> k.startsWith(region + "::"))) {
|
||||
if (token.equals(existing.getClientToken())) {
|
||||
if (!vpcId.equals(existing.getAttachments().get(0).getVpcId())
|
||||
|| !tagMap(tagList).equals(tagMap(existing.getCreationTags()))) {
|
||||
throw new AwsException("IdempotentParameterMismatch",
|
||||
"The client token '" + token + "' was already used with different parameters", 400);
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
Optional<EgressOnlyInternetGateway> replay = Ec2ClientTokens.replay(token,
|
||||
() -> egressOnlyInternetGateways.scan(k -> k.startsWith(region + "::")).stream(),
|
||||
EgressOnlyInternetGateway::getClientToken,
|
||||
first -> vpcId.equals(first.getAttachments().get(0).getVpcId())
|
||||
&& tagMap(tagList).equals(tagMap(first.getCreationTags())),
|
||||
"The client token '" + token + "' was already used with different parameters");
|
||||
if (replay.isPresent()) {
|
||||
return replay.get();
|
||||
}
|
||||
getRequiredVpc(region, vpcId);
|
||||
EgressOnlyInternetGateway eigw = new EgressOnlyInternetGateway();
|
||||
@@ -11643,19 +11639,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
String.valueOf(ephemeralStorage), endDateType, String.valueOf(endDate), instanceMatchCriteria,
|
||||
outpostArn, placementGroupArn, String.valueOf(startDate), String.valueOf(commitmentDuration),
|
||||
deliveryPreference);
|
||||
if (isSet(clientToken)) {
|
||||
for (CapacityReservation existing : capacityReservations.scan(k -> k.startsWith(region + "::"))) {
|
||||
if (clientToken.equals(existing.getClientToken()) && callerAccountId().equals(existing.getOwnerId())) {
|
||||
if (!parameters.equals(existing.getRequestParameters())
|
||||
|| !requestTags.equals(existing.getRequestTags())) {
|
||||
throw new AwsException("IdempotentParameterMismatch",
|
||||
"Parameters differ from the previous request with this ClientToken.", 400);
|
||||
}
|
||||
reconcileCapacityMembership(region);
|
||||
return new CapacityReservation(getRequiredCapacityReservation(region,
|
||||
existing.getCapacityReservationId()));
|
||||
}
|
||||
}
|
||||
Optional<CapacityReservation> replay = Ec2ClientTokens.replay(clientToken,
|
||||
() -> capacityReservations.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(existing -> callerAccountId().equals(existing.getOwnerId())),
|
||||
CapacityReservation::getClientToken,
|
||||
first -> parameters.equals(first.getRequestParameters())
|
||||
&& requestTags.equals(first.getRequestTags()),
|
||||
"Parameters differ from the previous request with this ClientToken.");
|
||||
if (replay.isPresent()) {
|
||||
reconcileCapacityMembership(region);
|
||||
return new CapacityReservation(getRequiredCapacityReservation(region,
|
||||
replay.get().getCapacityReservationId()));
|
||||
}
|
||||
Instant now = capacityReservationNow();
|
||||
validateCapacityReservationSchedule(startDate, commitmentDuration, deliveryPreference, endDate, now);
|
||||
@@ -13302,23 +13296,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
throw dryRunOperation();
|
||||
}
|
||||
String token = clientToken != null && !clientToken.isBlank() ? clientToken : null;
|
||||
if (token != null) {
|
||||
// Compared after defaults are applied, so a retry that omits a defaulted parameter the
|
||||
// first call also omitted still matches.
|
||||
Optional<InstanceConnectEndpoint> replay = instanceConnectEndpoints.scan(k -> k.startsWith(region + "::"))
|
||||
.stream().filter(existing -> token.equals(existing.getClientToken())).findFirst();
|
||||
if (replay.isPresent()) {
|
||||
InstanceConnectEndpoint first = replay.get();
|
||||
if (!subnetId.equals(first.getSubnetId())
|
||||
|| !new HashSet<>(groups).equals(new HashSet<>(first.getSecurityGroupIds()))
|
||||
|| !type.equals(first.getIpAddressType())
|
||||
|| Boolean.TRUE.equals(preserveClientIp) != first.isPreserveClientIp()
|
||||
|| !tagMap(tagList).equals(tagMap(first.getCreationTags()))) {
|
||||
throw new AwsException("IdempotentParameterMismatch",
|
||||
"The client token '" + token + "' was already used with different parameters", 400);
|
||||
}
|
||||
return withTags(first);
|
||||
}
|
||||
// Compared after defaults are applied, so a retry that omits a defaulted parameter the
|
||||
// first call also omitted still matches.
|
||||
Optional<InstanceConnectEndpoint> replay = Ec2ClientTokens.replay(token,
|
||||
() -> instanceConnectEndpoints.scan(k -> k.startsWith(region + "::")).stream(),
|
||||
InstanceConnectEndpoint::getClientToken,
|
||||
first -> subnetId.equals(first.getSubnetId())
|
||||
&& new HashSet<>(groups).equals(new HashSet<>(first.getSecurityGroupIds()))
|
||||
&& type.equals(first.getIpAddressType())
|
||||
&& Boolean.TRUE.equals(preserveClientIp) == first.isPreserveClientIp()
|
||||
&& tagMap(tagList).equals(tagMap(first.getCreationTags())),
|
||||
"The client token '" + token + "' was already used with different parameters");
|
||||
if (replay.isPresent()) {
|
||||
return withTags(replay.get());
|
||||
}
|
||||
|
||||
String id = "eice-" + randomHex(17);
|
||||
@@ -14955,20 +14945,60 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
public Volume createVolume(String region, String availabilityZone, String volumeType,
|
||||
int size, boolean encrypted, String kmsKeyId, int iops, Integer throughput,
|
||||
String snapshotId, List<Tag> volumeTags) {
|
||||
ensureDefaultResources(region);
|
||||
Volume vol = newVolume(region, availabilityZone, volumeType, size, encrypted, kmsKeyId, iops, throughput,
|
||||
snapshotId);
|
||||
String volumeId = vol.getVolumeId();
|
||||
if (volumeTags != null) {
|
||||
vol.setTags(new ArrayList<>(volumeTags));
|
||||
// Tags on create are tags like any other: DescribeTags lists them in this region.
|
||||
putTags(region, vol.getVolumeId(), new ArrayList<>(volumeTags));
|
||||
}
|
||||
volumes.put(key(region, volumeId), vol);
|
||||
if (volumeBlockDeviceManager != null) {
|
||||
volumeBlockDeviceManager.createVolume(volumeId, vol.getSize());
|
||||
}
|
||||
return vol;
|
||||
return createVolume(region, availabilityZone, volumeType, size, encrypted, kmsKeyId, iops, throughput,
|
||||
snapshotId, volumeTags, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* As above, honouring {@code clientToken}: a replay in the same Availability Zone returns the
|
||||
* volume the first call created, and the same token with another volume parameter or other
|
||||
* creation tags fails with IdempotentParameterMismatch. The EC2 idempotency guide exempts the
|
||||
* Availability Zone from that check, so the same token in another zone gets that zone's own volume.
|
||||
* Parameters are compared as requested, so a later ModifyVolume or CreateTags does not turn a
|
||||
* retry into a mismatch.
|
||||
*/
|
||||
public Volume createVolume(String region, String availabilityZone, String volumeType,
|
||||
int size, boolean encrypted, String kmsKeyId, int iops, Integer throughput,
|
||||
String snapshotId, List<Tag> volumeTags, String clientToken) {
|
||||
String token = isSet(clientToken) ? clientToken : null;
|
||||
// Held from the replay scan to the save, so two creates with one token see each other.
|
||||
return withResourceLock(volumeClientTokenLocks,
|
||||
token == null ? null : callerAccountId() + "::" + key(region, token), () -> {
|
||||
ensureDefaultResources(region);
|
||||
Volume vol = newVolume(region, availabilityZone, volumeType, size, encrypted, kmsKeyId, iops,
|
||||
throughput, snapshotId);
|
||||
List<String> parameters = Arrays.asList(volumeType, String.valueOf(size), String.valueOf(encrypted),
|
||||
kmsKeyId, String.valueOf(iops), String.valueOf(throughput), snapshotId);
|
||||
Map<String, String> requestTags = tagMap(volumeTags);
|
||||
// The zone's volume with this token, settled as a read would settle it, so the answer is
|
||||
// the same whether or not something read the volume since its instance terminated.
|
||||
Optional<Volume> replay = Ec2ClientTokens.replay(token,
|
||||
() -> volumes.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(existing -> vol.getAvailabilityZone().equals(existing.getAvailabilityZone())
|
||||
&& token.equals(existing.getClientToken()))
|
||||
.flatMap(existing -> settleEndedHolders(region, existing).stream()),
|
||||
Volume::getClientToken,
|
||||
first -> parameters.equals(first.getRequestParameters())
|
||||
&& requestTags.equals(first.getRequestTags()),
|
||||
"Parameters differ from the previous request with this ClientToken.");
|
||||
if (replay.isPresent()) {
|
||||
return replay.get();
|
||||
}
|
||||
vol.setClientToken(token);
|
||||
vol.setRequestParameters(parameters);
|
||||
vol.setRequestTags(requestTags);
|
||||
String volumeId = vol.getVolumeId();
|
||||
if (volumeTags != null) {
|
||||
vol.setTags(new ArrayList<>(volumeTags));
|
||||
// Tags on create are tags like any other: DescribeTags lists them in this region.
|
||||
putTags(region, vol.getVolumeId(), new ArrayList<>(volumeTags));
|
||||
}
|
||||
volumes.put(key(region, volumeId), vol);
|
||||
if (volumeBlockDeviceManager != null) {
|
||||
volumeBlockDeviceManager.createVolume(volumeId, vol.getSize());
|
||||
}
|
||||
return vol;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -15070,6 +15100,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
|
||||
private final ConcurrentHashMap<String, RefCountedLock> volumeLocks = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, RefCountedLock> volumeClientTokenLocks = new ConcurrentHashMap<>();
|
||||
private final Set<VolumeDevice> pendingVolumeAttachments = ConcurrentHashMap.newKeySet();
|
||||
|
||||
private record VolumeDevice(String accountId, String region, String instanceId, String device) {}
|
||||
|
||||
@@ -5,7 +5,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -26,6 +28,11 @@ public class Volume {
|
||||
private String region;
|
||||
private List<Tag> tags = new ArrayList<>();
|
||||
private List<VolumeAttachment> attachments = new ArrayList<>();
|
||||
// The CreateVolume ClientToken and the request it came with, kept so a retry can be told
|
||||
// apart from another request that reuses the token.
|
||||
private String clientToken;
|
||||
private List<String> requestParameters = new ArrayList<>();
|
||||
private Map<String, String> requestTags = new LinkedHashMap<>();
|
||||
|
||||
public Volume() {}
|
||||
|
||||
@@ -73,4 +80,13 @@ public class Volume {
|
||||
|
||||
public List<VolumeAttachment> getAttachments() { return attachments; }
|
||||
public void setAttachments(List<VolumeAttachment> attachments) { this.attachments = attachments; }
|
||||
|
||||
public String getClientToken() { return clientToken; }
|
||||
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
|
||||
|
||||
public List<String> getRequestParameters() { return requestParameters; }
|
||||
public void setRequestParameters(List<String> value) { requestParameters = new ArrayList<>(value); }
|
||||
|
||||
public Map<String, String> getRequestTags() { return requestTags; }
|
||||
public void setRequestTags(Map<String, String> requestTags) { this.requestTags = requestTags; }
|
||||
}
|
||||
Reference in new issue
Block a user