mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(kinesisanalytics): isolate applications by account and region (#3760)
* fix(kinesisanalytics): scope applications by account and region * fix(kinesisanalytics): migrate legacy application lookups Use the account-aware synchronized migration path for regional application lookups and listing. Reject foreign-account resource ARNs and cover legacy tagging migration.
This commit is contained in:
1 parent
2bf92a9beb
commit
76c103fd8c
7 files changed
+399
-96
No files matched your search
@@ -32,6 +32,10 @@ state backed by a live Flink job on Floci's Docker network.
|
||||
|
||||
## How it works
|
||||
|
||||
Application names are scoped by the signing region. The same name can exist in multiple regions,
|
||||
and list, describe, update, start, stop, snapshot, and delete operations only access the requested
|
||||
region. Application ARNs use that same request region.
|
||||
|
||||
1. **CreateApplication**: registers the application in the `READY` state and stores its
|
||||
`ApplicationConfiguration` (the S3 location of the Flink JAR and the parallelism). No container is
|
||||
started yet — this mirrors AWS, where a freshly created application is not running.
|
||||
|
||||
+36
-36
@@ -36,21 +36,21 @@ public class KinesisAnalyticsV2JsonHandler {
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
return switch (action) {
|
||||
case "CreateApplication" -> handleCreateApplication(request);
|
||||
case "CreateApplicationPresignedUrl" -> handleCreateApplicationPresignedUrl(request);
|
||||
case "DescribeApplication" -> handleDescribeApplication(request);
|
||||
case "ListApplications" -> handleListApplications(request);
|
||||
case "StartApplication" -> handleStartApplication(request);
|
||||
case "StopApplication" -> handleStopApplication(request);
|
||||
case "UpdateApplication" -> handleUpdateApplication(request);
|
||||
case "DeleteApplication" -> handleDeleteApplication(request);
|
||||
case "CreateApplication" -> handleCreateApplication(request, region);
|
||||
case "CreateApplicationPresignedUrl" -> handleCreateApplicationPresignedUrl(request, region);
|
||||
case "DescribeApplication" -> handleDescribeApplication(request, region);
|
||||
case "ListApplications" -> handleListApplications(request, region);
|
||||
case "StartApplication" -> handleStartApplication(request, region);
|
||||
case "StopApplication" -> handleStopApplication(request, region);
|
||||
case "UpdateApplication" -> handleUpdateApplication(request, region);
|
||||
case "DeleteApplication" -> handleDeleteApplication(request, region);
|
||||
case "TagResource" -> handleTagResource(request);
|
||||
case "UntagResource" -> handleUntagResource(request);
|
||||
case "ListTagsForResource" -> handleListTagsForResource(request);
|
||||
case "CreateApplicationSnapshot" -> handleCreateApplicationSnapshot(request);
|
||||
case "DescribeApplicationSnapshot" -> handleDescribeApplicationSnapshot(request);
|
||||
case "ListApplicationSnapshots" -> handleListApplicationSnapshots(request);
|
||||
case "DeleteApplicationSnapshot" -> handleDeleteApplicationSnapshot(request);
|
||||
case "CreateApplicationSnapshot" -> handleCreateApplicationSnapshot(request, region);
|
||||
case "DescribeApplicationSnapshot" -> handleDescribeApplicationSnapshot(request, region);
|
||||
case "ListApplicationSnapshots" -> handleListApplicationSnapshots(request, region);
|
||||
case "DeleteApplicationSnapshot" -> handleDeleteApplicationSnapshot(request, region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported."))
|
||||
@@ -58,7 +58,7 @@ public class KinesisAnalyticsV2JsonHandler {
|
||||
};
|
||||
}
|
||||
|
||||
private Response handleCreateApplication(JsonNode request) {
|
||||
private Response handleCreateApplication(JsonNode request, String region) {
|
||||
String applicationName = request.path("ApplicationName").asText(null);
|
||||
String runtimeEnvironment = request.path("RuntimeEnvironment").asText(null);
|
||||
String serviceExecutionRole = request.path("ServiceExecutionRole").asText(null);
|
||||
@@ -83,17 +83,17 @@ public class KinesisAnalyticsV2JsonHandler {
|
||||
FlinkApplication app = service.createApplication(applicationName, runtimeEnvironment,
|
||||
serviceExecutionRole, applicationDescription, applicationMode,
|
||||
codeBucket, codeKey, codeVersion, parallelism, parseTags(request.path("Tags")),
|
||||
environmentProperties, snapshotsEnabled);
|
||||
environmentProperties, snapshotsEnabled, region);
|
||||
return applicationDetailResponse(app);
|
||||
}
|
||||
|
||||
private Response handleCreateApplicationPresignedUrl(JsonNode request) {
|
||||
private Response handleCreateApplicationPresignedUrl(JsonNode request, String region) {
|
||||
String applicationName = request.path("ApplicationName").asText(null);
|
||||
String urlType = request.path("UrlType").asText(null);
|
||||
Long sessionExpirationDurationInSeconds = request.hasNonNull("SessionExpirationDurationInSeconds")
|
||||
? request.path("SessionExpirationDurationInSeconds").asLong() : null;
|
||||
String url = service.createApplicationPresignedUrl(applicationName, urlType,
|
||||
sessionExpirationDurationInSeconds);
|
||||
sessionExpirationDurationInSeconds, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("AuthorizedUrl", url);
|
||||
return Response.ok(response).build();
|
||||
@@ -108,15 +108,15 @@ public class KinesisAnalyticsV2JsonHandler {
|
||||
return bucketArn.startsWith(prefix) ? bucketArn.substring(prefix.length()) : bucketArn;
|
||||
}
|
||||
|
||||
private Response handleDescribeApplication(JsonNode request) {
|
||||
private Response handleDescribeApplication(JsonNode request, String region) {
|
||||
String applicationName = request.path("ApplicationName").asText(null);
|
||||
return applicationDetailResponse(service.describeApplication(applicationName));
|
||||
return applicationDetailResponse(service.describeApplication(applicationName, region));
|
||||
}
|
||||
|
||||
private Response handleListApplications(JsonNode request) {
|
||||
private Response handleListApplications(JsonNode request, String region) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode summaries = response.putArray("ApplicationSummaries");
|
||||
for (FlinkApplication app : service.listApplications()) {
|
||||
for (FlinkApplication app : service.listApplications(region)) {
|
||||
ObjectNode summary = summaries.addObject();
|
||||
summary.put("ApplicationName", app.getApplicationName());
|
||||
summary.put("ApplicationARN", app.getApplicationArn());
|
||||
@@ -130,21 +130,21 @@ public class KinesisAnalyticsV2JsonHandler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleStartApplication(JsonNode request) {
|
||||
private Response handleStartApplication(JsonNode request, String region) {
|
||||
String applicationName = request.path("ApplicationName").asText(null);
|
||||
service.startApplication(applicationName);
|
||||
service.startApplication(applicationName, region);
|
||||
// AWS StartApplication returns an empty body.
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleStopApplication(JsonNode request) {
|
||||
private Response handleStopApplication(JsonNode request, String region) {
|
||||
String applicationName = request.path("ApplicationName").asText(null);
|
||||
service.stopApplication(applicationName);
|
||||
service.stopApplication(applicationName, region);
|
||||
// AWS StopApplication returns an empty body.
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateApplication(JsonNode request) {
|
||||
private Response handleUpdateApplication(JsonNode request, String region) {
|
||||
String applicationName = request.path("ApplicationName").asText(null);
|
||||
// CurrentApplicationVersionId gates the update (optimistic concurrency); the service rejects a
|
||||
// stale or missing value.
|
||||
@@ -171,55 +171,55 @@ public class KinesisAnalyticsV2JsonHandler {
|
||||
? null : snapshotsEnabledUpdate.asBoolean();
|
||||
|
||||
return applicationDetailResponse(service.updateApplication(applicationName, currentVersionId,
|
||||
serviceExecutionRole, codeBucket, codeKey, codeVersion, parallelism, snapshotsEnabled));
|
||||
serviceExecutionRole, codeBucket, codeKey, codeVersion, parallelism, snapshotsEnabled, region));
|
||||
}
|
||||
|
||||
private Response handleDeleteApplication(JsonNode request) {
|
||||
private Response handleDeleteApplication(JsonNode request, String region) {
|
||||
String applicationName = request.path("ApplicationName").asText(null);
|
||||
// CreateTimestamp is epoch seconds on the wire (possibly fractional); the service validates it
|
||||
// against the stored value.
|
||||
Instant createTimestamp = request.hasNonNull("CreateTimestamp")
|
||||
? Instant.ofEpochMilli(Math.round(request.path("CreateTimestamp").asDouble() * 1000))
|
||||
: null;
|
||||
service.deleteApplication(applicationName, createTimestamp);
|
||||
service.deleteApplication(applicationName, createTimestamp, region);
|
||||
// AWS DeleteApplication returns an empty body.
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleCreateApplicationSnapshot(JsonNode request) {
|
||||
private Response handleCreateApplicationSnapshot(JsonNode request, String region) {
|
||||
String applicationName = request.path("ApplicationName").asText(null);
|
||||
String snapshotName = request.path("SnapshotName").asText(null);
|
||||
service.createApplicationSnapshot(applicationName, snapshotName);
|
||||
service.createApplicationSnapshot(applicationName, snapshotName, region);
|
||||
// AWS CreateApplicationSnapshot returns an empty body.
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeApplicationSnapshot(JsonNode request) {
|
||||
private Response handleDescribeApplicationSnapshot(JsonNode request, String region) {
|
||||
String applicationName = request.path("ApplicationName").asText(null);
|
||||
String snapshotName = request.path("SnapshotName").asText(null);
|
||||
Snapshot snapshot = service.describeApplicationSnapshot(applicationName, snapshotName);
|
||||
Snapshot snapshot = service.describeApplicationSnapshot(applicationName, snapshotName, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("SnapshotDetails", snapshotDetailNode(snapshot));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleListApplicationSnapshots(JsonNode request) {
|
||||
private Response handleListApplicationSnapshots(JsonNode request, String region) {
|
||||
String applicationName = request.path("ApplicationName").asText(null);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode summaries = response.putArray("SnapshotSummaries");
|
||||
for (Snapshot snapshot : service.listApplicationSnapshots(applicationName)) {
|
||||
for (Snapshot snapshot : service.listApplicationSnapshots(applicationName, region)) {
|
||||
summaries.add(snapshotDetailNode(snapshot));
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteApplicationSnapshot(JsonNode request) {
|
||||
private Response handleDeleteApplicationSnapshot(JsonNode request, String region) {
|
||||
String applicationName = request.path("ApplicationName").asText(null);
|
||||
String snapshotName = request.path("SnapshotName").asText(null);
|
||||
Instant snapshotCreationTimestamp = request.hasNonNull("SnapshotCreationTimestamp")
|
||||
? Instant.ofEpochMilli(Math.round(request.path("SnapshotCreationTimestamp").asDouble() * 1000))
|
||||
: null;
|
||||
service.deleteApplicationSnapshot(applicationName, snapshotName, snapshotCreationTimestamp);
|
||||
service.deleteApplicationSnapshot(applicationName, snapshotName, snapshotCreationTimestamp, region);
|
||||
// AWS DeleteApplicationSnapshot returns an empty body.
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
+182
-22
@@ -20,10 +20,12 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -138,6 +140,18 @@ public class KinesisAnalyticsV2Service {
|
||||
Map<String, String> tags,
|
||||
Map<String, Map<String, String>> environmentProperties,
|
||||
Boolean snapshotsEnabled) {
|
||||
return createApplication(applicationName, runtimeEnvironment, serviceExecutionRole,
|
||||
applicationDescription, applicationMode, codeS3Bucket, codeS3Key, codeS3ObjectVersion,
|
||||
parallelism, tags, environmentProperties, snapshotsEnabled, config.defaultRegion());
|
||||
}
|
||||
|
||||
public FlinkApplication createApplication(String applicationName, String runtimeEnvironment,
|
||||
String serviceExecutionRole, String applicationDescription,
|
||||
String applicationMode, String codeS3Bucket, String codeS3Key,
|
||||
String codeS3ObjectVersion, int parallelism,
|
||||
Map<String, String> tags,
|
||||
Map<String, Map<String, String>> environmentProperties,
|
||||
Boolean snapshotsEnabled, String region) {
|
||||
if (applicationName == null || applicationName.isBlank()) {
|
||||
throw new AwsException("InvalidArgumentException", "ApplicationName is required", 400);
|
||||
}
|
||||
@@ -155,7 +169,7 @@ public class KinesisAnalyticsV2Service {
|
||||
if (serviceExecutionRole == null || serviceExecutionRole.isBlank()) {
|
||||
throw new AwsException("InvalidArgumentException", "ServiceExecutionRole is required", 400);
|
||||
}
|
||||
if (storage.get(applicationName).isPresent()) {
|
||||
if (storage.get(applicationKey(region, applicationName)).isPresent()) {
|
||||
throw new AwsException("ResourceInUseException",
|
||||
"Application already exists: " + applicationName, 400);
|
||||
}
|
||||
@@ -165,7 +179,7 @@ public class KinesisAnalyticsV2Service {
|
||||
}
|
||||
|
||||
String accountId = regionResolver.getAccountId();
|
||||
String arn = AwsArnUtils.Arn.of("kinesisanalytics", config.defaultRegion(), accountId,
|
||||
String arn = AwsArnUtils.Arn.of("kinesisanalytics", region, accountId,
|
||||
"application/" + applicationName).toString();
|
||||
String mode = (applicationMode == null || applicationMode.isBlank()) ? "STREAMING" : applicationMode;
|
||||
|
||||
@@ -189,23 +203,49 @@ public class KinesisAnalyticsV2Service {
|
||||
app.setSnapshotsEnabled(snapshotsEnabled);
|
||||
}
|
||||
|
||||
storage.put(applicationName, app);
|
||||
putApplication(app);
|
||||
LOG.infov("Created Kinesis Analytics V2 application {0}", applicationName);
|
||||
return app;
|
||||
}
|
||||
|
||||
public FlinkApplication describeApplication(String applicationName) {
|
||||
return storage.get(applicationName)
|
||||
return describeApplication(applicationName, config.defaultRegion());
|
||||
}
|
||||
|
||||
public FlinkApplication describeApplication(String applicationName, String region) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
return getStoredApplication(accountId, region, applicationName)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Application not found: " + applicationName, 400));
|
||||
}
|
||||
|
||||
public List<FlinkApplication> listApplications() {
|
||||
return storage.scan(k -> true);
|
||||
return listApplications(config.defaultRegion());
|
||||
}
|
||||
|
||||
public List<FlinkApplication> listApplications(String region) {
|
||||
String prefix = region + "/";
|
||||
String accountId = regionResolver.getAccountId();
|
||||
if (storage instanceof AccountAwareStorageBackend<FlinkApplication> aware) {
|
||||
migrateLegacyApplications(aware, accountId, region);
|
||||
return aware.scanForAccount(accountId, key -> key.startsWith(prefix));
|
||||
}
|
||||
if (region.equals(config.defaultRegion())) {
|
||||
for (String key : new ArrayList<>(storage.keys())) {
|
||||
if (!key.contains("/")) {
|
||||
getStoredApplication(accountId, region, key);
|
||||
}
|
||||
}
|
||||
}
|
||||
return storage.scan(key -> key.startsWith(prefix));
|
||||
}
|
||||
|
||||
public FlinkApplication startApplication(String applicationName) {
|
||||
FlinkApplication app = describeApplication(applicationName);
|
||||
return startApplication(applicationName, config.defaultRegion());
|
||||
}
|
||||
|
||||
public FlinkApplication startApplication(String applicationName, String region) {
|
||||
FlinkApplication app = describeApplication(applicationName, region);
|
||||
// Defends state persisted by a floci build older than the ApplicationName check in
|
||||
// createApplication: applicationARN is baked as literal text into the CloudWatch-log-format
|
||||
// config FlinkContainerManager writes on startup, and a name outside AWS's charset (most
|
||||
@@ -260,7 +300,11 @@ public class KinesisAnalyticsV2Service {
|
||||
}
|
||||
|
||||
public FlinkApplication stopApplication(String applicationName) {
|
||||
FlinkApplication app = describeApplication(applicationName);
|
||||
return stopApplication(applicationName, config.defaultRegion());
|
||||
}
|
||||
|
||||
public FlinkApplication stopApplication(String applicationName, String region) {
|
||||
FlinkApplication app = describeApplication(applicationName, region);
|
||||
if (app.getApplicationStatus() != ApplicationStatus.RUNNING
|
||||
&& app.getApplicationStatus() != ApplicationStatus.STARTING) {
|
||||
throw new AwsException("ResourceInUseException",
|
||||
@@ -296,7 +340,16 @@ public class KinesisAnalyticsV2Service {
|
||||
String serviceExecutionRole, String codeS3Bucket,
|
||||
String codeS3Key, String codeS3ObjectVersion,
|
||||
Integer parallelism, Boolean snapshotsEnabled) {
|
||||
FlinkApplication app = describeApplication(applicationName);
|
||||
return updateApplication(applicationName, currentApplicationVersionId, serviceExecutionRole,
|
||||
codeS3Bucket, codeS3Key, codeS3ObjectVersion, parallelism, snapshotsEnabled,
|
||||
config.defaultRegion());
|
||||
}
|
||||
|
||||
public FlinkApplication updateApplication(String applicationName, Long currentApplicationVersionId,
|
||||
String serviceExecutionRole, String codeS3Bucket,
|
||||
String codeS3Key, String codeS3ObjectVersion,
|
||||
Integer parallelism, Boolean snapshotsEnabled, String region) {
|
||||
FlinkApplication app = describeApplication(applicationName, region);
|
||||
// AWS requires CurrentApplicationVersionId and rejects a stale value with
|
||||
// ConcurrentModificationException (optimistic concurrency on the application version).
|
||||
if (currentApplicationVersionId == null) {
|
||||
@@ -359,7 +412,11 @@ public class KinesisAnalyticsV2Service {
|
||||
}
|
||||
|
||||
public void deleteApplication(String applicationName, Instant createTimestamp) {
|
||||
FlinkApplication app = describeApplication(applicationName);
|
||||
deleteApplication(applicationName, createTimestamp, config.defaultRegion());
|
||||
}
|
||||
|
||||
public void deleteApplication(String applicationName, Instant createTimestamp, String region) {
|
||||
FlinkApplication app = describeApplication(applicationName, region);
|
||||
// AWS requires CreateTimestamp and rejects a value that does not match the stored one. The
|
||||
// wire value is epoch seconds, so compare at second granularity.
|
||||
if (createTimestamp == null) {
|
||||
@@ -385,7 +442,12 @@ public class KinesisAnalyticsV2Service {
|
||||
// volume must survive a stop/restart cycle so snapshots remain describable/listable.
|
||||
containerManager.removeSavepointsVolume(app);
|
||||
}
|
||||
storage.delete(applicationName);
|
||||
String key = applicationKey(region, applicationName);
|
||||
if (app.getAccountId() != null && storage instanceof AccountAwareStorageBackend<FlinkApplication> aware) {
|
||||
aware.deleteForAccount(app.getAccountId(), key);
|
||||
} else {
|
||||
storage.delete(key);
|
||||
}
|
||||
LOG.infov("Deleted Kinesis Analytics V2 application {0}", applicationName);
|
||||
}
|
||||
|
||||
@@ -418,7 +480,11 @@ public class KinesisAnalyticsV2Service {
|
||||
}
|
||||
|
||||
public Snapshot createApplicationSnapshot(String applicationName, String snapshotName) {
|
||||
FlinkApplication app = describeApplication(applicationName);
|
||||
return createApplicationSnapshot(applicationName, snapshotName, config.defaultRegion());
|
||||
}
|
||||
|
||||
public Snapshot createApplicationSnapshot(String applicationName, String snapshotName, String region) {
|
||||
FlinkApplication app = describeApplication(applicationName, region);
|
||||
if (snapshotName == null || snapshotName.isBlank()) {
|
||||
throw new AwsException("InvalidArgumentException", "SnapshotName is required", 400);
|
||||
}
|
||||
@@ -459,7 +525,11 @@ public class KinesisAnalyticsV2Service {
|
||||
}
|
||||
|
||||
public Snapshot describeApplicationSnapshot(String applicationName, String snapshotName) {
|
||||
FlinkApplication app = describeApplication(applicationName);
|
||||
return describeApplicationSnapshot(applicationName, snapshotName, config.defaultRegion());
|
||||
}
|
||||
|
||||
public Snapshot describeApplicationSnapshot(String applicationName, String snapshotName, String region) {
|
||||
FlinkApplication app = describeApplication(applicationName, region);
|
||||
Snapshot snapshot = app.getSnapshots().get(snapshotName);
|
||||
if (snapshot == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
@@ -469,12 +539,22 @@ public class KinesisAnalyticsV2Service {
|
||||
}
|
||||
|
||||
public List<Snapshot> listApplicationSnapshots(String applicationName) {
|
||||
return List.copyOf(describeApplication(applicationName).getSnapshots().values());
|
||||
return listApplicationSnapshots(applicationName, config.defaultRegion());
|
||||
}
|
||||
|
||||
public List<Snapshot> listApplicationSnapshots(String applicationName, String region) {
|
||||
return List.copyOf(describeApplication(applicationName, region).getSnapshots().values());
|
||||
}
|
||||
|
||||
public void deleteApplicationSnapshot(String applicationName, String snapshotName,
|
||||
Instant snapshotCreationTimestamp) {
|
||||
FlinkApplication app = describeApplication(applicationName);
|
||||
deleteApplicationSnapshot(applicationName, snapshotName, snapshotCreationTimestamp,
|
||||
config.defaultRegion());
|
||||
}
|
||||
|
||||
public void deleteApplicationSnapshot(String applicationName, String snapshotName,
|
||||
Instant snapshotCreationTimestamp, String region) {
|
||||
FlinkApplication app = describeApplication(applicationName, region);
|
||||
Snapshot snapshot = app.getSnapshots().get(snapshotName);
|
||||
if (snapshot == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
@@ -509,7 +589,13 @@ public class KinesisAnalyticsV2Service {
|
||||
*/
|
||||
public String createApplicationPresignedUrl(String applicationName, String urlType,
|
||||
Long sessionExpirationDurationInSeconds) {
|
||||
FlinkApplication app = describeApplication(applicationName);
|
||||
return createApplicationPresignedUrl(applicationName, urlType,
|
||||
sessionExpirationDurationInSeconds, config.defaultRegion());
|
||||
}
|
||||
|
||||
public String createApplicationPresignedUrl(String applicationName, String urlType,
|
||||
Long sessionExpirationDurationInSeconds, String region) {
|
||||
FlinkApplication app = describeApplication(applicationName, region);
|
||||
if (!"FLINK_DASHBOARD_URL".equals(urlType)) {
|
||||
throw new AwsException("InvalidArgumentException",
|
||||
"Unsupported UrlType: " + urlType + "; only FLINK_DASHBOARD_URL is supported", 400);
|
||||
@@ -532,13 +618,27 @@ public class KinesisAnalyticsV2Service {
|
||||
if (resourceArn == null || resourceArn.isBlank()) {
|
||||
throw new AwsException("InvalidArgumentException", "ResourceARN is required", 400);
|
||||
}
|
||||
// Resource format is "application/<name>"; application names never contain '/'.
|
||||
int slash = resourceArn.lastIndexOf('/');
|
||||
if (slash < 0 || slash == resourceArn.length() - 1) {
|
||||
AwsArnUtils.Arn arn;
|
||||
try {
|
||||
arn = AwsArnUtils.parse(resourceArn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidArgumentException", "Invalid resource ARN: " + resourceArn, 400);
|
||||
}
|
||||
String applicationName = resourceArn.substring(slash + 1);
|
||||
return storage.get(applicationName)
|
||||
String accountId = regionResolver.getAccountId();
|
||||
String resourcePrefix = "application/";
|
||||
if (!"kinesisanalytics".equals(arn.service())
|
||||
|| !arn.resource().startsWith(resourcePrefix)
|
||||
|| arn.resource().length() == resourcePrefix.length()
|
||||
|| arn.resource().substring(resourcePrefix.length()).contains("/")) {
|
||||
throw new AwsException("InvalidArgumentException", "Invalid resource ARN: " + resourceArn, 400);
|
||||
}
|
||||
if (!accountId.equals(arn.accountId())) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"No application found for ARN: " + resourceArn, 400);
|
||||
}
|
||||
String applicationName = arn.resource().substring(resourcePrefix.length());
|
||||
String region = arn.region().isEmpty() ? config.defaultRegion() : arn.region();
|
||||
return getStoredApplication(accountId, region, applicationName)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"No application found for ARN: " + resourceArn, 400));
|
||||
}
|
||||
@@ -593,10 +693,70 @@ public class KinesisAnalyticsV2Service {
|
||||
}
|
||||
|
||||
private void putApplication(FlinkApplication app) {
|
||||
String region = AwsArnUtils.regionOrDefault(app.getApplicationArn(), config.defaultRegion());
|
||||
String key = applicationKey(region, app.getApplicationName());
|
||||
if (app.getAccountId() != null && storage instanceof AccountAwareStorageBackend<FlinkApplication> aware) {
|
||||
aware.putForAccount(app.getAccountId(), app.getApplicationName(), app);
|
||||
aware.putForAccount(app.getAccountId(), key, app);
|
||||
} else {
|
||||
storage.put(app.getApplicationName(), app);
|
||||
storage.put(key, app);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<FlinkApplication> getStoredApplication(String accountId, String region,
|
||||
String applicationName) {
|
||||
String key = applicationKey(region, applicationName);
|
||||
if (storage instanceof AccountAwareStorageBackend<FlinkApplication> aware) {
|
||||
List<String> legacyKeys = region.equals(config.defaultRegion())
|
||||
? List.of(applicationName) : List.of();
|
||||
return aware.getForAccountMigratingLegacyKeys(accountId, key, legacyKeys,
|
||||
application -> belongsTo(application, accountId, region, applicationName),
|
||||
isDefaultScope(accountId, region));
|
||||
}
|
||||
synchronized (storage) {
|
||||
Optional<FlinkApplication> scoped = storage.get(key);
|
||||
if (scoped.isPresent() || !region.equals(config.defaultRegion())) {
|
||||
return scoped;
|
||||
}
|
||||
Optional<FlinkApplication> legacy = storage.get(applicationName)
|
||||
.filter(application -> belongsTo(application, accountId, region, applicationName));
|
||||
legacy.ifPresent(application -> {
|
||||
storage.put(key, application);
|
||||
storage.delete(applicationName);
|
||||
});
|
||||
return legacy;
|
||||
}
|
||||
}
|
||||
|
||||
private void migrateLegacyApplications(AccountAwareStorageBackend<FlinkApplication> aware,
|
||||
String accountId, String region) {
|
||||
if (!region.equals(config.defaultRegion())) {
|
||||
return;
|
||||
}
|
||||
aware.migrateLegacyEntries(accountId, key -> !key.contains("/"),
|
||||
application -> applicationKey(region, application.getApplicationName()),
|
||||
application -> belongsTo(application, accountId, region, application.getApplicationName()));
|
||||
}
|
||||
|
||||
private boolean isDefaultScope(String accountId, String region) {
|
||||
return accountId.equals(regionResolver.getDefaultAccountId())
|
||||
&& region.equals(regionResolver.getDefaultRegion());
|
||||
}
|
||||
|
||||
private static boolean belongsTo(FlinkApplication application, String accountId, String region,
|
||||
String applicationName) {
|
||||
if (!Objects.equals(applicationName, application.getApplicationName())) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(application.getApplicationArn());
|
||||
return accountId.equals(arn.accountId()) && region.equals(arn.region())
|
||||
&& (application.getAccountId() == null || accountId.equals(application.getAccountId()));
|
||||
} catch (IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String applicationKey(String region, String applicationName) {
|
||||
return region + "/" + applicationName;
|
||||
}
|
||||
}
|
||||
+47
-30
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
@@ -117,8 +118,23 @@ public class FlinkContainerManager {
|
||||
* accounts using the same application name would map to the same container. This mirrors AWS, where
|
||||
* an application name is account-and-region unique, and matches the accepted OpenSearch trade-off.
|
||||
*/
|
||||
private String containerName(String applicationName) {
|
||||
return ContainerStorageHelper.resourceName(config, "kinesisanalytics", null, applicationName);
|
||||
private String runtimeKey(FlinkApplication app) {
|
||||
String arn = app.getApplicationArn();
|
||||
if (arn == null || arn.isBlank()) {
|
||||
arn = "arn:aws:kinesisanalytics:" + regionResolver.getDefaultRegion() + ":"
|
||||
+ regionResolver.getAccountId() + ":application/"
|
||||
+ app.getApplicationName();
|
||||
}
|
||||
return arn.replace(':', '-').replace('/', '-');
|
||||
}
|
||||
|
||||
private String containerName(FlinkApplication app) {
|
||||
return ContainerStorageHelper.resourceName(config, "kinesisanalytics", null, runtimeKey(app));
|
||||
}
|
||||
|
||||
private String regionOf(FlinkApplication app) {
|
||||
String arn = app.getApplicationArn();
|
||||
return arn == null || arn.isBlank() ? regionResolver.getDefaultRegion() : AwsArnUtils.parse(arn).region();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -129,13 +145,14 @@ public class FlinkContainerManager {
|
||||
public void startCluster(FlinkApplication app) {
|
||||
String image = KinesisAnalyticsRuntimes.resolveImage(
|
||||
config.services().kinesisAnalytics().defaultImage(), app.getRuntimeEnvironment());
|
||||
String jmName = containerName(app.getApplicationName());
|
||||
String jmName = containerName(app);
|
||||
String tmName = jmName + "-tm";
|
||||
|
||||
// Read the JAR before starting anything so a missing/empty artifact fails fast, before any
|
||||
// container is created. (S3 read runs on the request thread → account context is available.)
|
||||
byte[] jarBytes = app.hasCode() ? readJar(app) : null;
|
||||
List<String> awsBaselineEnv = awsEnv.sdkBaselineEnv(config.defaultRegion(), Optional.empty());
|
||||
String region = regionOf(app);
|
||||
List<String> awsBaselineEnv = awsEnv.sdkBaselineEnv(region, Optional.empty());
|
||||
|
||||
LOG.infov("Starting Flink cluster for application {0} using image {1}{2}",
|
||||
app.getApplicationName(), image, app.hasCode() ? " (with TaskManager)" : "");
|
||||
@@ -155,14 +172,14 @@ public class FlinkContainerManager {
|
||||
.withEmbeddedDns()
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"kinesisanalytics", app.getApplicationName(), regionResolver.getAccountId(),
|
||||
regionResolver.getDefaultRegion()));
|
||||
"kinesisanalytics", app.getApplicationName(),
|
||||
app.getAccountId() != null ? app.getAccountId() : regionResolver.getAccountId(), region));
|
||||
// Named volume (not the container's ephemeral filesystem) so snapshots survive a
|
||||
// Stop/StartApplication cycle — stopCluster() removes the JobManager container, but this
|
||||
// volume is only removed on DeleteApplication (removeSavepointsVolume), mirroring how other
|
||||
// Docker-backed services keep persistent data outside the container lifecycle.
|
||||
ContainerStorageHelper.applyStorage(jmSpec, lifecycleManager, config, "kinesisanalytics",
|
||||
app.getApplicationName() + "-savepoints", app.getApplicationName() + "-savepoints",
|
||||
runtimeKey(app) + "-savepoints", runtimeKey(app) + "-savepoints",
|
||||
SAVEPOINTS_MOUNT);
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
jmSpec.withDynamicPort(JOBMANAGER_REST_PORT);
|
||||
@@ -186,7 +203,7 @@ public class FlinkContainerManager {
|
||||
throw e;
|
||||
}
|
||||
app.setContainerId(jm.containerId());
|
||||
containerIds.put(app.getApplicationName(), jm.containerId());
|
||||
containerIds.put(runtimeKey(app), jm.containerId());
|
||||
EndpointInfo rest = jm.getEndpoint(JOBMANAGER_REST_PORT);
|
||||
app.setRestEndpoint("http://" + rest.host() + ":" + rest.port());
|
||||
attachLogs(app, jm.containerId());
|
||||
@@ -206,8 +223,8 @@ public class FlinkContainerManager {
|
||||
.withNetworkMode("container:" + jm.containerId())
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"kinesisanalytics", app.getApplicationName(), regionResolver.getAccountId(),
|
||||
regionResolver.getDefaultRegion()))
|
||||
"kinesisanalytics", app.getApplicationName(),
|
||||
app.getAccountId() != null ? app.getAccountId() : regionResolver.getAccountId(), region))
|
||||
.build();
|
||||
try {
|
||||
String tmContainerId = lifecycleManager.create(tmSpec);
|
||||
@@ -215,7 +232,7 @@ public class FlinkContainerManager {
|
||||
msfStyleLog4j2Config(app), true);
|
||||
ContainerInfo tm = lifecycleManager.startCreated(tmContainerId, tmSpec);
|
||||
app.setTaskManagerContainerId(tm.containerId());
|
||||
taskManagerIds.put(app.getApplicationName(), tm.containerId());
|
||||
taskManagerIds.put(runtimeKey(app), tm.containerId());
|
||||
} catch (RuntimeException e) {
|
||||
// Roll back the whole cluster so a failed start leaves nothing behind.
|
||||
lifecycleManager.removeIfExists(tmName);
|
||||
@@ -236,8 +253,8 @@ public class FlinkContainerManager {
|
||||
copyFileIntoContainer(jm.containerId(), "/etc", "flink/application_properties.json", propertiesJson);
|
||||
copyFileIntoContainer(app.getTaskManagerContainerId(), "/etc", "flink/application_properties.json",
|
||||
propertiesJson);
|
||||
pendingJars.put(app.getApplicationName(), jarBytes);
|
||||
submissionFailed.remove(app.getApplicationName());
|
||||
pendingJars.put(runtimeKey(app), jarBytes);
|
||||
submissionFailed.remove(runtimeKey(app));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,13 +429,13 @@ public class FlinkContainerManager {
|
||||
return true;
|
||||
}
|
||||
if (app.getFlinkJobId() == null) {
|
||||
if (submissionFailed.contains(app.getApplicationName())) {
|
||||
if (submissionFailed.contains(runtimeKey(app))) {
|
||||
return false;
|
||||
}
|
||||
if (flinkRest.totalSlots(rest) < Math.max(1, app.getParallelism())) {
|
||||
return false; // TaskManager not registered yet
|
||||
}
|
||||
byte[] jar = pendingJars.get(app.getApplicationName());
|
||||
byte[] jar = pendingJars.get(runtimeKey(app));
|
||||
if (jar == null) {
|
||||
return false; // stashed at StartApplication; absent only after an emulator restart
|
||||
}
|
||||
@@ -426,11 +443,11 @@ public class FlinkContainerManager {
|
||||
String jarId = flinkRest.uploadJar(rest, jar);
|
||||
String jobId = flinkRest.runJob(rest, jarId, app.getParallelism());
|
||||
app.setFlinkJobId(jobId);
|
||||
pendingJars.remove(app.getApplicationName());
|
||||
pendingJars.remove(runtimeKey(app));
|
||||
LOG.infov("Submitted Flink job {0} for application {1}", jobId, app.getApplicationName());
|
||||
} catch (Exception e) {
|
||||
// Hard failure (e.g. a JAR with no main class) — do not resubmit every tick.
|
||||
submissionFailed.add(app.getApplicationName());
|
||||
submissionFailed.add(runtimeKey(app));
|
||||
LOG.errorv(e, "Failed to submit Flink job for application {0}", app.getApplicationName());
|
||||
}
|
||||
return false;
|
||||
@@ -457,8 +474,8 @@ public class FlinkContainerManager {
|
||||
copyFileIntoContainer(app.getContainerId(), "/etc", "flink/application_properties.json", propertiesJson);
|
||||
copyFileIntoContainer(app.getTaskManagerContainerId(), "/etc", "flink/application_properties.json",
|
||||
propertiesJson);
|
||||
pendingJars.put(app.getApplicationName(), readJar(app));
|
||||
submissionFailed.remove(app.getApplicationName());
|
||||
pendingJars.put(runtimeKey(app), readJar(app));
|
||||
submissionFailed.remove(runtimeKey(app));
|
||||
LOG.infov("Redeployed code for Kinesis Analytics V2 application {0}", app.getApplicationName());
|
||||
}
|
||||
|
||||
@@ -467,28 +484,28 @@ public class FlinkContainerManager {
|
||||
if (rest != null && app.getFlinkJobId() != null) {
|
||||
flinkRest.cancelJob(rest, app.getFlinkJobId());
|
||||
}
|
||||
pendingJars.remove(app.getApplicationName());
|
||||
submissionFailed.remove(app.getApplicationName());
|
||||
pendingJars.remove(runtimeKey(app));
|
||||
submissionFailed.remove(runtimeKey(app));
|
||||
|
||||
// Stop the TaskManager first, then the JobManager (whose netns it shares).
|
||||
String tmId = taskManagerIds.remove(app.getApplicationName());
|
||||
String tmId = taskManagerIds.remove(runtimeKey(app));
|
||||
if (tmId == null) {
|
||||
tmId = app.getTaskManagerContainerId();
|
||||
}
|
||||
if (tmId != null) {
|
||||
lifecycleManager.stopAndRemove(tmId, null);
|
||||
} else {
|
||||
lifecycleManager.removeIfExists(containerName(app.getApplicationName()) + "-tm");
|
||||
lifecycleManager.removeIfExists(containerName(app) + "-tm");
|
||||
}
|
||||
|
||||
containerIds.remove(app.getApplicationName());
|
||||
Closeable logHandle = logStreams.remove(app.getApplicationName());
|
||||
containerIds.remove(runtimeKey(app));
|
||||
Closeable logHandle = logStreams.remove(runtimeKey(app));
|
||||
String jmId = app.getContainerId();
|
||||
if (jmId != null) {
|
||||
lifecycleManager.stopAndRemove(jmId, logHandle);
|
||||
LOG.infov("Flink cluster for application {0} stopped and removed", app.getApplicationName());
|
||||
} else {
|
||||
lifecycleManager.removeIfExists(containerName(app.getApplicationName()));
|
||||
lifecycleManager.removeIfExists(containerName(app));
|
||||
}
|
||||
app.setContainerId(null);
|
||||
app.setRestEndpoint(null);
|
||||
@@ -564,7 +581,7 @@ public class FlinkContainerManager {
|
||||
* StopApplication (stopCluster), so snapshots survive a stop/restart cycle. */
|
||||
public void removeSavepointsVolume(FlinkApplication app) {
|
||||
ContainerStorageHelper.removeStorage(config, lifecycleManager, "kinesisanalytics",
|
||||
app.getApplicationName() + "-savepoints", app.getApplicationName() + "-savepoints");
|
||||
runtimeKey(app) + "-savepoints", runtimeKey(app) + "-savepoints");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -596,11 +613,11 @@ public class FlinkContainerManager {
|
||||
String shortId = containerId.length() >= 8 ? containerId.substring(0, 8) : containerId;
|
||||
String logGroup = "/aws/kinesis-analytics/" + app.getApplicationName();
|
||||
String logStream = logStreamer.generateLogStreamName(shortId);
|
||||
String region = regionResolver.getDefaultRegion();
|
||||
String region = regionOf(app);
|
||||
Closeable logHandle = logStreamer.attach(containerId, logGroup, logStream, region,
|
||||
"kinesisanalytics:" + app.getApplicationName());
|
||||
"kinesisanalytics:" + runtimeKey(app));
|
||||
if (logHandle != null) {
|
||||
logStreams.put(app.getApplicationName(), logHandle);
|
||||
logStreams.put(runtimeKey(app), logHandle);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+26
@@ -8,6 +8,7 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
@@ -24,6 +25,11 @@ class KinesisAnalyticsV2IntegrationTest {
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String ROLE = "arn:aws:iam::000000000000:role/x";
|
||||
|
||||
private static String authorization(String region) {
|
||||
return "AWS4-HMAC-SHA256 Credential=AKID/20260916/" + region
|
||||
+ "/kinesisanalytics/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
@@ -64,6 +70,26 @@ class KinesisAnalyticsV2IntegrationTest {
|
||||
.body("ApplicationDetail.RuntimeEnvironment", equalTo("FLINK-1_18"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameApplicationNameIsIsolatedByRequestRegion() {
|
||||
String name = "it-region-" + System.nanoTime();
|
||||
String body = "{\"ApplicationName\": \"" + name
|
||||
+ "\", \"RuntimeEnvironment\": \"FLINK-1_18\","
|
||||
+ " \"ServiceExecutionRole\": \"" + ROLE + "\"}";
|
||||
|
||||
given().header("Authorization", authorization("us-east-1"))
|
||||
.header("X-Amz-Target", "KinesisAnalytics_20180523.CreateApplication")
|
||||
.contentType(CONTENT_TYPE).body(body)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body("ApplicationDetail.ApplicationARN", containsString(":us-east-1:"));
|
||||
|
||||
given().header("Authorization", authorization("us-west-2"))
|
||||
.header("X-Amz-Target", "KinesisAnalytics_20180523.CreateApplication")
|
||||
.contentType(CONTENT_TYPE).body(body)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body("ApplicationDetail.ApplicationARN", containsString(":us-west-2:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startApplicationTransitionsToRunning() {
|
||||
createApplication("it-start");
|
||||
|
||||
+99
-3
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.kinesisanalytics;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
@@ -131,6 +132,22 @@ class KinesisAnalyticsV2ServiceTest {
|
||||
assertThrows(AwsException.class, () -> create("demo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameApplicationNameCanExistInDifferentRegions() {
|
||||
FlinkApplication east = create("regional");
|
||||
FlinkApplication west = service.createApplication("regional", "FLINK-1_18", ROLE,
|
||||
null, null, null, null, null, 1, null, null, null, "us-west-2");
|
||||
|
||||
assertEquals("us-east-1", AwsArnUtils.parse(east.getApplicationArn()).region());
|
||||
assertEquals("us-west-2", AwsArnUtils.parse(west.getApplicationArn()).region());
|
||||
assertEquals(1, service.listApplications("us-east-1").size());
|
||||
assertEquals(1, service.listApplications("us-west-2").size());
|
||||
assertEquals("us-east-1", AwsArnUtils
|
||||
.parse(service.describeApplication("regional", "us-east-1").getApplicationArn()).region());
|
||||
assertEquals("us-west-2", AwsArnUtils
|
||||
.parse(service.describeApplication("regional", "us-west-2").getApplicationArn()).region());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeApplicationThrowsWhenMissing() {
|
||||
assertThrows(AwsException.class, () -> service.describeApplication("nope"));
|
||||
@@ -301,6 +318,68 @@ class KinesisAnalyticsV2ServiceTest {
|
||||
assertEquals("platform", service.listTagsForResource(app.getApplicationArn()).get("team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagResourceMigratesLegacyApplicationToRegionalKey() {
|
||||
AccountAwareStorageBackend<FlinkApplication> store =
|
||||
AccountAwareStorageBackend.inMemory("000000000000");
|
||||
KinesisAnalyticsV2Service legacyState = mockModeService(store);
|
||||
FlinkApplication legacyApp = legacyApplication("legacy");
|
||||
store.putForAccount("000000000000", "legacy", legacyApp);
|
||||
|
||||
Map<String, String> tags = legacyState.tagResource(
|
||||
legacyApp.getApplicationArn(), Map.of("team", "platform"));
|
||||
|
||||
assertEquals("platform", tags.get("team"));
|
||||
assertTrue(store.getForAccount("000000000000", "legacy").isEmpty());
|
||||
assertEquals("platform", store.getForAccount("000000000000", "us-east-1/legacy")
|
||||
.orElseThrow().getTags().get("team"));
|
||||
assertEquals("platform", legacyState.listTagsForResource(legacyApp.getApplicationArn()).get("team"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagResourceRejectsArnOwnedByAnotherAccount() {
|
||||
FlinkApplication local = create("shared-name");
|
||||
String foreignArn = AwsArnUtils.Arn.of("kinesisanalytics", "us-east-1", "111122223333",
|
||||
"application/shared-name").toString();
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> service.tagResource(foreignArn, Map.of("team", "foreign")));
|
||||
|
||||
assertTrue(service.listTagsForResource(local.getApplicationArn()).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagResourceDoesNotMigrateLegacyApplicationIntoAnotherRegion() {
|
||||
AccountAwareStorageBackend<FlinkApplication> store =
|
||||
AccountAwareStorageBackend.inMemory("000000000000");
|
||||
KinesisAnalyticsV2Service legacyState = mockModeService(store);
|
||||
store.putForAccount("000000000000", "legacy", legacyApplication("legacy"));
|
||||
String westArn = AwsArnUtils.Arn.of("kinesisanalytics", "us-west-2", "000000000000",
|
||||
"application/legacy").toString();
|
||||
|
||||
assertThrows(AwsException.class,
|
||||
() -> legacyState.tagResource(westArn, Map.of("team", "platform")));
|
||||
|
||||
assertTrue(store.getForAccount("000000000000", "legacy").isPresent());
|
||||
assertTrue(store.getForAccount("000000000000", "us-west-2/legacy").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listApplicationsMigratesLegacyApplicationToRegionalKey() {
|
||||
AccountAwareStorageBackend<FlinkApplication> store =
|
||||
AccountAwareStorageBackend.inMemory("000000000000");
|
||||
KinesisAnalyticsV2Service legacyState = mockModeService(store);
|
||||
store.putForAccount("000000000000", "legacy", legacyApplication("legacy"));
|
||||
|
||||
List<FlinkApplication> applications = legacyState.listApplications("us-east-1");
|
||||
|
||||
assertEquals(List.of("legacy"), applications.stream()
|
||||
.map(FlinkApplication::getApplicationName)
|
||||
.toList());
|
||||
assertTrue(store.getForAccount("000000000000", "legacy").isEmpty());
|
||||
assertTrue(store.getForAccount("000000000000", "us-east-1/legacy").isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void untagResourceRemovesKeys() {
|
||||
FlinkApplication app = create("demo");
|
||||
@@ -639,7 +718,7 @@ class KinesisAnalyticsV2ServiceTest {
|
||||
Thread.sleep(1500);
|
||||
|
||||
Mockito.verify(store, Mockito.atLeastOnce())
|
||||
.putForAccount(Mockito.eq("000000000000"), Mockito.eq("demo"), Mockito.any());
|
||||
.putForAccount(Mockito.eq("000000000000"), Mockito.eq("us-east-1/demo"), Mockito.any());
|
||||
assertEquals("job-1", realMode.describeApplication("demo").getFlinkJobId());
|
||||
} finally {
|
||||
realMode.shutdown();
|
||||
@@ -650,6 +729,18 @@ class KinesisAnalyticsV2ServiceTest {
|
||||
return buildService(true, Mockito.mock(FlinkContainerManager.class));
|
||||
}
|
||||
|
||||
private KinesisAnalyticsV2Service mockModeService(AccountAwareStorageBackend<FlinkApplication> store) {
|
||||
return buildService(true, Mockito.mock(FlinkContainerManager.class), store);
|
||||
}
|
||||
|
||||
private FlinkApplication legacyApplication(String name) {
|
||||
FlinkApplication application = new FlinkApplication(name,
|
||||
"arn:aws:kinesisanalytics:us-east-1:000000000000:application/" + name,
|
||||
"FLINK-1_18", ROLE, "STREAMING");
|
||||
application.setAccountId("000000000000");
|
||||
return application;
|
||||
}
|
||||
|
||||
private KinesisAnalyticsV2Service realModeServiceWithFailingManager() {
|
||||
FlinkContainerManager failing = Mockito.mock(FlinkContainerManager.class);
|
||||
Mockito.doThrow(new RuntimeException("docker unavailable"))
|
||||
@@ -658,9 +749,14 @@ class KinesisAnalyticsV2ServiceTest {
|
||||
}
|
||||
|
||||
private KinesisAnalyticsV2Service buildService(boolean mock, FlinkContainerManager manager) {
|
||||
return buildService(mock, manager, AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
}
|
||||
|
||||
private KinesisAnalyticsV2Service buildService(boolean mock, FlinkContainerManager manager,
|
||||
AccountAwareStorageBackend<FlinkApplication> store) {
|
||||
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
|
||||
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
|
||||
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
Mockito.doReturn(store).when(storageFactory)
|
||||
.create(Mockito.anyString(), Mockito.anyString(), Mockito.any());
|
||||
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
|
||||
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
|
||||
|
||||
+5
-5
@@ -316,8 +316,8 @@ class FlinkContainerManagerTest {
|
||||
|
||||
assertThrows(RuntimeException.class, () -> manager.startCluster(app));
|
||||
|
||||
verify(lifecycleManager, times(2)).removeIfExists("floci-kinesisanalytics-jm-failure");
|
||||
verify(lifecycleManager, atLeastOnce()).removeIfExists("floci-kinesisanalytics-jm-failure-tm");
|
||||
verify(lifecycleManager, times(2)).removeIfExists("floci-kinesisanalytics-arn-aws-kinesisanalytics-us-west-2-000000000000-application-jm-failure");
|
||||
verify(lifecycleManager, atLeastOnce()).removeIfExists("floci-kinesisanalytics-arn-aws-kinesisanalytics-us-west-2-000000000000-application-jm-failure-tm");
|
||||
assertNull(app.getContainerId());
|
||||
assertNull(app.getTaskManagerContainerId());
|
||||
}
|
||||
@@ -337,7 +337,7 @@ class FlinkContainerManagerTest {
|
||||
assertThrows(RuntimeException.class, () -> manager.startCluster(app));
|
||||
|
||||
verify(lifecycleManager).stopAndRemove("jm-id", null);
|
||||
verify(lifecycleManager, atLeastOnce()).removeIfExists("floci-kinesisanalytics-tm-failure-tm");
|
||||
verify(lifecycleManager, atLeastOnce()).removeIfExists("floci-kinesisanalytics-arn-aws-kinesisanalytics-us-west-2-000000000000-application-tm-failure-tm");
|
||||
assertNull(app.getContainerId());
|
||||
assertNull(app.getRestEndpoint());
|
||||
assertNull(app.getTaskManagerContainerId());
|
||||
@@ -356,8 +356,8 @@ class FlinkContainerManagerTest {
|
||||
|
||||
assertThrows(RuntimeException.class, () -> manager.startCluster(app));
|
||||
|
||||
verify(lifecycleManager, times(2)).removeIfExists("floci-kinesisanalytics-log4j-copy-failure");
|
||||
verify(lifecycleManager, atLeastOnce()).removeIfExists("floci-kinesisanalytics-log4j-copy-failure-tm");
|
||||
verify(lifecycleManager, times(2)).removeIfExists("floci-kinesisanalytics-arn-aws-kinesisanalytics-us-west-2-000000000000-application-log4j-copy-failure");
|
||||
verify(lifecycleManager, atLeastOnce()).removeIfExists("floci-kinesisanalytics-arn-aws-kinesisanalytics-us-west-2-000000000000-application-log4j-copy-failure-tm");
|
||||
verify(lifecycleManager, Mockito.never()).startCreated(any(), any());
|
||||
assertNull(app.getContainerId());
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user