mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -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; }
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.acm.AcmService;
|
||||
import io.floci.aws.services.ec2.model.ClientVpnEndpoint;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static io.floci.aws.testing.Ec2ServiceFixtures.ACCOUNT;
|
||||
import static io.floci.aws.testing.Ec2ServiceFixtures.mockModeService;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* CreateClientVpnEndpoint's ClientToken: a retry with the token returns the endpoint the first call
|
||||
* made, and a call with no token, or a blank one, makes an endpoint of its own, as the other EC2
|
||||
* creates that take a token do.
|
||||
*/
|
||||
class Ec2ClientVpnClientTokenTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private final Ec2ClientVpnService vpn = new Ec2ClientVpnService(
|
||||
AccountAwareStorageBackend.<ClientVpnEndpoint>inMemory(ACCOUNT), mockModeService(), mock(AcmService.class));
|
||||
|
||||
@Test
|
||||
void aRetryWithTheSameTokenReturnsTheFirstEndpoint() {
|
||||
String first = createEndpoint("4f9a8d0c2b7e41f3");
|
||||
|
||||
assertEquals(first, createEndpoint("4f9a8d0c2b7e41f3"));
|
||||
assertEquals(List.of(first), endpointIds());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = " ")
|
||||
void aCreateWithoutATokenMakesAnEndpointOfItsOwn(String token) {
|
||||
String first = createEndpoint(token);
|
||||
String second = createEndpoint(token);
|
||||
|
||||
assertNotEquals(first, second);
|
||||
assertEquals(Stream.of(first, second).sorted().toList(), endpointIds());
|
||||
}
|
||||
|
||||
/** A certificate-authenticated endpoint with every optional member left to AWS's default. */
|
||||
private String createEndpoint(String clientToken) {
|
||||
ClientVpnEndpoint.Authentication certificate = new ClientVpnEndpoint.Authentication();
|
||||
certificate.setType("certificate-authentication");
|
||||
certificate.setClientRootCertificateChain("arn:aws:acm:us-east-1:000000000000:certificate/client-root");
|
||||
Ec2ClientVpnService.EndpointRequest request = new Ec2ClientVpnService.EndpointRequest("172.16.0.0/22",
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/server", List.of(certificate), false,
|
||||
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
|
||||
clientToken);
|
||||
return vpn.createEndpoint(REGION, request, List.of()).getClientVpnEndpointId();
|
||||
}
|
||||
|
||||
private List<String> endpointIds() {
|
||||
return vpn.describeEndpoints(REGION, List.of()).stream()
|
||||
.map(ClientVpnEndpoint::getClientVpnEndpointId).sorted().toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.services.ec2.model.Volume;
|
||||
import io.floci.aws.testing.InMemoryStorageFactory;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.ok;
|
||||
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.queryHandler;
|
||||
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.send;
|
||||
import static io.floci.aws.testing.Ec2ServiceFixtures.ACCOUNT;
|
||||
import static io.floci.aws.testing.Ec2ServiceFixtures.mockModeService;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* CreateVolume's ClientToken, sent through the Query handler to a real service, as the EBS CSI
|
||||
* driver sends it when it retries. A retry with the token and the request the first call made
|
||||
* returns that call's volume and creates no other; the token with another parameter or other
|
||||
* creation tags fails with IdempotentParameterMismatch; without a token every call creates a volume.
|
||||
*/
|
||||
class Ec2CreateVolumeClientTokenTest {
|
||||
|
||||
private static final String TOKEN = "4f9a8d0c2b7e41f3a6c5d8e9b0a1c2d3";
|
||||
private static final String MISMATCH = "Parameters differ from the previous request with this ClientToken.";
|
||||
|
||||
private final Ec2QueryHandler handler = queryHandler(mockModeService());
|
||||
|
||||
@Test
|
||||
void aRetryWithTheSameTokenAndParametersReturnsTheFirstVolume() {
|
||||
String first = volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1"));
|
||||
|
||||
assertEquals(first, volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1")));
|
||||
assertEquals(List.of(first), describedVolumeIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSameTokenWithAnotherSizeOrOtherTagsIsAMismatch() {
|
||||
String first = volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1"));
|
||||
|
||||
assertMismatch(createVolume(TOKEN, "us-east-1a", "11", "pvc-1"));
|
||||
assertMismatch(createVolume(TOKEN, "us-east-1a", "10", "pvc-2"));
|
||||
assertEquals(List.of(first), describedVolumeIds());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutATokenEveryCallCreatesAVolume() {
|
||||
String first = volumeId(createVolume(null, "us-east-1a", "10", "pvc-1"));
|
||||
String second = volumeId(createVolume(null, "us-east-1a", "10", "pvc-1"));
|
||||
|
||||
assertNotEquals(first, second);
|
||||
assertEquals(Stream.of(first, second).sorted().toList(), describedVolumeIds());
|
||||
}
|
||||
|
||||
/** The guide exempts the Availability Zone from the mismatch check: the token is zonal. */
|
||||
@Test
|
||||
void theSameTokenInAnotherZoneCreatesThatZonesVolume() {
|
||||
String first = volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1"));
|
||||
String other = volumeId(createVolume(TOKEN, "us-east-1b", "10", "pvc-1"));
|
||||
|
||||
assertNotEquals(first, other);
|
||||
assertEquals(Stream.of(first, other).sorted().toList(), describedVolumeIds());
|
||||
assertEquals(other, volumeId(createVolume(TOKEN, "us-east-1b", "10", "pvc-1")));
|
||||
}
|
||||
|
||||
/** The retry is compared with the first request, not with the volume as it is now. */
|
||||
@Test
|
||||
void aRetryStillMatchesAfterTheVolumeWasModifiedAndTagged() {
|
||||
String first = volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1"));
|
||||
ok(handler, "ModifyVolume", "VolumeId", first, "Size", "20");
|
||||
ok(handler, "CreateTags", "ResourceId.1", first, "Tag.1.Key", "Team", "Tag.1.Value", "storage");
|
||||
|
||||
assertEquals(first, volumeId(createVolume(TOKEN, "us-east-1a", "10", "pvc-1")));
|
||||
assertEquals(List.of(first), describedVolumeIds());
|
||||
}
|
||||
|
||||
/** Creates that race with one token are held apart by the token's lock, so one volume is made. */
|
||||
@Test
|
||||
void concurrentCreatesWithOneClientTokenMakeOneVolume() throws Exception {
|
||||
ExecutorService pool = Executors.newFixedThreadPool(8);
|
||||
try {
|
||||
for (int round = 0; round < 50; round++) {
|
||||
Ec2QueryHandler racing = queryHandler(mockModeService());
|
||||
CountDownLatch go = new CountDownLatch(1);
|
||||
List<Future<String>> ids = new ArrayList<>();
|
||||
for (int i = 0; i < 8; i++) {
|
||||
ids.add(pool.submit(() -> {
|
||||
go.await();
|
||||
return volumeId(createVolume(racing, TOKEN, "us-east-1a", "10", "pvc-1"));
|
||||
}));
|
||||
}
|
||||
go.countDown();
|
||||
Set<String> distinct = ConcurrentHashMap.newKeySet();
|
||||
for (Future<String> id : ids) {
|
||||
distinct.add(id.get());
|
||||
}
|
||||
assertEquals(1, distinct.size(), "round " + round + ": " + distinct);
|
||||
assertEquals(List.copyOf(distinct), XmlParser.extractAll(ok(racing, "DescribeVolumes"), "volumeId"));
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
/** Without a token there is nothing to replay, so a create does not read the volume store. */
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = " ")
|
||||
void aCreateWithoutATokenDoesNotScanTheVolumes(String token) {
|
||||
AccountAwareStorageBackend<Volume> volumes = spy(AccountAwareStorageBackend.<Volume>inMemory(ACCOUNT));
|
||||
Ec2QueryHandler tokenless = queryHandler(mockModeService(new InMemoryStorageFactory(ACCOUNT)
|
||||
.withStore("ec2-volumes.json", volumes)));
|
||||
clearInvocations(volumes);
|
||||
|
||||
volumeId(createVolume(tokenless, token, "us-east-1a", "10", "pvc-1"));
|
||||
|
||||
verify(volumes, never()).scan(any());
|
||||
}
|
||||
|
||||
private Response createVolume(String token, String zone, String size, String name) {
|
||||
return createVolume(handler, token, zone, size, name);
|
||||
}
|
||||
|
||||
/** A gp3 CreateVolume tagged with {@code Name}, as the CSI driver sends it; a null token is left out. */
|
||||
private static Response createVolume(Ec2QueryHandler handler, String token, String zone, String size,
|
||||
String name) {
|
||||
List<String> params = new ArrayList<>(List.of("AvailabilityZone", zone, "Size", size, "VolumeType", "gp3",
|
||||
"TagSpecification.1.ResourceType", "volume",
|
||||
"TagSpecification.1.Tag.1.Key", "Name", "TagSpecification.1.Tag.1.Value", name));
|
||||
if (token != null) {
|
||||
params.addAll(List.of("ClientToken", token));
|
||||
}
|
||||
return send(handler, "CreateVolume", params.toArray(String[]::new));
|
||||
}
|
||||
|
||||
private List<String> describedVolumeIds() {
|
||||
return XmlParser.extractAll(ok(handler, "DescribeVolumes"), "volumeId").stream().sorted().toList();
|
||||
}
|
||||
|
||||
private static String volumeId(Response response) {
|
||||
String body = String.valueOf(response.getEntity());
|
||||
assertEquals(200, response.getStatus(), body);
|
||||
return XmlParser.extractFirst(body, "volumeId", null);
|
||||
}
|
||||
|
||||
private static void assertMismatch(Response response) {
|
||||
String body = String.valueOf(response.getEntity());
|
||||
assertEquals(400, response.getStatus(), body);
|
||||
assertEquals("IdempotentParameterMismatch", XmlParser.extractFirst(body, "Code", null), body);
|
||||
assertEquals(MISMATCH, XmlParser.extractFirst(body, "Message", null), body);
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,10 @@ package io.floci.aws.services.ec2;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import io.floci.aws.testing.Ec2QueryHandlerFixtures;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -24,6 +21,7 @@ import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.queryHandler;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -60,9 +58,7 @@ class Ec2RepeatedFilterNamesTest {
|
||||
Ec2ImageCatalog imageCatalog = new Ec2ImageCatalog();
|
||||
service = new Ec2Service(config, mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class),
|
||||
new AmiImageResolver(imageCatalog), imageCatalog, new Ec2InstanceTypeCatalog(), new MemoryFactory());
|
||||
handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class), mock(FlowLogService.class),
|
||||
mock(Ec2EbsEncryptionService.class), mock(Ec2BlockPublicAccessService.class),
|
||||
mock(Ec2IpamService.class), new RegionResolver(REGION, "000000000000"));
|
||||
handler = queryHandler(service);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -704,14 +700,7 @@ class Ec2RepeatedFilterNamesTest {
|
||||
}
|
||||
|
||||
private String ok(String action, String... params) {
|
||||
MultivaluedMap<String, String> form = new MultivaluedHashMap<>();
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
form.add(params[i], params[i + 1]);
|
||||
}
|
||||
Response response = handler.handle(action, form, REGION);
|
||||
String body = String.valueOf(response.getEntity());
|
||||
assertEquals(200, response.getStatus(), action + ": " + body);
|
||||
return body;
|
||||
return Ec2QueryHandlerFixtures.ok(handler, action, params);
|
||||
}
|
||||
|
||||
private String first(String xml, String element) {
|
||||
|
||||
@@ -3,7 +3,6 @@ package io.floci.aws.services.ec2;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import io.floci.aws.core.storage.PersistentStorage;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
@@ -35,8 +34,6 @@ import io.floci.aws.services.ec2.model.Volume;
|
||||
import io.floci.aws.services.ec2.model.Vpc;
|
||||
import io.floci.aws.services.ec2.model.VpcEndpoint;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
@@ -49,6 +46,9 @@ import java.util.Map;
|
||||
|
||||
import static io.floci.aws.services.ec2.Ec2KeyPairFixtures.ED25519_FINGERPRINT;
|
||||
import static io.floci.aws.services.ec2.Ec2KeyPairFixtures.ED25519_KEY;
|
||||
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.ok;
|
||||
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.queryHandler;
|
||||
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.send;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
@@ -765,10 +765,7 @@ class Ec2ServicePersistenceTest {
|
||||
Map.of("key-type", List.of("ed25519"), "tag:Team", List.of("blue"))).stream()
|
||||
.map(KeyPair::getKeyName).toList());
|
||||
|
||||
String xml = (String) new Ec2QueryHandler(restarted, mock(EmulatorConfig.class), mock(FlowLogService.class),
|
||||
mock(Ec2EbsEncryptionService.class), mock(Ec2BlockPublicAccessService.class),
|
||||
mock(Ec2IpamService.class), new RegionResolver(REGION, "000000000000"))
|
||||
.handle("DescribeKeyPairs", new MultivaluedHashMap<>(), REGION).getEntity();
|
||||
String xml = (String) send(queryHandler(restarted), "DescribeKeyPairs").getEntity();
|
||||
assertTrue(xml.contains("<keyType>rsa</keyType>"), xml);
|
||||
assertTrue(xml.contains("<keyType>ed25519</keyType>"), xml);
|
||||
assertFalse(xml.contains("<createTime>"), xml);
|
||||
@@ -787,6 +784,20 @@ class Ec2ServicePersistenceTest {
|
||||
assertEquals(List.of(keyArn), XmlParser.extractAll(described, "kmsKeyId"), described);
|
||||
}
|
||||
|
||||
/** The token and the request it came with are stored, so a retry after a restart still matches. */
|
||||
@Test
|
||||
void volumeClientTokenSurvivesRestart(@TempDir Path dir) {
|
||||
String[] request = {"AvailabilityZone", "us-east-1a", "Size", "1", "ClientToken", "restart-token",
|
||||
"TagSpecification.1.ResourceType", "volume",
|
||||
"TagSpecification.1.Tag.1.Key", "Name", "TagSpecification.1.Tag.1.Value", "pvc-1"};
|
||||
String volumeId = XmlParser.extractFirst(query(newService(dir), "CreateVolume", request), "volumeId", null);
|
||||
|
||||
String retried = query(newService(dir), "CreateVolume", request);
|
||||
|
||||
assertEquals(volumeId, XmlParser.extractFirst(retried, "volumeId", null), retried);
|
||||
assertEquals(List.of(volumeId), XmlParser.extractAll(query(newService(dir), "DescribeVolumes"), "volumeId"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A volume store as Floci wrote it before a volume kept its KMS key: an encrypted volume
|
||||
* attached to an instance and an unencrypted one. Both load as they were stored, and
|
||||
@@ -867,18 +878,7 @@ class Ec2ServicePersistenceTest {
|
||||
}
|
||||
|
||||
private static String query(Ec2Service service, String action, String... params) {
|
||||
MultivaluedHashMap<String, String> form = new MultivaluedHashMap<>();
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
form.add(params[i], params[i + 1]);
|
||||
}
|
||||
Response response = new Ec2QueryHandler(service, mock(EmulatorConfig.class),
|
||||
mock(FlowLogService.class), mock(Ec2EbsEncryptionService.class),
|
||||
mock(Ec2BlockPublicAccessService.class), mock(Ec2IpamService.class),
|
||||
new RegionResolver(REGION, "000000000000"))
|
||||
.handle(action, form, REGION);
|
||||
String body = String.valueOf(response.getEntity());
|
||||
assertEquals(200, response.getStatus(), action + ": " + body);
|
||||
return body;
|
||||
return ok(queryHandler(service), action, params);
|
||||
}
|
||||
|
||||
private static String jsonString(String value) {
|
||||
|
||||
@@ -2,14 +2,11 @@ package io.floci.aws.services.ec2;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.XmlParser;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import io.floci.aws.testing.Ec2QueryHandlerFixtures;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -19,6 +16,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static io.floci.aws.testing.Ec2QueryHandlerFixtures.queryHandler;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -55,9 +53,7 @@ class Ec2VolumeKmsKeyIdTest {
|
||||
Ec2Service service = new Ec2Service(config, mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), new AmiImageResolver(imageCatalog), imageCatalog,
|
||||
new Ec2InstanceTypeCatalog(), new MemoryFactory());
|
||||
handler = new Ec2QueryHandler(service, mock(EmulatorConfig.class), mock(FlowLogService.class),
|
||||
mock(Ec2EbsEncryptionService.class), mock(Ec2BlockPublicAccessService.class),
|
||||
mock(Ec2IpamService.class), new RegionResolver(REGION, "000000000000"));
|
||||
handler = queryHandler(service);
|
||||
}
|
||||
|
||||
/** Each form CreateVolume documents for KmsKeyId is kept as the caller gave it. */
|
||||
@@ -126,14 +122,7 @@ class Ec2VolumeKmsKeyIdTest {
|
||||
}
|
||||
|
||||
private String ok(String action, String... params) {
|
||||
MultivaluedMap<String, String> form = new MultivaluedHashMap<>();
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
form.add(params[i], params[i + 1]);
|
||||
}
|
||||
Response response = handler.handle(action, form, REGION);
|
||||
String body = String.valueOf(response.getEntity());
|
||||
assertEquals(200, response.getStatus(), action + ": " + body);
|
||||
return body;
|
||||
return Ec2QueryHandlerFixtures.ok(handler, action, params);
|
||||
}
|
||||
|
||||
private static String first(String xml, String element) {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.services.ec2.Ec2BlockPublicAccessService;
|
||||
import io.floci.aws.services.ec2.Ec2EbsEncryptionService;
|
||||
import io.floci.aws.services.ec2.Ec2IpamService;
|
||||
import io.floci.aws.services.ec2.Ec2QueryHandler;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.FlowLogService;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* EC2 Query requests sent straight to an {@link Ec2QueryHandler} in {@link #REGION}, for unit tests
|
||||
* that check what a call answers without HTTP. The handler's other services are mocks.
|
||||
*/
|
||||
public final class Ec2QueryHandlerFixtures {
|
||||
|
||||
public static final String REGION = "us-east-1";
|
||||
|
||||
private Ec2QueryHandlerFixtures() {
|
||||
}
|
||||
|
||||
/** A handler over {@code service} for {@link #REGION} and {@link Ec2ServiceFixtures#ACCOUNT}. */
|
||||
public static Ec2QueryHandler queryHandler(Ec2Service service) {
|
||||
return new Ec2QueryHandler(service, mock(EmulatorConfig.class), mock(FlowLogService.class),
|
||||
mock(Ec2EbsEncryptionService.class), mock(Ec2BlockPublicAccessService.class),
|
||||
mock(Ec2IpamService.class), new RegionResolver(REGION, Ec2ServiceFixtures.ACCOUNT));
|
||||
}
|
||||
|
||||
/** Sends {@code action} with {@code params}, given as name and value pairs, and returns the answer. */
|
||||
public static Response send(Ec2QueryHandler handler, String action, String... params) {
|
||||
MultivaluedMap<String, String> form = new MultivaluedHashMap<>();
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
form.add(params[i], params[i + 1]);
|
||||
}
|
||||
return handler.handle(action, form, REGION);
|
||||
}
|
||||
|
||||
/** As {@link #send}, asserting that the call succeeds, and returns the response body. */
|
||||
public static String ok(Ec2QueryHandler handler, String action, String... params) {
|
||||
Response response = send(handler, action, params);
|
||||
String body = String.valueOf(response.getEntity());
|
||||
assertEquals(200, response.getStatus(), action + ": " + body);
|
||||
return body;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user