mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
firt commit
This commit is contained in:
313 files changed
+51266
No files matched your search
@@ -0,0 +1,334 @@
|
||||
package io.github.hectorvent.floci.config;
|
||||
|
||||
import io.smallrye.config.ConfigMapping;
|
||||
import io.smallrye.config.WithDefault;
|
||||
import java.util.Optional;
|
||||
|
||||
@ConfigMapping(prefix = "floci")
|
||||
public interface EmulatorConfig {
|
||||
|
||||
@WithDefault("http://localhost:4566")
|
||||
String baseUrl();
|
||||
|
||||
@WithDefault("us-east-1")
|
||||
String defaultRegion();
|
||||
|
||||
@WithDefault("000000000000")
|
||||
String defaultAccountId();
|
||||
|
||||
StorageConfig storage();
|
||||
|
||||
AuthConfig auth();
|
||||
|
||||
ServicesConfig services();
|
||||
|
||||
interface StorageConfig {
|
||||
@WithDefault("hybrid")
|
||||
String mode();
|
||||
|
||||
@WithDefault("./data")
|
||||
String persistentPath();
|
||||
|
||||
WalConfig wal();
|
||||
|
||||
ServiceStorageOverrides services();
|
||||
}
|
||||
|
||||
interface ServiceStorageOverrides {
|
||||
SsmStorageConfig ssm();
|
||||
SqsStorageConfig sqs();
|
||||
S3StorageConfig s3();
|
||||
DynamoDbStorageConfig dynamodb();
|
||||
SnsStorageConfig sns();
|
||||
LambdaStorageConfig lambda();
|
||||
CloudWatchLogsStorageConfig cloudwatchlogs();
|
||||
CloudWatchMetricsStorageConfig cloudwatchmetrics();
|
||||
SecretsManagerStorageConfig secretsmanager();
|
||||
}
|
||||
|
||||
interface SsmStorageConfig {
|
||||
@WithDefault("memory")
|
||||
String mode();
|
||||
|
||||
@WithDefault("5000")
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface SqsStorageConfig {
|
||||
@WithDefault("memory")
|
||||
String mode();
|
||||
}
|
||||
|
||||
interface S3StorageConfig {
|
||||
@WithDefault("hybrid")
|
||||
String mode();
|
||||
}
|
||||
|
||||
interface DynamoDbStorageConfig {
|
||||
@WithDefault("memory")
|
||||
String mode();
|
||||
|
||||
@WithDefault("5000")
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface SnsStorageConfig {
|
||||
@WithDefault("memory")
|
||||
String mode();
|
||||
|
||||
@WithDefault("5000")
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface LambdaStorageConfig {
|
||||
@WithDefault("memory")
|
||||
String mode();
|
||||
|
||||
@WithDefault("5000")
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface CloudWatchLogsStorageConfig {
|
||||
@WithDefault("memory")
|
||||
String mode();
|
||||
|
||||
@WithDefault("5000")
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface CloudWatchMetricsStorageConfig {
|
||||
@WithDefault("memory")
|
||||
String mode();
|
||||
|
||||
@WithDefault("5000")
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface SecretsManagerStorageConfig {
|
||||
@WithDefault("memory")
|
||||
String mode();
|
||||
|
||||
@WithDefault("5000")
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface WalConfig {
|
||||
@WithDefault("30000")
|
||||
long compactionIntervalMs();
|
||||
}
|
||||
|
||||
interface AuthConfig {
|
||||
@WithDefault("false")
|
||||
boolean validateSignatures();
|
||||
|
||||
@WithDefault("local-emulator-secret")
|
||||
String presignSecret();
|
||||
}
|
||||
|
||||
interface ServicesConfig {
|
||||
/** Shared Docker network for all container-based services (Lambda, RDS, ElastiCache).
|
||||
* Per-service dockerNetwork settings override this value when present. */
|
||||
Optional<String> dockerNetwork();
|
||||
|
||||
SsmServiceConfig ssm();
|
||||
SqsServiceConfig sqs();
|
||||
S3ServiceConfig s3();
|
||||
DynamoDbServiceConfig dynamodb();
|
||||
SnsServiceConfig sns();
|
||||
LambdaServiceConfig lambda();
|
||||
ApiGatewayServiceConfig apigateway();
|
||||
IamServiceConfig iam();
|
||||
ElastiCacheServiceConfig elasticache();
|
||||
RdsServiceConfig rds();
|
||||
EventBridgeServiceConfig eventbridge();
|
||||
CloudWatchLogsServiceConfig cloudwatchlogs();
|
||||
CloudWatchMetricsServiceConfig cloudwatchmetrics();
|
||||
SecretsManagerServiceConfig secretsmanager();
|
||||
ApiGatewayV2ServiceConfig apigatewayv2();
|
||||
KinesisServiceConfig kinesis();
|
||||
KmsServiceConfig kms();
|
||||
CognitoServiceConfig cognito();
|
||||
StepFunctionsServiceConfig stepfunctions();
|
||||
CloudFormationServiceConfig cloudformation();
|
||||
}
|
||||
|
||||
interface SsmServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("5")
|
||||
int maxParameterHistory();
|
||||
}
|
||||
|
||||
interface SqsServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("30")
|
||||
int defaultVisibilityTimeout();
|
||||
|
||||
@WithDefault("262144")
|
||||
int maxMessageSize();
|
||||
}
|
||||
|
||||
interface S3ServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("3600")
|
||||
int defaultPresignExpirySeconds();
|
||||
}
|
||||
|
||||
interface DynamoDbServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface SnsServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface ApiGatewayServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface IamServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface ElastiCacheServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("6379")
|
||||
int proxyBasePort();
|
||||
|
||||
@WithDefault("6399")
|
||||
int proxyMaxPort();
|
||||
|
||||
@WithDefault("valkey/valkey:8")
|
||||
String defaultImage();
|
||||
|
||||
/** Docker network to attach Valkey containers to. Empty = default bridge. */
|
||||
Optional<String> dockerNetwork();
|
||||
}
|
||||
|
||||
interface RdsServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("7000")
|
||||
int proxyBasePort();
|
||||
|
||||
@WithDefault("7099")
|
||||
int proxyMaxPort();
|
||||
|
||||
@WithDefault("postgres:16-alpine")
|
||||
String defaultPostgresImage();
|
||||
|
||||
@WithDefault("mysql:8.0")
|
||||
String defaultMysqlImage();
|
||||
|
||||
@WithDefault("mariadb:11")
|
||||
String defaultMariadbImage();
|
||||
|
||||
/** Docker network to attach DB containers to. Empty = default bridge. */
|
||||
Optional<String> dockerNetwork();
|
||||
}
|
||||
|
||||
interface EventBridgeServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface CloudWatchLogsServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("10000")
|
||||
int maxEventsPerQuery();
|
||||
}
|
||||
|
||||
interface CloudWatchMetricsServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface SecretsManagerServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("30")
|
||||
int defaultRecoveryWindowDays();
|
||||
}
|
||||
|
||||
interface ApiGatewayV2ServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface KinesisServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface KmsServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface CognitoServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface StepFunctionsServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface CloudFormationServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface LambdaServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("128")
|
||||
int defaultMemoryMb();
|
||||
|
||||
@WithDefault("3")
|
||||
int defaultTimeoutSeconds();
|
||||
|
||||
@WithDefault("unix:///var/run/docker.sock")
|
||||
String dockerHost();
|
||||
|
||||
Optional<String> dockerHostOverride();
|
||||
|
||||
@WithDefault("9200")
|
||||
int runtimeApiBasePort();
|
||||
|
||||
@WithDefault("9299")
|
||||
int runtimeApiMaxPort();
|
||||
|
||||
@WithDefault("./data/lambda-code")
|
||||
String codePath();
|
||||
|
||||
@WithDefault("1000")
|
||||
long pollIntervalMs();
|
||||
|
||||
@WithDefault("false")
|
||||
boolean ephemeral();
|
||||
|
||||
@WithDefault("300")
|
||||
int containerIdleTimeoutSeconds();
|
||||
|
||||
/** Docker network to attach Lambda containers to. Empty = default bridge. */
|
||||
Optional<String> dockerNetwork();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
public final class AwsArnUtils {
|
||||
|
||||
private AwsArnUtils() {}
|
||||
|
||||
/**
|
||||
* Converts an SQS ARN to a queue URL using the given base URL.
|
||||
* Example: arn:aws:sqs:us-east-1:000000000000:my-queue → http://localhost:4566/000000000000/my-queue
|
||||
*/
|
||||
public static String arnToQueueUrl(String arn, String baseUrl) {
|
||||
String[] parts = arn.split(":");
|
||||
return baseUrl + "/" + parts[4] + "/" + parts[5];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerResponseContext;
|
||||
import jakarta.ws.rs.container.ContainerResponseFilter;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Sets the Date response header in RFC 822 format as expected by AWS SDKs.
|
||||
* Without this, Quarkus/Vert.x may send ISO 8601 format which the SDK cannot parse.
|
||||
*/
|
||||
@Provider
|
||||
public class AwsDateHeaderFilter implements ContainerResponseFilter {
|
||||
|
||||
private static final ZoneId GMT = ZoneId.of("GMT");
|
||||
private static final DateTimeFormatter RFC_822 = DateTimeFormatter
|
||||
.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
|
||||
responseContext.getHeaders().putSingle("Date",
|
||||
ZonedDateTime.now(GMT).format(RFC_822));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public record AwsErrorResponse(@JsonProperty("__type") String type, @JsonProperty("message") String message) {
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
/**
|
||||
* Base exception for AWS emulator errors.
|
||||
* Maps to AWS-style error responses with code, message, and HTTP status.
|
||||
*/
|
||||
public class AwsException extends RuntimeException {
|
||||
|
||||
private final String errorCode;
|
||||
private final int httpStatus;
|
||||
|
||||
public AwsException(String errorCode, String message, int httpStatus) {
|
||||
super(message);
|
||||
this.errorCode = errorCode;
|
||||
this.httpStatus = httpStatus;
|
||||
}
|
||||
|
||||
public String getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
public int getHttpStatus() {
|
||||
return httpStatus;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.ExceptionMapper;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* JAX-RS exception mapper that converts AwsException to AWS-formatted JSON error responses.
|
||||
*/
|
||||
@Provider
|
||||
public class AwsExceptionMapper implements ExceptionMapper<AwsException> {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AwsExceptionMapper.class);
|
||||
|
||||
@Override
|
||||
public Response toResponse(AwsException exception) {
|
||||
LOG.debugv("Mapping exception: {0} - {1}", exception.getErrorCode(), exception.getMessage());
|
||||
return Response.status(exception.getHttpStatus())
|
||||
.entity(new AwsErrorResponse(exception.getErrorCode(), exception.getMessage()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2JsonHandler;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsHandler;
|
||||
import io.github.hectorvent.floci.services.cognito.CognitoJsonHandler;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler;
|
||||
import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler;
|
||||
import io.github.hectorvent.floci.services.kms.KmsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerJsonHandler;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmJsonHandler;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* Generic dispatcher for all AWS services that use the application/x-amz-json-1.1 protocol.
|
||||
* Routes requests to the appropriate service handler based on the X-Amz-Target header prefix.
|
||||
* <p>
|
||||
* Currently supported services:
|
||||
* - SSM (AmazonSSM.*)
|
||||
* - EventBridge (AmazonEventBridge.*)
|
||||
* - CloudWatch Logs (Logs_20140328.*)
|
||||
*/
|
||||
@Path("/")
|
||||
public class AwsJson11Controller {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AwsJson11Controller.class);
|
||||
|
||||
private static final String SSM_TARGET_PREFIX = "AmazonSSM.";
|
||||
private static final String EVENTBRIDGE_TARGET_PREFIX = "AWSEvents.";
|
||||
private static final String LOGS_TARGET_PREFIX = "Logs_20140328.";
|
||||
private static final String SECRETS_MANAGER_TARGET_PREFIX = "secretsmanager.";
|
||||
private static final String KINESIS_TARGET_PREFIX = "Kinesis_20131202.";
|
||||
private static final String APIGW_V2_TARGET_PREFIX = "AmazonApiGatewayV2.";
|
||||
private static final String KMS_TARGET_PREFIX = "TrentService.";
|
||||
private static final String COGNITO_TARGET_PREFIX = "AWSCognitoIdentityProviderService.";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RegionResolver regionResolver;
|
||||
private final SsmJsonHandler ssmJsonHandler;
|
||||
private final EventBridgeHandler eventBridgeHandler;
|
||||
private final CloudWatchLogsHandler cloudWatchLogsHandler;
|
||||
private final SecretsManagerJsonHandler secretsManagerJsonHandler;
|
||||
private final KinesisJsonHandler kinesisJsonHandler;
|
||||
private final ApiGatewayV2JsonHandler apigwV2JsonHandler;
|
||||
private final KmsJsonHandler kmsJsonHandler;
|
||||
private final CognitoJsonHandler cognitoJsonHandler;
|
||||
|
||||
@Inject
|
||||
public AwsJson11Controller(ObjectMapper objectMapper, RegionResolver regionResolver,
|
||||
SsmJsonHandler ssmJsonHandler, EventBridgeHandler eventBridgeHandler,
|
||||
CloudWatchLogsHandler cloudWatchLogsHandler,
|
||||
SecretsManagerJsonHandler secretsManagerJsonHandler,
|
||||
KinesisJsonHandler kinesisJsonHandler,
|
||||
ApiGatewayV2JsonHandler apigwV2JsonHandler,
|
||||
KmsJsonHandler kmsJsonHandler, CognitoJsonHandler cognitoJsonHandler) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.regionResolver = regionResolver;
|
||||
this.ssmJsonHandler = ssmJsonHandler;
|
||||
this.eventBridgeHandler = eventBridgeHandler;
|
||||
this.cloudWatchLogsHandler = cloudWatchLogsHandler;
|
||||
this.secretsManagerJsonHandler = secretsManagerJsonHandler;
|
||||
this.kinesisJsonHandler = kinesisJsonHandler;
|
||||
this.apigwV2JsonHandler = apigwV2JsonHandler;
|
||||
this.kmsJsonHandler = kmsJsonHandler;
|
||||
this.cognitoJsonHandler = cognitoJsonHandler;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Consumes("application/x-amz-json-1.1")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response handle(
|
||||
@HeaderParam("X-Amz-Target") String target,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
String body) {
|
||||
|
||||
if (target == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String prefix;
|
||||
String serviceName;
|
||||
|
||||
if (target.startsWith(SSM_TARGET_PREFIX)) {
|
||||
prefix = SSM_TARGET_PREFIX;
|
||||
serviceName = "SSM";
|
||||
} else if (target.startsWith(EVENTBRIDGE_TARGET_PREFIX)) {
|
||||
prefix = EVENTBRIDGE_TARGET_PREFIX;
|
||||
serviceName = "EventBridge";
|
||||
} else if (target.startsWith(LOGS_TARGET_PREFIX)) {
|
||||
prefix = LOGS_TARGET_PREFIX;
|
||||
serviceName = "Logs";
|
||||
} else if (target.startsWith(SECRETS_MANAGER_TARGET_PREFIX)) {
|
||||
prefix = SECRETS_MANAGER_TARGET_PREFIX;
|
||||
serviceName = "SecretsManager";
|
||||
} else if (target.startsWith(KINESIS_TARGET_PREFIX)) {
|
||||
prefix = KINESIS_TARGET_PREFIX;
|
||||
serviceName = "Kinesis";
|
||||
} else if (target.startsWith(APIGW_V2_TARGET_PREFIX)) {
|
||||
prefix = APIGW_V2_TARGET_PREFIX;
|
||||
serviceName = "ApiGatewayV2";
|
||||
} else if (target.startsWith(KMS_TARGET_PREFIX)) {
|
||||
prefix = KMS_TARGET_PREFIX;
|
||||
serviceName = "KMS";
|
||||
} else if (target.startsWith(COGNITO_TARGET_PREFIX)) {
|
||||
prefix = COGNITO_TARGET_PREFIX;
|
||||
serviceName = "Cognito";
|
||||
} else {
|
||||
return Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnknownOperationException",
|
||||
"Unknown operation: " + target))
|
||||
.build();
|
||||
}
|
||||
|
||||
String action = target.substring(prefix.length());
|
||||
LOG.infov("AwsJson11Controller {0} action: {1}", serviceName, action);
|
||||
|
||||
try {
|
||||
JsonNode request = objectMapper.readTree(body);
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
|
||||
return switch (serviceName) {
|
||||
case "SSM" -> ssmJsonHandler.handle(action, request, region);
|
||||
case "EventBridge" -> eventBridgeHandler.handle(action, request, region);
|
||||
case "Logs" -> cloudWatchLogsHandler.handle(action, request, region);
|
||||
case "SecretsManager" -> secretsManagerJsonHandler.handle(action, request, region);
|
||||
case "Kinesis" -> kinesisJsonHandler.handle(action, request, region);
|
||||
case "ApiGatewayV2" -> apigwV2JsonHandler.handle(action, request, region);
|
||||
case "KMS" -> kmsJsonHandler.handle(action, request, region);
|
||||
case "Cognito" -> cognitoJsonHandler.handle(action, request, region);
|
||||
default -> null;
|
||||
};
|
||||
} catch (AwsException e) {
|
||||
return Response.status(e.getHttpStatus())
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new AwsErrorResponse(e.getErrorCode(), e.getMessage()))
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
LOG.errorf("Error processing %s request", serviceName, e);
|
||||
return Response.status(500)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new AwsErrorResponse("InternalServerError", e.getMessage()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORGenerator;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* Generic dispatcher for all AWS services that use the application/x-amz-json-1.0 protocol.
|
||||
* Routes requests to the appropriate service handler based on the X-Amz-Target header prefix.
|
||||
* <p>
|
||||
* Currently supported services:
|
||||
* - DynamoDB (DynamoDB_20120810.*)
|
||||
* - SQS (AmazonSQS.*)
|
||||
*/
|
||||
@Path("/")
|
||||
public class AwsJsonController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AwsJsonController.class);
|
||||
private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
|
||||
|
||||
private static final String DYNAMODB_TARGET_PREFIX = "DynamoDB_20120810.";
|
||||
private static final String DYNAMODB_STREAMS_TARGET_PREFIX = "DynamoDBStreams_20120810.";
|
||||
private static final String SQS_TARGET_PREFIX = "AmazonSQS.";
|
||||
private static final String SNS_TARGET_PREFIX = "SNS_20100331.";
|
||||
private static final String STEPFUNCTIONS_TARGET_PREFIX = "AWSStepFunctions.";
|
||||
private static final String CLOUDWATCH_TARGET_PREFIX = "GraniteServiceVersion20100801.";
|
||||
private static final String CLOUDWATCH_SERVICE_ID = "GraniteServiceVersion20100801";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RegionResolver regionResolver;
|
||||
private final DynamoDbJsonHandler dynamoDbJsonHandler;
|
||||
private final DynamoDbStreamsJsonHandler dynamoDbStreamsJsonHandler;
|
||||
private final SqsJsonHandler sqsJsonHandler;
|
||||
private final SnsJsonHandler snsJsonHandler;
|
||||
private final StepFunctionsJsonHandler sfnJsonHandler;
|
||||
private final CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler;
|
||||
|
||||
@Inject
|
||||
public AwsJsonController(ObjectMapper objectMapper, RegionResolver regionResolver,
|
||||
DynamoDbJsonHandler dynamoDbJsonHandler,
|
||||
DynamoDbStreamsJsonHandler dynamoDbStreamsJsonHandler,
|
||||
SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler,
|
||||
StepFunctionsJsonHandler sfnJsonHandler,
|
||||
CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.regionResolver = regionResolver;
|
||||
this.dynamoDbJsonHandler = dynamoDbJsonHandler;
|
||||
this.dynamoDbStreamsJsonHandler = dynamoDbStreamsJsonHandler;
|
||||
this.sqsJsonHandler = sqsJsonHandler;
|
||||
this.snsJsonHandler = snsJsonHandler;
|
||||
this.sfnJsonHandler = sfnJsonHandler;
|
||||
this.cloudWatchMetricsJsonHandler = cloudWatchMetricsJsonHandler;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Consumes("application/x-amz-json-1.0")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public Response handleJsonRequest(
|
||||
@HeaderParam("X-Amz-Target") String target,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
String body) {
|
||||
|
||||
if (target == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String prefix;
|
||||
String action;
|
||||
String serviceName;
|
||||
|
||||
if (target.startsWith(DYNAMODB_STREAMS_TARGET_PREFIX)) {
|
||||
prefix = DYNAMODB_STREAMS_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "DynamoDBStreams";
|
||||
} else if (target.startsWith(DYNAMODB_TARGET_PREFIX)) {
|
||||
prefix = DYNAMODB_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "DynamoDB";
|
||||
} else if (target.startsWith(SQS_TARGET_PREFIX)) {
|
||||
prefix = SQS_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "SQS";
|
||||
} else if (target.startsWith(SNS_TARGET_PREFIX)) {
|
||||
prefix = SNS_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "SNS";
|
||||
} else if (target.startsWith(STEPFUNCTIONS_TARGET_PREFIX)) {
|
||||
prefix = STEPFUNCTIONS_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "StepFunctions";
|
||||
} else if (target.startsWith(CLOUDWATCH_TARGET_PREFIX)) {
|
||||
prefix = CLOUDWATCH_TARGET_PREFIX;
|
||||
action = target.substring(prefix.length());
|
||||
serviceName = "CloudWatch";
|
||||
} else {
|
||||
return Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnknownOperationException",
|
||||
"Unknown operation: " + target))
|
||||
.build();
|
||||
}
|
||||
|
||||
LOG.debugv("{0} JSON action: {1}", serviceName, action);
|
||||
|
||||
try {
|
||||
JsonNode request = objectMapper.readTree(body);
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
|
||||
return switch (serviceName) {
|
||||
case "DynamoDB" -> dynamoDbJsonHandler.handle(action, request, region);
|
||||
case "DynamoDBStreams" -> dynamoDbStreamsJsonHandler.handle(action, request, region);
|
||||
case "SQS" -> sqsJsonHandler.handle(action, request, region);
|
||||
case "SNS" -> snsJsonHandler.handle(action, request, region);
|
||||
case "StepFunctions" -> sfnJsonHandler.handle(action, request, region);
|
||||
case "CloudWatch" -> cloudWatchMetricsJsonHandler.handle(action, request, region);
|
||||
default -> null;
|
||||
};
|
||||
} catch (AwsException e) {
|
||||
return Response.status(e.getHttpStatus())
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new AwsErrorResponse(e.getErrorCode(), e.getMessage()))
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error processing " + serviceName + " JSON request", e);
|
||||
return Response.status(500)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new AwsErrorResponse("InternalServerError", e.getMessage()))
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes a JsonNode to CBOR bytes, encoding fields named "Timestamp" with CBOR tag 1
|
||||
* as required by the smithy-rpc-v2-cbor protocol specification.
|
||||
*/
|
||||
private static byte[] nodeToSmithyCbor(JsonNode node) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
CBORFactory factory = (CBORFactory) CBOR_MAPPER.getFactory();
|
||||
try (CBORGenerator gen = factory.createGenerator(out)) {
|
||||
writeNodeToCbor(gen, node, null);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static void writeNodeToCbor(CBORGenerator gen, JsonNode node, String fieldName) throws Exception {
|
||||
if (node.isObject()) {
|
||||
gen.writeStartObject();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
gen.writeFieldName(entry.getKey());
|
||||
writeNodeToCbor(gen, entry.getValue(), entry.getKey());
|
||||
}
|
||||
gen.writeEndObject();
|
||||
} else if (node.isArray()) {
|
||||
gen.writeStartArray();
|
||||
for (JsonNode item : node) {
|
||||
writeNodeToCbor(gen, item, null);
|
||||
}
|
||||
gen.writeEndArray();
|
||||
} else if ("Timestamp".equals(fieldName) && node.isNumber()) {
|
||||
gen.writeTag(1);
|
||||
gen.writeNumber(node.longValue());
|
||||
} else if (node.isTextual()) {
|
||||
gen.writeString(node.textValue());
|
||||
} else if (node.isDouble() || node.isFloat()) {
|
||||
gen.writeNumber(node.doubleValue());
|
||||
} else if (node.isLong() || node.isInt()) {
|
||||
gen.writeNumber(node.longValue());
|
||||
} else if (node.isBoolean()) {
|
||||
gen.writeBoolean(node.booleanValue());
|
||||
} else if (node.isNull()) {
|
||||
gen.writeNull();
|
||||
} else {
|
||||
gen.writeString(node.asText());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles AWS smithy-rpc-v2-cbor protocol requests.
|
||||
* Go SDK CloudWatch v1.55.1+ sends to POST /service/{serviceId}/operation/{op}
|
||||
* with Content-Type: application/cbor and no X-Amz-Target header.
|
||||
*/
|
||||
@POST
|
||||
@Path("service/{serviceId}/operation/{operation}")
|
||||
@Consumes("application/cbor")
|
||||
@Produces("application/cbor")
|
||||
public Response handleSmithyRpcV2Cbor(
|
||||
@PathParam("serviceId") String serviceId,
|
||||
@PathParam("operation") String operation,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
byte[] body) {
|
||||
|
||||
if (!CLOUDWATCH_SERVICE_ID.equals(serviceId)) {
|
||||
return Response.status(404).build();
|
||||
}
|
||||
|
||||
LOG.debugv("CloudWatch RPC v2 CBOR action: {0}", operation);
|
||||
|
||||
try {
|
||||
JsonNode request = (body != null && body.length > 0)
|
||||
? CBOR_MAPPER.readTree(body)
|
||||
: objectMapper.createObjectNode();
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
|
||||
Response delegated = cloudWatchMetricsJsonHandler.handle(operation, request, region);
|
||||
byte[] cborBytes = nodeToSmithyCbor((JsonNode) delegated.getEntity());
|
||||
|
||||
return Response.status(delegated.getStatus())
|
||||
.header("Smithy-Protocol", "rpc-v2-cbor")
|
||||
.type("application/cbor")
|
||||
.entity(cborBytes)
|
||||
.build();
|
||||
} catch (AwsException e) {
|
||||
try {
|
||||
byte[] errBytes = CBOR_MAPPER.writeValueAsBytes(
|
||||
new AwsErrorResponse(e.getErrorCode(), e.getMessage()));
|
||||
return Response.status(e.getHttpStatus())
|
||||
.header("Smithy-Protocol", "rpc-v2-cbor")
|
||||
.type("application/cbor")
|
||||
.entity(errBytes)
|
||||
.build();
|
||||
} catch (Exception ex) {
|
||||
return Response.status(e.getHttpStatus()).build();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error processing CloudWatch CBOR request", e);
|
||||
return Response.status(500).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles AWS services that migrated to the smithy-rpc-v2-cbor protocol at root path.
|
||||
* Fallback handler for X-Amz-Target based routing with CBOR body.
|
||||
*/
|
||||
@POST
|
||||
@Consumes("application/cbor")
|
||||
@Produces("application/cbor")
|
||||
public Response handleCborRequest(
|
||||
@HeaderParam("X-Amz-Target") String target,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
byte[] body) {
|
||||
|
||||
if (target == null || !target.startsWith(CLOUDWATCH_TARGET_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String action = target.substring(CLOUDWATCH_TARGET_PREFIX.length());
|
||||
LOG.debugv("CloudWatch CBOR action: {0}", action);
|
||||
|
||||
try {
|
||||
JsonNode request = (body != null && body.length > 0)
|
||||
? CBOR_MAPPER.readTree(body)
|
||||
: objectMapper.createObjectNode();
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
|
||||
Response delegated = cloudWatchMetricsJsonHandler.handle(action, request, region);
|
||||
byte[] cborBytes = nodeToSmithyCbor((JsonNode) delegated.getEntity());
|
||||
|
||||
return Response.status(delegated.getStatus())
|
||||
.header("smithy-protocol", "rpc-v2-cbor")
|
||||
.type("application/cbor")
|
||||
.entity(cborBytes)
|
||||
.build();
|
||||
} catch (AwsException e) {
|
||||
try {
|
||||
byte[] errBytes = CBOR_MAPPER.writeValueAsBytes(
|
||||
new AwsErrorResponse(e.getErrorCode(), e.getMessage()));
|
||||
return Response.status(e.getHttpStatus())
|
||||
.header("smithy-protocol", "rpc-v2-cbor")
|
||||
.type("application/cbor")
|
||||
.entity(errBytes)
|
||||
.build();
|
||||
} catch (Exception ex) {
|
||||
return Response.status(e.getHttpStatus()).build();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error processing CloudWatch CBOR request", e);
|
||||
return Response.status(500).build();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
/**
|
||||
* Canonical XML namespace URIs for every AWS service that uses the Query (XML) protocol.
|
||||
* Use these constants instead of inline string literals in handlers.
|
||||
*/
|
||||
public final class AwsNamespaces {
|
||||
|
||||
public static final String SQS = "https://sqs.amazonaws.com/doc/2012-11-05/";
|
||||
public static final String SNS = "http://sns.amazonaws.com/doc/2010-03-31/";
|
||||
public static final String IAM = "https://iam.amazonaws.com/doc/2010-05-08/";
|
||||
public static final String STS = "https://sts.amazonaws.com/doc/2011-06-15/";
|
||||
public static final String RDS = "http://rds.amazonaws.com/doc/2014-10-31/";
|
||||
public static final String EC = "http://elasticache.amazonaws.com/doc/2015-02-02/";
|
||||
public static final String CW = "http://monitoring.amazonaws.com/doc/2010-08-01/";
|
||||
public static final String S3 = "http://s3.amazonaws.com/doc/2006-03-01/";
|
||||
|
||||
private AwsNamespaces() {}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsQueryHandler;
|
||||
import io.github.hectorvent.floci.services.elasticache.ElastiCacheQueryHandler;
|
||||
import io.github.hectorvent.floci.services.iam.IamQueryHandler;
|
||||
import io.github.hectorvent.floci.services.iam.StsQueryHandler;
|
||||
import io.github.hectorvent.floci.services.rds.RdsQueryHandler;
|
||||
import io.github.hectorvent.floci.services.sns.SnsQueryHandler;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsQueryHandler;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.HeaderParam;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Generic dispatcher for all AWS services that use the Query Protocol (form-encoded POST, XML response).
|
||||
* Routes requests to the appropriate service handler based on the service name extracted from the
|
||||
* Authorization header's credential scope, falling back to action-name matching when no auth header
|
||||
* is present.
|
||||
*
|
||||
* <p>Currently supported services:
|
||||
* <ul>
|
||||
* <li>SQS — form-encoded query protocol</li>
|
||||
* <li>SNS — form-encoded query protocol</li>
|
||||
* <li>IAM — form-encoded query protocol (global service)</li>
|
||||
* <li>STS — form-encoded query protocol (global service)</li>
|
||||
* </ul>
|
||||
*
|
||||
* @see AwsJsonController
|
||||
*/
|
||||
@Path("/")
|
||||
public class AwsQueryController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AwsQueryController.class);
|
||||
|
||||
// Extracts service name: Credential=AKID/20260227/us-east-1/iam/aws4_request → "iam"
|
||||
private static final Pattern SERVICE_PATTERN =
|
||||
Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
|
||||
|
||||
private static final Set<String> STS_ACTIONS = Set.of(
|
||||
"AssumeRole", "AssumeRoleWithWebIdentity", "AssumeRoleWithSAML",
|
||||
"GetCallerIdentity", "GetSessionToken", "GetFederationToken",
|
||||
"DecodeAuthorizationMessage"
|
||||
);
|
||||
|
||||
private static final Set<String> SNS_ACTIONS = Set.of(
|
||||
"CreateTopic", "DeleteTopic", "ListTopics", "GetTopicAttributes", "SetTopicAttributes",
|
||||
"Subscribe", "Unsubscribe", "ListSubscriptions", "ListSubscriptionsByTopic",
|
||||
"Publish", "PublishBatch", "TagResource", "UntagResource", "ListTagsForResource",
|
||||
"CreatePlatformApplication", "DeletePlatformApplication", "GetPlatformApplicationAttributes",
|
||||
"SetPlatformApplicationAttributes", "ListPlatformApplications",
|
||||
"CreatePlatformEndpoint", "DeleteEndpoint", "GetEndpointAttributes",
|
||||
"SetEndpointAttributes", "ListEndpointsByPlatformApplication",
|
||||
"CheckIfPhoneNumberIsOptedOut", "ListPhoneNumbersOptedOut",
|
||||
"OptInPhoneNumber", "SetSMSAttributes", "GetSMSAttributes",
|
||||
"GetSubscriptionAttributes", "SetSubscriptionAttributes", "ConfirmSubscription",
|
||||
"CreateSMSSandboxPhoneNumber", "DeleteSMSSandboxPhoneNumber",
|
||||
"GetSMSSandboxAccountStatus", "ListSMSSandboxPhoneNumbers",
|
||||
"VerifySMSSandboxPhoneNumber", "AddPermission", "RemovePermission"
|
||||
);
|
||||
|
||||
private static final Set<String> IAM_ACTIONS = Set.of(
|
||||
"CreateUser", "GetUser", "DeleteUser", "ListUsers", "UpdateUser",
|
||||
"CreateGroup", "GetGroup", "DeleteGroup", "ListGroups",
|
||||
"AddUserToGroup", "RemoveUserFromGroup", "ListGroupsForUser",
|
||||
"CreateRole", "GetRole", "DeleteRole", "ListRoles", "UpdateRole",
|
||||
"CreatePolicy", "GetPolicy", "DeletePolicy", "ListPolicies",
|
||||
"CreatePolicyVersion", "GetPolicyVersion", "DeletePolicyVersion",
|
||||
"ListPolicyVersions", "SetDefaultPolicyVersion",
|
||||
"AttachUserPolicy", "DetachUserPolicy", "ListAttachedUserPolicies",
|
||||
"AttachGroupPolicy", "DetachGroupPolicy", "ListAttachedGroupPolicies",
|
||||
"AttachRolePolicy", "DetachRolePolicy", "ListAttachedRolePolicies",
|
||||
"PutUserPolicy", "GetUserPolicy", "DeleteUserPolicy", "ListUserPolicies",
|
||||
"PutRolePolicy", "GetRolePolicy", "DeleteRolePolicy", "ListRolePolicies",
|
||||
"PutGroupPolicy", "GetGroupPolicy", "DeleteGroupPolicy", "ListGroupPolicies",
|
||||
"CreateAccessKey", "DeleteAccessKey", "ListAccessKeys", "UpdateAccessKey",
|
||||
"CreateInstanceProfile", "GetInstanceProfile", "DeleteInstanceProfile",
|
||||
"ListInstanceProfiles", "AddRoleToInstanceProfile",
|
||||
"RemoveRoleFromInstanceProfile", "ListInstanceProfilesForRole",
|
||||
"TagUser", "UntagUser", "ListUserTags",
|
||||
"TagRole", "UntagRole", "ListRoleTags",
|
||||
"TagPolicy", "UntagPolicy", "ListPolicyTags",
|
||||
"CreateLoginProfile", "GetLoginProfile", "DeleteLoginProfile", "UpdateLoginProfile",
|
||||
"GenerateCredentialReport", "GetCredentialReport",
|
||||
"GetAccountSummary", "GetAccountAuthorizationDetails"
|
||||
);
|
||||
|
||||
private final CloudFormationQueryHandler cloudFormationQueryHandler;
|
||||
private final ElastiCacheQueryHandler elastiCacheQueryHandler;
|
||||
private final RdsQueryHandler rdsQueryHandler;
|
||||
private final SqsQueryHandler sqsQueryHandler;
|
||||
private final SnsQueryHandler snsQueryHandler;
|
||||
private final IamQueryHandler iamQueryHandler;
|
||||
private final StsQueryHandler stsQueryHandler;
|
||||
private final CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public AwsQueryController(CloudFormationQueryHandler cloudFormationQueryHandler,
|
||||
ElastiCacheQueryHandler elastiCacheQueryHandler,
|
||||
RdsQueryHandler rdsQueryHandler,
|
||||
SqsQueryHandler sqsQueryHandler, SnsQueryHandler snsQueryHandler,
|
||||
IamQueryHandler iamQueryHandler, StsQueryHandler stsQueryHandler,
|
||||
CloudWatchMetricsQueryHandler cloudWatchMetricsQueryHandler,
|
||||
RegionResolver regionResolver) {
|
||||
this.cloudFormationQueryHandler = cloudFormationQueryHandler;
|
||||
this.elastiCacheQueryHandler = elastiCacheQueryHandler;
|
||||
this.rdsQueryHandler = rdsQueryHandler;
|
||||
this.sqsQueryHandler = sqsQueryHandler;
|
||||
this.snsQueryHandler = snsQueryHandler;
|
||||
this.iamQueryHandler = iamQueryHandler;
|
||||
this.stsQueryHandler = stsQueryHandler;
|
||||
this.cloudWatchMetricsQueryHandler = cloudWatchMetricsQueryHandler;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
@Produces(MediaType.APPLICATION_XML)
|
||||
public Response dispatch(
|
||||
@HeaderParam("Authorization") String authorization,
|
||||
@Context HttpHeaders httpHeaders,
|
||||
MultivaluedMap<String, String> formParams) {
|
||||
|
||||
String action = formParams.getFirst("Action");
|
||||
if (action == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String service = resolveService(authorization, action);
|
||||
LOG.debugv("Query protocol service={0} action={1}", service, action);
|
||||
|
||||
String region = regionResolver.resolveRegion(httpHeaders);
|
||||
|
||||
return switch (service) {
|
||||
case "sqs" -> sqsQueryHandler.handle(action, formParams, region);
|
||||
case "sns" -> snsQueryHandler.handle(action, formParams, region);
|
||||
case "iam" -> iamQueryHandler.handle(action, formParams);
|
||||
case "sts" -> stsQueryHandler.handle(action, formParams);
|
||||
case "elasticache" -> elastiCacheQueryHandler.handle(action, formParams);
|
||||
case "rds" -> rdsQueryHandler.handle(action, formParams);
|
||||
case "monitoring" -> cloudWatchMetricsQueryHandler.handle(action, formParams, region);
|
||||
case "cloudformation" -> cloudFormationQueryHandler.handle(action, formParams, region);
|
||||
default -> xmlErrorResponse("UnknownService",
|
||||
"Unknown or unsupported service: " + service, 400);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the target AWS service. Prefers the service name embedded in the
|
||||
* Authorization header credential scope. Falls back to action-name lookup when
|
||||
* the header is absent (e.g. raw HTTP testing without AWS SDK auth).
|
||||
*/
|
||||
private static final Set<String> ELASTICACHE_ACTIONS = Set.of(
|
||||
"ValidateIamAuthToken",
|
||||
"CreateReplicationGroup", "DescribeReplicationGroups", "DeleteReplicationGroup",
|
||||
"CreateUser", "DescribeUsers", "ModifyUser", "DeleteUser"
|
||||
);
|
||||
|
||||
private static final Set<String> CLOUDWATCH_ACTIONS = Set.of(
|
||||
"PutMetricData", "ListMetrics", "GetMetricStatistics", "GetMetricData"
|
||||
);
|
||||
|
||||
private static final Set<String> RDS_ACTIONS = Set.of(
|
||||
"CreateDBInstance", "DescribeDBInstances", "DeleteDBInstance",
|
||||
"ModifyDBInstance", "RebootDBInstance",
|
||||
"CreateDBCluster", "DescribeDBClusters", "DeleteDBCluster", "ModifyDBCluster",
|
||||
"CreateDBParameterGroup", "DescribeDBParameterGroups",
|
||||
"DeleteDBParameterGroup", "ModifyDBParameterGroup", "DescribeDBParameters"
|
||||
);
|
||||
|
||||
private static final Set<String> CLOUDFORMATION_ACTIONS = Set.of(
|
||||
"CreateStack", "DeleteStack", "UpdateStack", "DescribeStacks",
|
||||
"ListStacks", "GetTemplate", "ValidateTemplate",
|
||||
"CreateChangeSet", "DeleteChangeSet", "DescribeChangeSet", "ExecuteChangeSet", "ListChangeSets",
|
||||
"DescribeStackEvents", "DescribeStackResources", "ListStackResources", "DescribeStackResource",
|
||||
"SetStackPolicy", "GetStackPolicy", "ListStackSets", "DescribeStackSet", "CreateStackSet"
|
||||
);
|
||||
|
||||
private static final Set<String> QUERY_PROTOCOL_SERVICES = Set.of("sqs", "sns", "iam", "sts", "elasticache", "rds", "monitoring", "cloudformation");
|
||||
|
||||
private String resolveService(String authorization, String action) {
|
||||
if (authorization != null && !authorization.isEmpty()) {
|
||||
Matcher m = SERVICE_PATTERN.matcher(authorization);
|
||||
if (m.find()) {
|
||||
String svc = m.group(1).toLowerCase();
|
||||
if (QUERY_PROTOCOL_SERVICES.contains(svc)) {
|
||||
return svc;
|
||||
}
|
||||
}
|
||||
}
|
||||
return inferServiceFromAction(action);
|
||||
}
|
||||
|
||||
private String inferServiceFromAction(String action) {
|
||||
if (STS_ACTIONS.contains(action)) {
|
||||
return "sts";
|
||||
}
|
||||
if (IAM_ACTIONS.contains(action)) {
|
||||
return "iam";
|
||||
}
|
||||
if (SNS_ACTIONS.contains(action)) {
|
||||
return "sns";
|
||||
}
|
||||
if (ELASTICACHE_ACTIONS.contains(action)) {
|
||||
return "elasticache";
|
||||
}
|
||||
if (RDS_ACTIONS.contains(action)) {
|
||||
return "rds";
|
||||
}
|
||||
if (CLOUDWATCH_ACTIONS.contains(action)) {
|
||||
return "monitoring";
|
||||
}
|
||||
if (CLOUDFORMATION_ACTIONS.contains(action)) {
|
||||
return "cloudformation";
|
||||
}
|
||||
// SQS actions are numerous and not enumerated — fall back to sqs only for
|
||||
// requests that arrived without an Authorization header (raw/test clients)
|
||||
return "sqs";
|
||||
}
|
||||
|
||||
private Response xmlErrorResponse(String code, String message, int status) {
|
||||
String xml = new XmlBuilder()
|
||||
.start("ErrorResponse")
|
||||
.start("Error")
|
||||
.elem("Type", "Sender")
|
||||
.elem("Code", code)
|
||||
.elem("Message", message)
|
||||
.end("Error")
|
||||
.elem("RequestId", UUID.randomUUID().toString())
|
||||
.end("ErrorResponse")
|
||||
.build();
|
||||
return Response.status(status).entity(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Shared helpers for building AWS Query-protocol (form-encoded POST → XML) responses.
|
||||
*
|
||||
* <p>Every Query-protocol service handler should call these methods instead of
|
||||
* hand-rolling its own {@code ResponseMetadata}, envelope, or error skeleton.
|
||||
*
|
||||
* <h2>Usage</h2>
|
||||
* <pre>{@code
|
||||
* // Simple envelope
|
||||
* return Response.ok(AwsQueryResponse.envelope("CreateQueue", null, resultXml)).build();
|
||||
*
|
||||
* // Namespaced envelope (e.g. SNS)
|
||||
* return Response.ok(AwsQueryResponse.envelope("CreateTopic", AwsNamespaces.SNS, resultXml)).build();
|
||||
*
|
||||
* // Error
|
||||
* return AwsQueryResponse.error("InvalidParameterValue", "Queue name too long", null, 400);
|
||||
* }</pre>
|
||||
*/
|
||||
public final class AwsQueryResponse {
|
||||
|
||||
private AwsQueryResponse() {}
|
||||
|
||||
/**
|
||||
* Produces a {@code <ResponseMetadata>} block with a random request ID:
|
||||
* <pre>{@code
|
||||
* <ResponseMetadata><RequestId>UUID</RequestId></ResponseMetadata>
|
||||
* }</pre>
|
||||
*/
|
||||
public static String responseMetadata() {
|
||||
return new XmlBuilder()
|
||||
.start("ResponseMetadata")
|
||||
.elem("RequestId", UUID.randomUUID().toString())
|
||||
.end("ResponseMetadata")
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a result fragment in the standard Query-protocol outer envelope:
|
||||
* <pre>{@code
|
||||
* <{action}Response xmlns="{xmlns}">
|
||||
* <{action}Result>{result}</{action}Result>
|
||||
* <ResponseMetadata><RequestId>UUID</RequestId></ResponseMetadata>
|
||||
* </{action}Response>
|
||||
* }</pre>
|
||||
*
|
||||
* @param action the AWS action name (e.g. {@code "CreateQueue"})
|
||||
* @param xmlns the XML namespace URI, or {@code null} for namespace-free responses (e.g. SQS)
|
||||
* @param result the inner XML fragment placed inside the Result element
|
||||
*/
|
||||
public static String envelope(String action, String xmlns, String result) {
|
||||
return new XmlBuilder()
|
||||
.start(action + "Response", xmlns)
|
||||
.start(action + "Result")
|
||||
.raw(result)
|
||||
.end(action + "Result")
|
||||
.raw(responseMetadata())
|
||||
.end(action + "Response")
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as {@link #envelope} but for actions whose response element does not include
|
||||
* a {@code Result} child (e.g. {@code DeleteQueue}, {@code DeleteTopic}).
|
||||
*/
|
||||
public static String envelopeNoResult(String action, String xmlns) {
|
||||
return new XmlBuilder()
|
||||
.start(action + "Response", xmlns)
|
||||
.raw(responseMetadata())
|
||||
.end(action + "Response")
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a Query-protocol XML error response and returns a JAX-RS {@link Response}.
|
||||
*
|
||||
* <pre>{@code
|
||||
* <ErrorResponse xmlns="{xmlns}">
|
||||
* <Error>
|
||||
* <Type>Sender</Type>
|
||||
* <Code>{code}</Code>
|
||||
* <Message>{message}</Message>
|
||||
* </Error>
|
||||
* <RequestId>UUID</RequestId>
|
||||
* </ErrorResponse>
|
||||
* }</pre>
|
||||
*
|
||||
* @param xmlns the namespace URI, or {@code null} for namespace-free error responses (e.g. SQS)
|
||||
*/
|
||||
public static Response error(String code, String message, String xmlns, int status) {
|
||||
String xml = new XmlBuilder()
|
||||
.start("ErrorResponse", xmlns)
|
||||
.start("Error")
|
||||
.elem("Type", "Sender")
|
||||
.elem("Code", code)
|
||||
.elem("Message", message)
|
||||
.end("Error")
|
||||
.raw(responseMetadata())
|
||||
.end("ErrorResponse")
|
||||
.build();
|
||||
return Response.status(status).entity(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RegionResolver {
|
||||
|
||||
// Matches: Credential=AKID/20260215/us-west-2/s3/aws4_request
|
||||
private static final Pattern CREDENTIAL_REGION_PATTERN =
|
||||
Pattern.compile("Credential=\\S+/\\d{8}/([^/]+)/");
|
||||
|
||||
private final String defaultRegion;
|
||||
private final String defaultAccountId;
|
||||
|
||||
@Inject
|
||||
public RegionResolver(EmulatorConfig config) {
|
||||
this(config.defaultRegion(), config.defaultAccountId());
|
||||
}
|
||||
|
||||
public RegionResolver(String defaultRegion, String defaultAccountId) {
|
||||
this.defaultRegion = defaultRegion;
|
||||
this.defaultAccountId = defaultAccountId;
|
||||
}
|
||||
|
||||
public String resolveRegion(HttpHeaders headers) {
|
||||
if (headers == null) {
|
||||
return defaultRegion;
|
||||
}
|
||||
String auth = headers.getHeaderString("Authorization");
|
||||
if (auth == null || auth.isEmpty()) {
|
||||
return defaultRegion;
|
||||
}
|
||||
Matcher matcher = CREDENTIAL_REGION_PATTERN.matcher(auth);
|
||||
if (matcher.find()) {
|
||||
return matcher.group(1);
|
||||
}
|
||||
return defaultRegion;
|
||||
}
|
||||
|
||||
public String getDefaultRegion() {
|
||||
return defaultRegion;
|
||||
}
|
||||
|
||||
public String getAccountId() {
|
||||
return defaultAccountId;
|
||||
}
|
||||
|
||||
public String buildArn(String service, String region, String resource) {
|
||||
return "arn:aws:" + service + ":" + region + ":" + defaultAccountId + ":" + resource;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Provider
|
||||
public class ServiceEnabledFilter implements ContainerRequestFilter {
|
||||
|
||||
private static final Pattern AUTH_SERVICE_PATTERN =
|
||||
Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
|
||||
|
||||
private final ServiceRegistry serviceRegistry;
|
||||
|
||||
@Inject
|
||||
public ServiceEnabledFilter(ServiceRegistry serviceRegistry) {
|
||||
this.serviceRegistry = serviceRegistry;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext ctx) {
|
||||
String serviceKey = resolveServiceKey(ctx);
|
||||
if (serviceKey == null) {
|
||||
return;
|
||||
}
|
||||
if (!serviceRegistry.isServiceEnabled(serviceKey)) {
|
||||
ctx.abortWith(disabledResponse(ctx, serviceKey));
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveServiceKey(ContainerRequestContext ctx) {
|
||||
String target = ctx.getHeaderString("X-Amz-Target");
|
||||
if (target != null) {
|
||||
return serviceKeyFromTarget(target);
|
||||
}
|
||||
|
||||
String auth = ctx.getHeaderString("Authorization");
|
||||
if (auth != null) {
|
||||
Matcher m = AUTH_SERVICE_PATTERN.matcher(auth);
|
||||
if (m.find()) {
|
||||
return mapCredentialScope(m.group(1).toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private String serviceKeyFromTarget(String target) {
|
||||
if (target.startsWith("AmazonSSM.")) return "ssm";
|
||||
if (target.startsWith("AWSEvents.")) return "events";
|
||||
if (target.startsWith("Logs_20140328.")) return "logs";
|
||||
if (target.startsWith("secretsmanager.")) return "secretsmanager";
|
||||
if (target.startsWith("Kinesis_20131202.")) return "kinesis";
|
||||
if (target.startsWith("AmazonApiGatewayV2.")) return "apigatewayv2";
|
||||
if (target.startsWith("TrentService.")) return "kms";
|
||||
if (target.startsWith("AWSCognitoIdentityProviderService.")) return "cognito-idp";
|
||||
if (target.startsWith("DynamoDB_20120810.") || target.startsWith("DynamoDBStreams_20120810.")) return "dynamodb";
|
||||
if (target.startsWith("AmazonSQS.")) return "sqs";
|
||||
if (target.startsWith("SNS_20100331.")) return "sns";
|
||||
if (target.startsWith("AWSStepFunctions.")) return "states";
|
||||
if (target.startsWith("GraniteServiceVersion20100801.")) return "monitoring";
|
||||
return null;
|
||||
}
|
||||
|
||||
private String mapCredentialScope(String scope) {
|
||||
return switch (scope) {
|
||||
case "execute-api" -> "apigateway";
|
||||
default -> scope;
|
||||
};
|
||||
}
|
||||
|
||||
private Response disabledResponse(ContainerRequestContext ctx, String serviceKey) {
|
||||
String message = "Service " + serviceKey + " is not enabled.";
|
||||
String target = ctx.getHeaderString("X-Amz-Target");
|
||||
String contentType = ctx.getMediaType() != null ? ctx.getMediaType().toString() : "";
|
||||
|
||||
if (target != null || contentType.contains("json")) {
|
||||
return Response.status(400)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.entity(new AwsErrorResponse("ServiceNotAvailableException", message))
|
||||
.build();
|
||||
}
|
||||
|
||||
String xml = new XmlBuilder()
|
||||
.start("ErrorResponse")
|
||||
.start("Error")
|
||||
.elem("Type", "Sender")
|
||||
.elem("Code", "ServiceNotAvailableException")
|
||||
.elem("Message", message)
|
||||
.end("Error")
|
||||
.elem("RequestId", java.util.UUID.randomUUID().toString())
|
||||
.end("ErrorResponse")
|
||||
.build();
|
||||
return Response.status(400).entity(xml).type(MediaType.APPLICATION_XML).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Registry of enabled AWS services based on configuration.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ServiceRegistry {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ServiceRegistry.class);
|
||||
|
||||
private final EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
public ServiceRegistry(EmulatorConfig config) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public boolean isServiceEnabled(String serviceName) {
|
||||
return switch (serviceName) {
|
||||
case "ssm" -> config.services().ssm().enabled();
|
||||
case "sqs" -> config.services().sqs().enabled();
|
||||
case "s3" -> config.services().s3().enabled();
|
||||
case "dynamodb" -> config.services().dynamodb().enabled();
|
||||
case "sns" -> config.services().sns().enabled();
|
||||
case "lambda" -> config.services().lambda().enabled();
|
||||
case "apigateway" -> config.services().apigateway().enabled();
|
||||
case "iam", "sts" -> config.services().iam().enabled();
|
||||
case "elasticache" -> config.services().elasticache().enabled();
|
||||
case "rds" -> config.services().rds().enabled();
|
||||
case "events" -> config.services().eventbridge().enabled();
|
||||
case "logs" -> config.services().cloudwatchlogs().enabled();
|
||||
case "monitoring" -> config.services().cloudwatchmetrics().enabled();
|
||||
case "secretsmanager" -> config.services().secretsmanager().enabled();
|
||||
case "apigatewayv2" -> config.services().apigatewayv2().enabled();
|
||||
case "kinesis" -> config.services().kinesis().enabled();
|
||||
case "kms" -> config.services().kms().enabled();
|
||||
case "cognito-idp" -> config.services().cognito().enabled();
|
||||
case "states" -> config.services().stepfunctions().enabled();
|
||||
case "cloudformation" -> config.services().cloudformation().enabled();
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
|
||||
public List<String> getEnabledServices() {
|
||||
List<String> enabled = new ArrayList<>();
|
||||
if (config.services().ssm().enabled()) enabled.add("ssm");
|
||||
if (config.services().sqs().enabled()) enabled.add("sqs");
|
||||
if (config.services().s3().enabled()) enabled.add("s3");
|
||||
if (config.services().dynamodb().enabled()) enabled.add("dynamodb");
|
||||
if (config.services().sns().enabled()) enabled.add("sns");
|
||||
if (config.services().lambda().enabled()) enabled.add("lambda");
|
||||
if (config.services().apigateway().enabled()) enabled.add("apigateway");
|
||||
if (config.services().iam().enabled()) enabled.add("iam");
|
||||
if (config.services().elasticache().enabled()) enabled.add("elasticache");
|
||||
if (config.services().rds().enabled()) enabled.add("rds");
|
||||
if (config.services().eventbridge().enabled()) enabled.add("events");
|
||||
if (config.services().cloudwatchlogs().enabled()) enabled.add("logs");
|
||||
if (config.services().cloudwatchmetrics().enabled()) enabled.add("monitoring");
|
||||
if (config.services().secretsmanager().enabled()) enabled.add("secretsmanager");
|
||||
if (config.services().apigatewayv2().enabled()) enabled.add("apigatewayv2");
|
||||
if (config.services().kinesis().enabled()) enabled.add("kinesis");
|
||||
if (config.services().kms().enabled()) enabled.add("kms");
|
||||
if (config.services().cognito().enabled()) enabled.add("cognito-idp");
|
||||
if (config.services().stepfunctions().enabled()) enabled.add("states");
|
||||
if (config.services().cloudformation().enabled()) enabled.add("cloudformation");
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void logEnabledServices() {
|
||||
LOG.infov("Enabled services: {0}", getEnabledServices());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
/**
|
||||
* Fluent, allocation-efficient XML builder backed by a plain {@link StringBuilder}.
|
||||
*
|
||||
* <p>All content written via {@link #elem} and {@link #start} is automatically escaped.
|
||||
* Pre-built XML fragments can be injected without re-escaping via {@link #raw}.
|
||||
*
|
||||
* <pre>{@code
|
||||
* String xml = new XmlBuilder()
|
||||
* .start("CreateQueueResponse")
|
||||
* .start("CreateQueueResult")
|
||||
* .elem("QueueUrl", queue.getQueueUrl())
|
||||
* .end("CreateQueueResult")
|
||||
* .raw(AwsQueryResponse.responseMetadata())
|
||||
* .end("CreateQueueResponse")
|
||||
* .build();
|
||||
* }</pre>
|
||||
*/
|
||||
public final class XmlBuilder {
|
||||
|
||||
private final StringBuilder sb = new StringBuilder();
|
||||
|
||||
/** Opens {@code <element xmlns="xmlns">}. Omits the xmlns attribute when {@code xmlns} is null. */
|
||||
public XmlBuilder start(String element, String xmlns) {
|
||||
sb.append('<').append(element);
|
||||
if (xmlns != null) {
|
||||
sb.append(" xmlns=\"").append(xmlns).append('"');
|
||||
}
|
||||
sb.append('>');
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Opens {@code <element>} without a namespace. */
|
||||
public XmlBuilder start(String element) {
|
||||
return start(element, null);
|
||||
}
|
||||
|
||||
/** Appends {@code </element>}. */
|
||||
public XmlBuilder end(String element) {
|
||||
sb.append("</").append(element).append('>');
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends {@code <name>escapedValue</name>}.
|
||||
* Skips the element entirely when {@code value} is {@code null}.
|
||||
*/
|
||||
public XmlBuilder elem(String name, String value) {
|
||||
if (value == null) {
|
||||
return this;
|
||||
}
|
||||
sb.append('<').append(name).append('>')
|
||||
.append(escape(value))
|
||||
.append("</").append(name).append('>');
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Convenience overload — converts {@code long} to string. */
|
||||
public XmlBuilder elem(String name, long value) {
|
||||
return elem(name, String.valueOf(value));
|
||||
}
|
||||
|
||||
/** Convenience overload — converts {@code boolean} to string. */
|
||||
public XmlBuilder elem(String name, boolean value) {
|
||||
return elem(name, String.valueOf(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a pre-built XML fragment verbatim, without escaping.
|
||||
* The caller is responsible for correctness of the fragment.
|
||||
*/
|
||||
public XmlBuilder raw(String fragment) {
|
||||
if (fragment != null) {
|
||||
sb.append(fragment);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Returns the accumulated XML string. */
|
||||
public String build() {
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes the five XML special characters: {@code & < > " '}.
|
||||
* Returns an empty string for null or empty input.
|
||||
*/
|
||||
public static String escape(String s) {
|
||||
if (s == null || s.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder out = null;
|
||||
int len = s.length();
|
||||
for (int i = 0; i < len; i++) {
|
||||
char c = s.charAt(i);
|
||||
String replacement = switch (c) {
|
||||
case '&' -> "&";
|
||||
case '<' -> "<";
|
||||
case '>' -> ">";
|
||||
case '"' -> """;
|
||||
case '\'' -> "'";
|
||||
default -> null;
|
||||
};
|
||||
if (replacement != null) {
|
||||
if (out == null) {
|
||||
out = new StringBuilder(len + 8);
|
||||
out.append(s, 0, i);
|
||||
}
|
||||
out.append(replacement);
|
||||
} else if (out != null) {
|
||||
out.append(c);
|
||||
}
|
||||
}
|
||||
return out != null ? out.toString() : s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import javax.xml.stream.XMLInputFactory;
|
||||
import javax.xml.stream.XMLStreamConstants;
|
||||
import javax.xml.stream.XMLStreamException;
|
||||
import javax.xml.stream.XMLStreamReader;
|
||||
import java.io.StringReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Lightweight StAX-based helpers for parsing XML request bodies.
|
||||
*
|
||||
* <p>Uses {@code javax.xml.stream} (part of the JDK — no extra dependency).
|
||||
* Namespace prefixes are ignored so that both plain {@code <Key>} and
|
||||
* namespace-qualified {@code <s3:Key>} elements match by local name.
|
||||
* Handles whitespace variations and CDATA sections correctly.
|
||||
*
|
||||
* <p>All methods silently return empty collections on malformed input so that
|
||||
* callers receive the same result they would have from a non-matching regex.
|
||||
*/
|
||||
public final class XmlParser {
|
||||
|
||||
private static final XMLInputFactory FACTORY;
|
||||
|
||||
static {
|
||||
FACTORY = XMLInputFactory.newInstance();
|
||||
FACTORY.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
|
||||
FACTORY.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
|
||||
FACTORY.setProperty(XMLInputFactory.SUPPORT_DTD, false);
|
||||
}
|
||||
|
||||
private XmlParser() {}
|
||||
|
||||
/**
|
||||
* Extracts the text content of every element whose local name matches {@code elementName}.
|
||||
*
|
||||
* <pre>{@code
|
||||
* List<String> keys = XmlParser.extractAll(body, "Key");
|
||||
* }</pre>
|
||||
*/
|
||||
public static List<String> extractAll(String xml, String elementName) {
|
||||
List<String> result = new ArrayList<>();
|
||||
if (xml == null || xml.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
try {
|
||||
XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
|
||||
while (r.hasNext()) {
|
||||
int event = r.next();
|
||||
if (event == XMLStreamConstants.START_ELEMENT
|
||||
&& elementName.equals(r.getLocalName())) {
|
||||
result.add(r.getElementText());
|
||||
}
|
||||
}
|
||||
r.close();
|
||||
} catch (XMLStreamException ignored) {}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the text content of the first element matching {@code elementName},
|
||||
* or {@code defaultValue} if no such element exists.
|
||||
*
|
||||
* <pre>{@code
|
||||
* String mode = XmlParser.extractFirst(body, "Mode", null);
|
||||
* }</pre>
|
||||
*/
|
||||
public static String extractFirst(String xml, String elementName, String defaultValue) {
|
||||
List<String> all = extractAll(xml, elementName);
|
||||
return all.isEmpty() ? defaultValue : all.get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} if the document contains at least one element with the given
|
||||
* local name whose text is equal to {@code value} (case-sensitive).
|
||||
*
|
||||
* <pre>{@code
|
||||
* boolean quiet = XmlParser.containsValue(body, "Quiet", "true");
|
||||
* }</pre>
|
||||
*/
|
||||
public static boolean containsValue(String xml, String elementName, String value) {
|
||||
return extractAll(xml, elementName).stream().anyMatch(value::equals);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts sibling key/value pairs from every {@code parentElement} block.
|
||||
*
|
||||
* <p>Example — parses {@code <Tag><Key>env</Key><Value>prod</Value></Tag>}:
|
||||
* <pre>{@code
|
||||
* Map<String,String> tags = XmlParser.extractPairs(body, "Tag", "Key", "Value");
|
||||
* }</pre>
|
||||
*
|
||||
* Insertion order is preserved (backed by {@link LinkedHashMap}).
|
||||
*/
|
||||
public static Map<String, String> extractPairs(String xml, String parentElement,
|
||||
String keyElement, String valueElement) {
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
if (xml == null || xml.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
try {
|
||||
XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
|
||||
String pendingKey = null;
|
||||
boolean inParent = false;
|
||||
while (r.hasNext()) {
|
||||
int event = r.next();
|
||||
if (event == XMLStreamConstants.START_ELEMENT) {
|
||||
String local = r.getLocalName();
|
||||
if (parentElement.equals(local)) {
|
||||
inParent = true;
|
||||
pendingKey = null;
|
||||
} else if (inParent && keyElement.equals(local)) {
|
||||
pendingKey = r.getElementText();
|
||||
} else if (inParent && valueElement.equals(local) && pendingKey != null) {
|
||||
result.put(pendingKey, r.getElementText());
|
||||
pendingKey = null;
|
||||
}
|
||||
} else if (event == XMLStreamConstants.END_ELEMENT) {
|
||||
if (parentElement.equals(r.getLocalName())) {
|
||||
inParent = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
r.close();
|
||||
} catch (XMLStreamException ignored) {}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts every group of elements nested inside a repeating {@code parentElement},
|
||||
* returning each group as a {@code Map<localName, List<text>>}.
|
||||
*
|
||||
* <p>Allows for repeated child elements with the same name (e.g. multiple {@code <Event>}
|
||||
* tags inside a single {@code <QueueConfiguration>}).
|
||||
*/
|
||||
public static List<Map<String, List<String>>> extractGroupsMulti(String xml, String parentElement) {
|
||||
List<Map<String, List<String>>> result = new ArrayList<>();
|
||||
if (xml == null || xml.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
try {
|
||||
XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
|
||||
Map<String, List<String>> current = null;
|
||||
int depth = 0;
|
||||
while (r.hasNext()) {
|
||||
int event = r.next();
|
||||
if (event == XMLStreamConstants.START_ELEMENT) {
|
||||
String local = r.getLocalName();
|
||||
if (parentElement.equals(local)) {
|
||||
current = new LinkedHashMap<>();
|
||||
depth = 1;
|
||||
} else if (current != null && depth == 1) {
|
||||
String text = r.getElementText();
|
||||
current.computeIfAbsent(local, k -> new ArrayList<>()).add(text);
|
||||
} else if (current != null) {
|
||||
depth++;
|
||||
}
|
||||
} else if (event == XMLStreamConstants.END_ELEMENT) {
|
||||
if (current != null && parentElement.equals(r.getLocalName())) {
|
||||
result.add(current);
|
||||
current = null;
|
||||
depth = 0;
|
||||
} else if (current != null) {
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
}
|
||||
r.close();
|
||||
} catch (XMLStreamException ignored) {}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts every group of elements nested inside a repeating {@code parentElement},
|
||||
* returning each group as a {@code Map<localName, text>}.
|
||||
*
|
||||
* <p>Useful for notification-configuration blocks that contain multiple fields:
|
||||
* <pre>{@code
|
||||
* List<Map<String,String>> configs =
|
||||
* XmlParser.extractGroups(body, "QueueConfiguration");
|
||||
* // configs.get(0).get("QueueArn") → "arn:aws:sqs:..."
|
||||
* }</pre>
|
||||
*/
|
||||
public static List<Map<String, String>> extractGroups(String xml, String parentElement) {
|
||||
List<Map<String, String>> result = new ArrayList<>();
|
||||
if (xml == null || xml.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
try {
|
||||
XMLStreamReader r = FACTORY.createXMLStreamReader(new StringReader(xml));
|
||||
Map<String, String> current = null;
|
||||
int depth = 0;
|
||||
while (r.hasNext()) {
|
||||
int event = r.next();
|
||||
if (event == XMLStreamConstants.START_ELEMENT) {
|
||||
String local = r.getLocalName();
|
||||
if (parentElement.equals(local)) {
|
||||
current = new LinkedHashMap<>();
|
||||
depth = 1;
|
||||
} else if (current != null && depth == 1) {
|
||||
String text = r.getElementText();
|
||||
current.put(local, text);
|
||||
} else if (current != null) {
|
||||
depth++;
|
||||
}
|
||||
} else if (event == XMLStreamConstants.END_ELEMENT) {
|
||||
if (current != null && parentElement.equals(r.getLocalName())) {
|
||||
result.add(current);
|
||||
current = null;
|
||||
depth = 0;
|
||||
} else if (current != null) {
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
}
|
||||
r.close();
|
||||
} catch (XMLStreamException ignored) {}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.core.DefaultDockerClientConfig;
|
||||
import com.github.dockerjava.core.DockerClientImpl;
|
||||
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Produces;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* CDI producer for the DockerClient singleton bean.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class DockerClientProducer {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(DockerClientProducer.class);
|
||||
|
||||
private final EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
public DockerClientProducer(EmulatorConfig config) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
@Produces
|
||||
@ApplicationScoped
|
||||
public DockerClient dockerClient() {
|
||||
String dockerHost = config.services().lambda().dockerHost();
|
||||
LOG.infov("Creating DockerClient for host: {0}", dockerHost);
|
||||
|
||||
DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
|
||||
.withDockerHost(dockerHost)
|
||||
.build();
|
||||
|
||||
ApacheDockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
|
||||
.dockerHost(clientConfig.getDockerHost())
|
||||
.maxConnections(100)
|
||||
.connectionTimeout(Duration.ofSeconds(30))
|
||||
.responseTimeout(Duration.ofMinutes(5))
|
||||
.build();
|
||||
|
||||
return DockerClientImpl.getInstance(clientConfig, httpClient);
|
||||
}
|
||||
}
|
||||
+683
@@ -0,0 +1,683 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* Registers all docker-java classes for GraalVM native image reflection.
|
||||
* Jackson needs reflective access to model classes when deserializing Docker API responses.
|
||||
*/
|
||||
@RegisterForReflection(classNames = {
|
||||
"com.github.dockerjava.api.DockerClient",
|
||||
"com.github.dockerjava.api.DockerClientDelegate",
|
||||
"com.github.dockerjava.api.async.ResultCallback",
|
||||
"com.github.dockerjava.api.async.ResultCallback$Adapter",
|
||||
"com.github.dockerjava.api.async.ResultCallbackTemplate",
|
||||
"com.github.dockerjava.api.command.AsyncDockerCmd",
|
||||
"com.github.dockerjava.api.command.AttachContainerCmd",
|
||||
"com.github.dockerjava.api.command.AttachContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.AuthCmd",
|
||||
"com.github.dockerjava.api.command.AuthCmd$Exec",
|
||||
"com.github.dockerjava.api.command.BuildImageCmd",
|
||||
"com.github.dockerjava.api.command.BuildImageCmd$Exec",
|
||||
"com.github.dockerjava.api.command.BuildImageResultCallback",
|
||||
"com.github.dockerjava.api.command.CommitCmd",
|
||||
"com.github.dockerjava.api.command.CommitCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ConnectToNetworkCmd",
|
||||
"com.github.dockerjava.api.command.ConnectToNetworkCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ContainerDiffCmd",
|
||||
"com.github.dockerjava.api.command.ContainerDiffCmd$Exec",
|
||||
"com.github.dockerjava.api.command.CopyArchiveFromContainerCmd",
|
||||
"com.github.dockerjava.api.command.CopyArchiveFromContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.CopyArchiveToContainerCmd",
|
||||
"com.github.dockerjava.api.command.CopyArchiveToContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.CopyFileFromContainerCmd",
|
||||
"com.github.dockerjava.api.command.CopyFileFromContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.CreateConfigCmd",
|
||||
"com.github.dockerjava.api.command.CreateConfigCmd$Exec",
|
||||
"com.github.dockerjava.api.command.CreateConfigResponse",
|
||||
"com.github.dockerjava.api.command.CreateContainerCmd",
|
||||
"com.github.dockerjava.api.command.CreateContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.CreateContainerResponse",
|
||||
"com.github.dockerjava.api.command.CreateImageCmd",
|
||||
"com.github.dockerjava.api.command.CreateImageCmd$Exec",
|
||||
"com.github.dockerjava.api.command.CreateImageResponse",
|
||||
"com.github.dockerjava.api.command.CreateNetworkCmd",
|
||||
"com.github.dockerjava.api.command.CreateNetworkCmd$Exec",
|
||||
"com.github.dockerjava.api.command.CreateNetworkResponse",
|
||||
"com.github.dockerjava.api.command.CreateSecretCmd",
|
||||
"com.github.dockerjava.api.command.CreateSecretCmd$Exec",
|
||||
"com.github.dockerjava.api.command.CreateSecretResponse",
|
||||
"com.github.dockerjava.api.command.CreateServiceCmd",
|
||||
"com.github.dockerjava.api.command.CreateServiceCmd$Exec",
|
||||
"com.github.dockerjava.api.command.CreateServiceResponse",
|
||||
"com.github.dockerjava.api.command.CreateVolumeCmd",
|
||||
"com.github.dockerjava.api.command.CreateVolumeCmd$Exec",
|
||||
"com.github.dockerjava.api.command.CreateVolumeResponse",
|
||||
"com.github.dockerjava.api.command.DelegatingDockerCmdExecFactory",
|
||||
"com.github.dockerjava.api.command.DisconnectFromNetworkCmd",
|
||||
"com.github.dockerjava.api.command.DisconnectFromNetworkCmd$Exec",
|
||||
"com.github.dockerjava.api.command.DockerCmd",
|
||||
"com.github.dockerjava.api.command.DockerCmdAsyncExec",
|
||||
"com.github.dockerjava.api.command.DockerCmdExecFactory",
|
||||
"com.github.dockerjava.api.command.DockerCmdSyncExec",
|
||||
"com.github.dockerjava.api.command.EventsCmd",
|
||||
"com.github.dockerjava.api.command.EventsCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ExecCreateCmd",
|
||||
"com.github.dockerjava.api.command.ExecCreateCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ExecCreateCmdResponse",
|
||||
"com.github.dockerjava.api.command.ExecStartCmd",
|
||||
"com.github.dockerjava.api.command.ExecStartCmd$Exec",
|
||||
"com.github.dockerjava.api.command.GraphData",
|
||||
"com.github.dockerjava.api.command.GraphDriver",
|
||||
"com.github.dockerjava.api.command.HealthState",
|
||||
"com.github.dockerjava.api.command.HealthStateLog",
|
||||
"com.github.dockerjava.api.command.InfoCmd",
|
||||
"com.github.dockerjava.api.command.InfoCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InitializeSwarmCmd",
|
||||
"com.github.dockerjava.api.command.InitializeSwarmCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InspectConfigCmd",
|
||||
"com.github.dockerjava.api.command.InspectConfigCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InspectContainerCmd",
|
||||
"com.github.dockerjava.api.command.InspectContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InspectContainerResponse",
|
||||
"com.github.dockerjava.api.command.InspectContainerResponse$ContainerState",
|
||||
"com.github.dockerjava.api.command.InspectContainerResponse$Mount",
|
||||
"com.github.dockerjava.api.command.InspectContainerResponse$Node",
|
||||
"com.github.dockerjava.api.command.InspectExecCmd",
|
||||
"com.github.dockerjava.api.command.InspectExecCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InspectExecResponse",
|
||||
"com.github.dockerjava.api.command.InspectExecResponse$Container",
|
||||
"com.github.dockerjava.api.command.InspectExecResponse$ProcessConfig",
|
||||
"com.github.dockerjava.api.command.InspectImageCmd",
|
||||
"com.github.dockerjava.api.command.InspectImageCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InspectImageResponse",
|
||||
"com.github.dockerjava.api.command.InspectNetworkCmd",
|
||||
"com.github.dockerjava.api.command.InspectNetworkCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InspectServiceCmd",
|
||||
"com.github.dockerjava.api.command.InspectServiceCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InspectSwarmCmd",
|
||||
"com.github.dockerjava.api.command.InspectSwarmCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InspectSwarmNodeCmd",
|
||||
"com.github.dockerjava.api.command.InspectSwarmNodeCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InspectTaskCmd",
|
||||
"com.github.dockerjava.api.command.InspectTaskCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InspectVolumeCmd",
|
||||
"com.github.dockerjava.api.command.InspectVolumeCmd$Exec",
|
||||
"com.github.dockerjava.api.command.InspectVolumeResponse",
|
||||
"com.github.dockerjava.api.command.JoinSwarmCmd",
|
||||
"com.github.dockerjava.api.command.JoinSwarmCmd$Exec",
|
||||
"com.github.dockerjava.api.command.KillContainerCmd",
|
||||
"com.github.dockerjava.api.command.KillContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.LeaveSwarmCmd",
|
||||
"com.github.dockerjava.api.command.LeaveSwarmCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ListConfigsCmd",
|
||||
"com.github.dockerjava.api.command.ListConfigsCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ListContainersCmd",
|
||||
"com.github.dockerjava.api.command.ListContainersCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ListImagesCmd",
|
||||
"com.github.dockerjava.api.command.ListImagesCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ListNetworksCmd",
|
||||
"com.github.dockerjava.api.command.ListNetworksCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ListSecretsCmd",
|
||||
"com.github.dockerjava.api.command.ListSecretsCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ListServicesCmd",
|
||||
"com.github.dockerjava.api.command.ListServicesCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ListSwarmNodesCmd",
|
||||
"com.github.dockerjava.api.command.ListSwarmNodesCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ListTasksCmd",
|
||||
"com.github.dockerjava.api.command.ListTasksCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ListVolumesCmd",
|
||||
"com.github.dockerjava.api.command.ListVolumesCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ListVolumesResponse",
|
||||
"com.github.dockerjava.api.command.LoadImageAsyncCmd",
|
||||
"com.github.dockerjava.api.command.LoadImageAsyncCmd$Exec",
|
||||
"com.github.dockerjava.api.command.LoadImageCallback",
|
||||
"com.github.dockerjava.api.command.LoadImageCmd",
|
||||
"com.github.dockerjava.api.command.LoadImageCmd$Exec",
|
||||
"com.github.dockerjava.api.command.LogContainerCmd",
|
||||
"com.github.dockerjava.api.command.LogContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.LogSwarmObjectCmd",
|
||||
"com.github.dockerjava.api.command.LogSwarmObjectCmd$Exec",
|
||||
"com.github.dockerjava.api.command.PauseContainerCmd",
|
||||
"com.github.dockerjava.api.command.PauseContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.PingCmd",
|
||||
"com.github.dockerjava.api.command.PingCmd$Exec",
|
||||
"com.github.dockerjava.api.command.PruneCmd",
|
||||
"com.github.dockerjava.api.command.PruneCmd$Exec",
|
||||
"com.github.dockerjava.api.command.PullImageCmd",
|
||||
"com.github.dockerjava.api.command.PullImageCmd$Exec",
|
||||
"com.github.dockerjava.api.command.PullImageResultCallback",
|
||||
"com.github.dockerjava.api.command.PushImageCmd",
|
||||
"com.github.dockerjava.api.command.PushImageCmd$1",
|
||||
"com.github.dockerjava.api.command.PushImageCmd$Exec",
|
||||
"com.github.dockerjava.api.command.RemoveConfigCmd",
|
||||
"com.github.dockerjava.api.command.RemoveConfigCmd$Exec",
|
||||
"com.github.dockerjava.api.command.RemoveContainerCmd",
|
||||
"com.github.dockerjava.api.command.RemoveContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.RemoveImageCmd",
|
||||
"com.github.dockerjava.api.command.RemoveImageCmd$Exec",
|
||||
"com.github.dockerjava.api.command.RemoveNetworkCmd",
|
||||
"com.github.dockerjava.api.command.RemoveNetworkCmd$Exec",
|
||||
"com.github.dockerjava.api.command.RemoveSecretCmd",
|
||||
"com.github.dockerjava.api.command.RemoveSecretCmd$Exec",
|
||||
"com.github.dockerjava.api.command.RemoveServiceCmd",
|
||||
"com.github.dockerjava.api.command.RemoveServiceCmd$Exec",
|
||||
"com.github.dockerjava.api.command.RemoveSwarmNodeCmd",
|
||||
"com.github.dockerjava.api.command.RemoveSwarmNodeCmd$Exec",
|
||||
"com.github.dockerjava.api.command.RemoveVolumeCmd",
|
||||
"com.github.dockerjava.api.command.RemoveVolumeCmd$Exec",
|
||||
"com.github.dockerjava.api.command.RenameContainerCmd",
|
||||
"com.github.dockerjava.api.command.RenameContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ResizeContainerCmd",
|
||||
"com.github.dockerjava.api.command.ResizeContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.ResizeExecCmd",
|
||||
"com.github.dockerjava.api.command.ResizeExecCmd$Exec",
|
||||
"com.github.dockerjava.api.command.RestartContainerCmd",
|
||||
"com.github.dockerjava.api.command.RestartContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.RootFS",
|
||||
"com.github.dockerjava.api.command.SaveImageCmd",
|
||||
"com.github.dockerjava.api.command.SaveImageCmd$Exec",
|
||||
"com.github.dockerjava.api.command.SaveImagesCmd",
|
||||
"com.github.dockerjava.api.command.SaveImagesCmd$Exec",
|
||||
"com.github.dockerjava.api.command.SaveImagesCmd$TaggedImage",
|
||||
"com.github.dockerjava.api.command.SearchImagesCmd",
|
||||
"com.github.dockerjava.api.command.SearchImagesCmd$Exec",
|
||||
"com.github.dockerjava.api.command.StartContainerCmd",
|
||||
"com.github.dockerjava.api.command.StartContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.StatsCmd",
|
||||
"com.github.dockerjava.api.command.StatsCmd$Exec",
|
||||
"com.github.dockerjava.api.command.StopContainerCmd",
|
||||
"com.github.dockerjava.api.command.StopContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.SyncDockerCmd",
|
||||
"com.github.dockerjava.api.command.TagImageCmd",
|
||||
"com.github.dockerjava.api.command.TagImageCmd$Exec",
|
||||
"com.github.dockerjava.api.command.TopContainerCmd",
|
||||
"com.github.dockerjava.api.command.TopContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.TopContainerResponse",
|
||||
"com.github.dockerjava.api.command.UnpauseContainerCmd",
|
||||
"com.github.dockerjava.api.command.UnpauseContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.UpdateContainerCmd",
|
||||
"com.github.dockerjava.api.command.UpdateContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.UpdateServiceCmd",
|
||||
"com.github.dockerjava.api.command.UpdateServiceCmd$Exec",
|
||||
"com.github.dockerjava.api.command.UpdateSwarmCmd",
|
||||
"com.github.dockerjava.api.command.UpdateSwarmCmd$Exec",
|
||||
"com.github.dockerjava.api.command.UpdateSwarmNodeCmd",
|
||||
"com.github.dockerjava.api.command.UpdateSwarmNodeCmd$Exec",
|
||||
"com.github.dockerjava.api.command.VersionCmd",
|
||||
"com.github.dockerjava.api.command.VersionCmd$Exec",
|
||||
"com.github.dockerjava.api.command.WaitContainerCmd",
|
||||
"com.github.dockerjava.api.command.WaitContainerCmd$Exec",
|
||||
"com.github.dockerjava.api.command.WaitContainerResultCallback",
|
||||
"com.github.dockerjava.api.exception.BadRequestException",
|
||||
"com.github.dockerjava.api.exception.ConflictException",
|
||||
"com.github.dockerjava.api.exception.DockerClientException",
|
||||
"com.github.dockerjava.api.exception.DockerException",
|
||||
"com.github.dockerjava.api.exception.InternalServerErrorException",
|
||||
"com.github.dockerjava.api.exception.NotAcceptableException",
|
||||
"com.github.dockerjava.api.exception.NotFoundException",
|
||||
"com.github.dockerjava.api.exception.NotModifiedException",
|
||||
"com.github.dockerjava.api.exception.UnauthorizedException",
|
||||
"com.github.dockerjava.api.model.AccessMode",
|
||||
"com.github.dockerjava.api.model.AuthConfig",
|
||||
"com.github.dockerjava.api.model.AuthConfigurations",
|
||||
"com.github.dockerjava.api.model.AuthResponse",
|
||||
"com.github.dockerjava.api.model.Bind",
|
||||
"com.github.dockerjava.api.model.BindOptions",
|
||||
"com.github.dockerjava.api.model.BindPropagation",
|
||||
"com.github.dockerjava.api.model.Binds",
|
||||
"com.github.dockerjava.api.model.BlkioRateDevice",
|
||||
"com.github.dockerjava.api.model.BlkioStatEntry",
|
||||
"com.github.dockerjava.api.model.BlkioStatsConfig",
|
||||
"com.github.dockerjava.api.model.BlkioWeightDevice",
|
||||
"com.github.dockerjava.api.model.BuildResponseItem",
|
||||
"com.github.dockerjava.api.model.Capability",
|
||||
"com.github.dockerjava.api.model.ChangeLog",
|
||||
"com.github.dockerjava.api.model.ClusterInfo",
|
||||
"com.github.dockerjava.api.model.Config",
|
||||
"com.github.dockerjava.api.model.ConfigSpec",
|
||||
"com.github.dockerjava.api.model.Container",
|
||||
"com.github.dockerjava.api.model.ContainerConfig",
|
||||
"com.github.dockerjava.api.model.ContainerDNSConfig",
|
||||
"com.github.dockerjava.api.model.ContainerHostConfig",
|
||||
"com.github.dockerjava.api.model.ContainerMount",
|
||||
"com.github.dockerjava.api.model.ContainerNetwork",
|
||||
"com.github.dockerjava.api.model.ContainerNetwork$Ipam",
|
||||
"com.github.dockerjava.api.model.ContainerNetworkSettings",
|
||||
"com.github.dockerjava.api.model.ContainerPort",
|
||||
"com.github.dockerjava.api.model.ContainerSpec",
|
||||
"com.github.dockerjava.api.model.ContainerSpecConfig",
|
||||
"com.github.dockerjava.api.model.ContainerSpecFile",
|
||||
"com.github.dockerjava.api.model.ContainerSpecPrivileges",
|
||||
"com.github.dockerjava.api.model.ContainerSpecPrivilegesCredential",
|
||||
"com.github.dockerjava.api.model.ContainerSpecPrivilegesSELinuxContext",
|
||||
"com.github.dockerjava.api.model.ContainerSpecSecret",
|
||||
"com.github.dockerjava.api.model.CpuStatsConfig",
|
||||
"com.github.dockerjava.api.model.CpuUsageConfig",
|
||||
"com.github.dockerjava.api.model.Device",
|
||||
"com.github.dockerjava.api.model.DeviceRequest",
|
||||
"com.github.dockerjava.api.model.DiscreteResourceSpec",
|
||||
"com.github.dockerjava.api.model.DockerObject",
|
||||
"com.github.dockerjava.api.model.DockerObjectAccessor",
|
||||
"com.github.dockerjava.api.model.Driver",
|
||||
"com.github.dockerjava.api.model.DriverStatus",
|
||||
"com.github.dockerjava.api.model.Endpoint",
|
||||
"com.github.dockerjava.api.model.EndpointResolutionMode",
|
||||
"com.github.dockerjava.api.model.EndpointSpec",
|
||||
"com.github.dockerjava.api.model.EndpointVirtualIP",
|
||||
"com.github.dockerjava.api.model.ErrorDetail",
|
||||
"com.github.dockerjava.api.model.ErrorResponse",
|
||||
"com.github.dockerjava.api.model.Event",
|
||||
"com.github.dockerjava.api.model.EventActor",
|
||||
"com.github.dockerjava.api.model.EventType",
|
||||
"com.github.dockerjava.api.model.ExposedPort",
|
||||
"com.github.dockerjava.api.model.ExposedPorts",
|
||||
"com.github.dockerjava.api.model.ExternalCA",
|
||||
"com.github.dockerjava.api.model.ExternalCAProtocol",
|
||||
"com.github.dockerjava.api.model.Frame",
|
||||
"com.github.dockerjava.api.model.GenericResource",
|
||||
"com.github.dockerjava.api.model.HealthCheck",
|
||||
"com.github.dockerjava.api.model.HostConfig",
|
||||
"com.github.dockerjava.api.model.Identifier",
|
||||
"com.github.dockerjava.api.model.Image",
|
||||
"com.github.dockerjava.api.model.ImageOptions",
|
||||
"com.github.dockerjava.api.model.Info",
|
||||
"com.github.dockerjava.api.model.InfoRegistryConfig",
|
||||
"com.github.dockerjava.api.model.InfoRegistryConfig$IndexConfig",
|
||||
"com.github.dockerjava.api.model.InternetProtocol",
|
||||
"com.github.dockerjava.api.model.Isolation",
|
||||
"com.github.dockerjava.api.model.Link",
|
||||
"com.github.dockerjava.api.model.Links",
|
||||
"com.github.dockerjava.api.model.LoadResponseItem",
|
||||
"com.github.dockerjava.api.model.LocalNodeState",
|
||||
"com.github.dockerjava.api.model.LogConfig",
|
||||
"com.github.dockerjava.api.model.LogConfig$LoggingType",
|
||||
"com.github.dockerjava.api.model.LxcConf",
|
||||
"com.github.dockerjava.api.model.MemoryStatsConfig",
|
||||
"com.github.dockerjava.api.model.Mount",
|
||||
"com.github.dockerjava.api.model.MountType",
|
||||
"com.github.dockerjava.api.model.NamedResourceSpec",
|
||||
"com.github.dockerjava.api.model.Network",
|
||||
"com.github.dockerjava.api.model.Network$ContainerNetworkConfig",
|
||||
"com.github.dockerjava.api.model.Network$Ipam",
|
||||
"com.github.dockerjava.api.model.Network$Ipam$Config",
|
||||
"com.github.dockerjava.api.model.NetworkAttachmentConfig",
|
||||
"com.github.dockerjava.api.model.NetworkSettings",
|
||||
"com.github.dockerjava.api.model.Node",
|
||||
"com.github.dockerjava.api.model.ObjectVersion",
|
||||
"com.github.dockerjava.api.model.PeerNode",
|
||||
"com.github.dockerjava.api.model.PidsStatsConfig",
|
||||
"com.github.dockerjava.api.model.PortBinding",
|
||||
"com.github.dockerjava.api.model.PortConfig",
|
||||
"com.github.dockerjava.api.model.PortConfig$PublishMode",
|
||||
"com.github.dockerjava.api.model.PortConfigProtocol",
|
||||
"com.github.dockerjava.api.model.Ports",
|
||||
"com.github.dockerjava.api.model.Ports$Binding",
|
||||
"com.github.dockerjava.api.model.PropagationMode",
|
||||
"com.github.dockerjava.api.model.PruneResponse",
|
||||
"com.github.dockerjava.api.model.PruneType",
|
||||
"com.github.dockerjava.api.model.PullResponseItem",
|
||||
"com.github.dockerjava.api.model.PushResponseItem",
|
||||
"com.github.dockerjava.api.model.Reachability",
|
||||
"com.github.dockerjava.api.model.Repository",
|
||||
"com.github.dockerjava.api.model.ResourceRequirements",
|
||||
"com.github.dockerjava.api.model.ResourceSpecs",
|
||||
"com.github.dockerjava.api.model.ResourceVersion",
|
||||
"com.github.dockerjava.api.model.ResponseItem",
|
||||
"com.github.dockerjava.api.model.ResponseItem$AuxDetail",
|
||||
"com.github.dockerjava.api.model.ResponseItem$ErrorDetail",
|
||||
"com.github.dockerjava.api.model.ResponseItem$ProgressDetail",
|
||||
"com.github.dockerjava.api.model.RestartPolicy",
|
||||
"com.github.dockerjava.api.model.RuntimeInfo",
|
||||
"com.github.dockerjava.api.model.SELContext",
|
||||
"com.github.dockerjava.api.model.SearchItem",
|
||||
"com.github.dockerjava.api.model.Secret",
|
||||
"com.github.dockerjava.api.model.SecretSpec",
|
||||
"com.github.dockerjava.api.model.Service",
|
||||
"com.github.dockerjava.api.model.ServiceGlobalModeOptions",
|
||||
"com.github.dockerjava.api.model.ServiceMode",
|
||||
"com.github.dockerjava.api.model.ServiceModeConfig",
|
||||
"com.github.dockerjava.api.model.ServicePlacement",
|
||||
"com.github.dockerjava.api.model.ServiceReplicatedModeOptions",
|
||||
"com.github.dockerjava.api.model.ServiceRestartCondition",
|
||||
"com.github.dockerjava.api.model.ServiceRestartPolicy",
|
||||
"com.github.dockerjava.api.model.ServiceSpec",
|
||||
"com.github.dockerjava.api.model.ServiceUpdateState",
|
||||
"com.github.dockerjava.api.model.ServiceUpdateStatus",
|
||||
"com.github.dockerjava.api.model.StatisticNetworksConfig",
|
||||
"com.github.dockerjava.api.model.Statistics",
|
||||
"com.github.dockerjava.api.model.StatsConfig",
|
||||
"com.github.dockerjava.api.model.StreamType",
|
||||
"com.github.dockerjava.api.model.Swarm",
|
||||
"com.github.dockerjava.api.model.SwarmCAConfig",
|
||||
"com.github.dockerjava.api.model.SwarmDispatcherConfig",
|
||||
"com.github.dockerjava.api.model.SwarmInfo",
|
||||
"com.github.dockerjava.api.model.SwarmJoinTokens",
|
||||
"com.github.dockerjava.api.model.SwarmNode",
|
||||
"com.github.dockerjava.api.model.SwarmNodeAvailability",
|
||||
"com.github.dockerjava.api.model.SwarmNodeDescription",
|
||||
"com.github.dockerjava.api.model.SwarmNodeEngineDescription",
|
||||
"com.github.dockerjava.api.model.SwarmNodeManagerStatus",
|
||||
"com.github.dockerjava.api.model.SwarmNodePlatform",
|
||||
"com.github.dockerjava.api.model.SwarmNodePluginDescription",
|
||||
"com.github.dockerjava.api.model.SwarmNodeResources",
|
||||
"com.github.dockerjava.api.model.SwarmNodeRole",
|
||||
"com.github.dockerjava.api.model.SwarmNodeSpec",
|
||||
"com.github.dockerjava.api.model.SwarmNodeState",
|
||||
"com.github.dockerjava.api.model.SwarmNodeStatus",
|
||||
"com.github.dockerjava.api.model.SwarmNodeVersion",
|
||||
"com.github.dockerjava.api.model.SwarmOrchestration",
|
||||
"com.github.dockerjava.api.model.SwarmRaftConfig",
|
||||
"com.github.dockerjava.api.model.SwarmSpec",
|
||||
"com.github.dockerjava.api.model.SwarmVersion",
|
||||
"com.github.dockerjava.api.model.Task",
|
||||
"com.github.dockerjava.api.model.TaskDefaults",
|
||||
"com.github.dockerjava.api.model.TaskSpec",
|
||||
"com.github.dockerjava.api.model.TaskState",
|
||||
"com.github.dockerjava.api.model.TaskStatus",
|
||||
"com.github.dockerjava.api.model.TaskStatusContainerStatus",
|
||||
"com.github.dockerjava.api.model.ThrottlingDataConfig",
|
||||
"com.github.dockerjava.api.model.TmpfsOptions",
|
||||
"com.github.dockerjava.api.model.Ulimit",
|
||||
"com.github.dockerjava.api.model.UpdateConfig",
|
||||
"com.github.dockerjava.api.model.UpdateContainerResponse",
|
||||
"com.github.dockerjava.api.model.UpdateFailureAction",
|
||||
"com.github.dockerjava.api.model.UpdateOrder",
|
||||
"com.github.dockerjava.api.model.Version",
|
||||
"com.github.dockerjava.api.model.VersionComponent",
|
||||
"com.github.dockerjava.api.model.VersionPlatform",
|
||||
"com.github.dockerjava.api.model.Volume",
|
||||
"com.github.dockerjava.api.model.VolumeBind",
|
||||
"com.github.dockerjava.api.model.VolumeBinds",
|
||||
"com.github.dockerjava.api.model.VolumeOptions",
|
||||
"com.github.dockerjava.api.model.VolumeRW",
|
||||
"com.github.dockerjava.api.model.Volumes",
|
||||
"com.github.dockerjava.api.model.VolumesFrom",
|
||||
"com.github.dockerjava.api.model.VolumesRW",
|
||||
"com.github.dockerjava.api.model.WaitResponse",
|
||||
"com.github.dockerjava.core.AbstractDockerCmdExecFactory",
|
||||
"com.github.dockerjava.core.DefaultDockerClientConfig",
|
||||
"com.github.dockerjava.core.DefaultDockerClientConfig$Builder",
|
||||
"com.github.dockerjava.core.DefaultDockerCmdExecFactory",
|
||||
"com.github.dockerjava.core.DefaultDockerCmdExecFactory$DefaultWebTarget",
|
||||
"com.github.dockerjava.core.DefaultInvocationBuilder",
|
||||
"com.github.dockerjava.core.DefaultInvocationBuilder$1",
|
||||
"com.github.dockerjava.core.DefaultInvocationBuilder$2",
|
||||
"com.github.dockerjava.core.DefaultInvocationBuilder$JsonSink",
|
||||
"com.github.dockerjava.core.DefaultObjectMapperHolder",
|
||||
"com.github.dockerjava.core.DefaultObjectMapperHolder$1",
|
||||
"com.github.dockerjava.core.DefaultObjectMapperHolder$1$1",
|
||||
"com.github.dockerjava.core.DockerClientConfig",
|
||||
"com.github.dockerjava.core.DockerClientConfigAware",
|
||||
"com.github.dockerjava.core.DockerClientConfigDelegate",
|
||||
"com.github.dockerjava.core.DockerClientImpl",
|
||||
"com.github.dockerjava.core.DockerConfigFile",
|
||||
"com.github.dockerjava.core.DockerConfigFile$1",
|
||||
"com.github.dockerjava.core.DockerContextMetaFile",
|
||||
"com.github.dockerjava.core.DockerContextMetaFile$Endpoints",
|
||||
"com.github.dockerjava.core.DockerContextMetaFile$Endpoints$Docker",
|
||||
"com.github.dockerjava.core.DockerObjectDeserializer",
|
||||
"com.github.dockerjava.core.FramedInputStreamConsumer",
|
||||
"com.github.dockerjava.core.GoLangFileMatch",
|
||||
"com.github.dockerjava.core.GoLangFileMatch$RangeParseState",
|
||||
"com.github.dockerjava.core.GoLangMatchFileFilter",
|
||||
"com.github.dockerjava.core.InvocationBuilder",
|
||||
"com.github.dockerjava.core.InvocationBuilder$AsyncResultCallback",
|
||||
"com.github.dockerjava.core.KeystoreSSLConfig",
|
||||
"com.github.dockerjava.core.KeystoreSSLConfig$1",
|
||||
"com.github.dockerjava.core.LocalDirectorySSLConfig",
|
||||
"com.github.dockerjava.core.MediaType",
|
||||
"com.github.dockerjava.core.NameParser",
|
||||
"com.github.dockerjava.core.NameParser$HostnameReposName",
|
||||
"com.github.dockerjava.core.NameParser$ReposTag",
|
||||
"com.github.dockerjava.core.RemoteApiVersion",
|
||||
"com.github.dockerjava.core.RemoteApiVersion$1",
|
||||
"com.github.dockerjava.core.SSLConfig",
|
||||
"com.github.dockerjava.core.WebTarget",
|
||||
"com.github.dockerjava.core.async.FrameStreamProcessor",
|
||||
"com.github.dockerjava.core.async.JsonStreamProcessor",
|
||||
"com.github.dockerjava.core.async.JsonStreamProcessor$1",
|
||||
"com.github.dockerjava.core.async.ResponseStreamProcessor",
|
||||
"com.github.dockerjava.core.async.ResultCallbackTemplate",
|
||||
"com.github.dockerjava.core.command.AbstrAsyncDockerCmd",
|
||||
"com.github.dockerjava.core.command.AbstrDockerCmd",
|
||||
"com.github.dockerjava.core.command.AttachContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.AttachContainerResultCallback",
|
||||
"com.github.dockerjava.core.command.AuthCmdImpl",
|
||||
"com.github.dockerjava.core.command.BuildImageCmdImpl",
|
||||
"com.github.dockerjava.core.command.BuildImageResultCallback",
|
||||
"com.github.dockerjava.core.command.CommitCmdImpl",
|
||||
"com.github.dockerjava.core.command.ConnectToNetworkCmdImpl",
|
||||
"com.github.dockerjava.core.command.ContainerDiffCmdImpl",
|
||||
"com.github.dockerjava.core.command.CopyArchiveFromContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.CopyArchiveToContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.CopyFileFromContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.CreateConfigCmdImpl",
|
||||
"com.github.dockerjava.core.command.CreateContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.CreateContainerCmdImpl$NetworkingConfig",
|
||||
"com.github.dockerjava.core.command.CreateImageCmdImpl",
|
||||
"com.github.dockerjava.core.command.CreateNetworkCmdImpl",
|
||||
"com.github.dockerjava.core.command.CreateSecretCmdImpl",
|
||||
"com.github.dockerjava.core.command.CreateServiceCmdImpl",
|
||||
"com.github.dockerjava.core.command.CreateVolumeCmdImpl",
|
||||
"com.github.dockerjava.core.command.DisconnectFromNetworkCmdImpl",
|
||||
"com.github.dockerjava.core.command.EventsCmdImpl",
|
||||
"com.github.dockerjava.core.command.EventsResultCallback",
|
||||
"com.github.dockerjava.core.command.ExecCreateCmdImpl",
|
||||
"com.github.dockerjava.core.command.ExecStartCmdImpl",
|
||||
"com.github.dockerjava.core.command.ExecStartResultCallback",
|
||||
"com.github.dockerjava.core.command.ExecStartResultCallback$1",
|
||||
"com.github.dockerjava.core.command.FrameReader",
|
||||
"com.github.dockerjava.core.command.InfoCmdImpl",
|
||||
"com.github.dockerjava.core.command.InitializeSwarmCmdImpl",
|
||||
"com.github.dockerjava.core.command.InpectNetworkCmdImpl",
|
||||
"com.github.dockerjava.core.command.InspectConfigCmdImpl",
|
||||
"com.github.dockerjava.core.command.InspectContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.InspectExecCmdImpl",
|
||||
"com.github.dockerjava.core.command.InspectImageCmdImpl",
|
||||
"com.github.dockerjava.core.command.InspectServiceCmdImpl",
|
||||
"com.github.dockerjava.core.command.InspectSwarmCmdImpl",
|
||||
"com.github.dockerjava.core.command.InspectSwarmNodeCmdImpl",
|
||||
"com.github.dockerjava.core.command.InspectVolumeCmdImpl",
|
||||
"com.github.dockerjava.core.command.JoinSwarmCmdImpl",
|
||||
"com.github.dockerjava.core.command.KillContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.LeaveSwarmCmdImpl",
|
||||
"com.github.dockerjava.core.command.ListConfigsCmdImpl",
|
||||
"com.github.dockerjava.core.command.ListContainersCmdImpl",
|
||||
"com.github.dockerjava.core.command.ListImagesCmdImpl",
|
||||
"com.github.dockerjava.core.command.ListNetworksCmdImpl",
|
||||
"com.github.dockerjava.core.command.ListSecretsCmdImpl",
|
||||
"com.github.dockerjava.core.command.ListServicesCmdImpl",
|
||||
"com.github.dockerjava.core.command.ListSwarmNodesCmdImpl",
|
||||
"com.github.dockerjava.core.command.ListTasksCmdImpl",
|
||||
"com.github.dockerjava.core.command.ListVolumesCmdImpl",
|
||||
"com.github.dockerjava.core.command.LoadImageAsyncCmdImpl",
|
||||
"com.github.dockerjava.core.command.LoadImageCmdImpl",
|
||||
"com.github.dockerjava.core.command.LogContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.LogContainerResultCallback",
|
||||
"com.github.dockerjava.core.command.LogSwarmObjectImpl",
|
||||
"com.github.dockerjava.core.command.PauseContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.PingCmdImpl",
|
||||
"com.github.dockerjava.core.command.PruneCmdImpl",
|
||||
"com.github.dockerjava.core.command.PruneCmdImpl$1",
|
||||
"com.github.dockerjava.core.command.PullImageCmdImpl",
|
||||
"com.github.dockerjava.core.command.PullImageResultCallback",
|
||||
"com.github.dockerjava.core.command.PushImageCmdImpl",
|
||||
"com.github.dockerjava.core.command.PushImageResultCallback",
|
||||
"com.github.dockerjava.core.command.RemoveConfigCmdImpl",
|
||||
"com.github.dockerjava.core.command.RemoveContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.RemoveImageCmdImpl",
|
||||
"com.github.dockerjava.core.command.RemoveNetworkCmdImpl",
|
||||
"com.github.dockerjava.core.command.RemoveSecretCmdImpl",
|
||||
"com.github.dockerjava.core.command.RemoveServiceCmdImpl",
|
||||
"com.github.dockerjava.core.command.RemoveSwarmNodeCmdImpl",
|
||||
"com.github.dockerjava.core.command.RemoveVolumeCmdImpl",
|
||||
"com.github.dockerjava.core.command.RenameContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.ResizeContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.ResizeExecCmdImpl",
|
||||
"com.github.dockerjava.core.command.RestartContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.SaveImageCmdImpl",
|
||||
"com.github.dockerjava.core.command.SaveImagesCmdImpl",
|
||||
"com.github.dockerjava.core.command.SaveImagesCmdImpl$1",
|
||||
"com.github.dockerjava.core.command.SaveImagesCmdImpl$TaggedImageImpl",
|
||||
"com.github.dockerjava.core.command.SearchImagesCmdImpl",
|
||||
"com.github.dockerjava.core.command.StartContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.StatsCmdImpl",
|
||||
"com.github.dockerjava.core.command.StopContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.TagImageCmdImpl",
|
||||
"com.github.dockerjava.core.command.TopContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.UnpauseContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.UpdateContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.UpdateServiceCmdImpl",
|
||||
"com.github.dockerjava.core.command.UpdateSwarmCmdImpl",
|
||||
"com.github.dockerjava.core.command.UpdateSwarmNodeCmdImpl",
|
||||
"com.github.dockerjava.core.command.VersionCmdImpl",
|
||||
"com.github.dockerjava.core.command.WaitContainerCmdImpl",
|
||||
"com.github.dockerjava.core.command.WaitContainerResultCallback",
|
||||
"com.github.dockerjava.core.dockerfile.Dockerfile",
|
||||
"com.github.dockerjava.core.dockerfile.Dockerfile$1",
|
||||
"com.github.dockerjava.core.dockerfile.Dockerfile$LineTransformer",
|
||||
"com.github.dockerjava.core.dockerfile.Dockerfile$ScannedResult",
|
||||
"com.github.dockerjava.core.dockerfile.Dockerfile$ScannedResult$1",
|
||||
"com.github.dockerjava.core.dockerfile.DockerfileStatement",
|
||||
"com.github.dockerjava.core.dockerfile.DockerfileStatement$1",
|
||||
"com.github.dockerjava.core.dockerfile.DockerfileStatement$Add",
|
||||
"com.github.dockerjava.core.dockerfile.DockerfileStatement$Env",
|
||||
"com.github.dockerjava.core.dockerfile.DockerfileStatement$OtherLine",
|
||||
"com.github.dockerjava.core.exception.GoLangFileMatchException",
|
||||
"com.github.dockerjava.core.exception.InvalidRepositoryNameException",
|
||||
"com.github.dockerjava.core.exec.AbstrAsyncDockerCmdExec",
|
||||
"com.github.dockerjava.core.exec.AbstrAsyncDockerCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.AbstrDockerCmdExec",
|
||||
"com.github.dockerjava.core.exec.AbstrSyncDockerCmdExec",
|
||||
"com.github.dockerjava.core.exec.AttachContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.AuthCmdExec",
|
||||
"com.github.dockerjava.core.exec.AuthCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.BuildImageCmdExec",
|
||||
"com.github.dockerjava.core.exec.BuildImageCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.CommitCmdExec",
|
||||
"com.github.dockerjava.core.exec.CommitCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.ConnectToNetworkCmdExec",
|
||||
"com.github.dockerjava.core.exec.ContainerDiffCmdExec",
|
||||
"com.github.dockerjava.core.exec.ContainerDiffCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.CopyArchiveFromContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.CopyArchiveToContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.CopyFileFromContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.CreateConfigCmdExec",
|
||||
"com.github.dockerjava.core.exec.CreateConfigCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.CreateContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.CreateContainerCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.CreateImageCmdExec",
|
||||
"com.github.dockerjava.core.exec.CreateImageCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.CreateNetworkCmdExec",
|
||||
"com.github.dockerjava.core.exec.CreateNetworkCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.CreateSecretCmdExec",
|
||||
"com.github.dockerjava.core.exec.CreateSecretCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.CreateServiceCmdExec",
|
||||
"com.github.dockerjava.core.exec.CreateServiceCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.CreateVolumeCmdExec",
|
||||
"com.github.dockerjava.core.exec.CreateVolumeCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.DisconnectFromNetworkCmdExec",
|
||||
"com.github.dockerjava.core.exec.EventsCmdExec",
|
||||
"com.github.dockerjava.core.exec.EventsCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.ExecCreateCmdExec",
|
||||
"com.github.dockerjava.core.exec.ExecCreateCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.ExecStartCmdExec",
|
||||
"com.github.dockerjava.core.exec.InfoCmdExec",
|
||||
"com.github.dockerjava.core.exec.InfoCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.InitializeSwarmCmdExec",
|
||||
"com.github.dockerjava.core.exec.InspectConfigCmdExec",
|
||||
"com.github.dockerjava.core.exec.InspectConfigCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.InspectContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.InspectContainerCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.InspectExecCmdExec",
|
||||
"com.github.dockerjava.core.exec.InspectExecCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.InspectImageCmdExec",
|
||||
"com.github.dockerjava.core.exec.InspectImageCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.InspectNetworkCmdExec",
|
||||
"com.github.dockerjava.core.exec.InspectNetworkCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.InspectServiceCmdExec",
|
||||
"com.github.dockerjava.core.exec.InspectServiceCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.InspectSwarmCmdExec",
|
||||
"com.github.dockerjava.core.exec.InspectSwarmCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.InspectSwarmNodeCmdExec",
|
||||
"com.github.dockerjava.core.exec.InspectSwarmNodeCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.InspectVolumeCmdExec",
|
||||
"com.github.dockerjava.core.exec.InspectVolumeCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.JoinSwarmCmdExec",
|
||||
"com.github.dockerjava.core.exec.KillContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.LeaveSwarmCmdExec",
|
||||
"com.github.dockerjava.core.exec.ListConfigsCmdExec",
|
||||
"com.github.dockerjava.core.exec.ListConfigsCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.ListContainersCmdExec",
|
||||
"com.github.dockerjava.core.exec.ListContainersCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.ListImagesCmdExec",
|
||||
"com.github.dockerjava.core.exec.ListImagesCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.ListNetworksCmdExec",
|
||||
"com.github.dockerjava.core.exec.ListNetworksCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.ListSecretsCmdExec",
|
||||
"com.github.dockerjava.core.exec.ListSecretsCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.ListServicesCmdExec",
|
||||
"com.github.dockerjava.core.exec.ListServicesCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.ListSwarmNodesCmdExec",
|
||||
"com.github.dockerjava.core.exec.ListSwarmNodesCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.ListTasksCmdExec",
|
||||
"com.github.dockerjava.core.exec.ListTasksCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.ListVolumesCmdExec",
|
||||
"com.github.dockerjava.core.exec.ListVolumesCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.LoadImageAsyncCmdExec",
|
||||
"com.github.dockerjava.core.exec.LoadImageAsyncCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.LoadImageCmdExec",
|
||||
"com.github.dockerjava.core.exec.LogContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.LogSwarmObjectExec",
|
||||
"com.github.dockerjava.core.exec.PauseContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.PingCmdExec",
|
||||
"com.github.dockerjava.core.exec.PruneCmdExec",
|
||||
"com.github.dockerjava.core.exec.PruneCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.PullImageCmdExec",
|
||||
"com.github.dockerjava.core.exec.PullImageCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.PushImageCmdExec",
|
||||
"com.github.dockerjava.core.exec.PushImageCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.RemoveConfigCmdExec",
|
||||
"com.github.dockerjava.core.exec.RemoveContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.RemoveImageCmdExec",
|
||||
"com.github.dockerjava.core.exec.RemoveNetworkCmdExec",
|
||||
"com.github.dockerjava.core.exec.RemoveSecretCmdExec",
|
||||
"com.github.dockerjava.core.exec.RemoveServiceCmdExec",
|
||||
"com.github.dockerjava.core.exec.RemoveSwarmNodeCmdExec",
|
||||
"com.github.dockerjava.core.exec.RemoveVolumeCmdExec",
|
||||
"com.github.dockerjava.core.exec.RenameContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.ResizeContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.ResizeExecCmdExec",
|
||||
"com.github.dockerjava.core.exec.RestartContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.SaveImageCmdExec",
|
||||
"com.github.dockerjava.core.exec.SaveImagesCmdExec",
|
||||
"com.github.dockerjava.core.exec.SearchImagesCmdExec",
|
||||
"com.github.dockerjava.core.exec.SearchImagesCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.StartContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.StatsCmdExec",
|
||||
"com.github.dockerjava.core.exec.StatsCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.StopContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.TagImageCmdExec",
|
||||
"com.github.dockerjava.core.exec.TopContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.TopContainerCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.UnpauseContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.UpdateContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.UpdateContainerCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.UpdateServiceCmdExec",
|
||||
"com.github.dockerjava.core.exec.UpdateSwarmCmdExec",
|
||||
"com.github.dockerjava.core.exec.UpdateSwarmNodeCmdExec",
|
||||
"com.github.dockerjava.core.exec.VersionCmdExec",
|
||||
"com.github.dockerjava.core.exec.VersionCmdExec$1",
|
||||
"com.github.dockerjava.core.exec.WaitContainerCmdExec",
|
||||
"com.github.dockerjava.core.exec.WaitContainerCmdExec$1",
|
||||
"com.github.dockerjava.core.util.CacheFromEncoder",
|
||||
"com.github.dockerjava.core.util.CertificateUtils",
|
||||
"com.github.dockerjava.core.util.CompressArchiveUtil",
|
||||
"com.github.dockerjava.core.util.FilePathUtil",
|
||||
"com.github.dockerjava.core.util.FiltersBuilder",
|
||||
"com.github.dockerjava.core.util.FiltersEncoder",
|
||||
"com.github.dockerjava.core.util.SwarmNodesFiltersBuilder",
|
||||
"com.github.dockerjava.core.util.TarDirWalker"
|
||||
})
|
||||
public class DockerJavaNativeSupport {}
|
||||
@@ -0,0 +1,37 @@
|
||||
package io.github.hectorvent.floci.core.common.port;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Thread-safe sequential port dispenser for Lambda Runtime API servers.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class PortAllocator {
|
||||
|
||||
private final AtomicInteger counter;
|
||||
private final int maxPort;
|
||||
|
||||
@Inject
|
||||
public PortAllocator(EmulatorConfig config) {
|
||||
this.counter = new AtomicInteger(config.services().lambda().runtimeApiBasePort());
|
||||
this.maxPort = config.services().lambda().runtimeApiMaxPort();
|
||||
}
|
||||
|
||||
PortAllocator(int basePort, int maxPort) {
|
||||
this.counter = new AtomicInteger(basePort);
|
||||
this.maxPort = maxPort;
|
||||
}
|
||||
|
||||
public int allocate() {
|
||||
int port = counter.getAndIncrement();
|
||||
if (port > maxPort) {
|
||||
counter.set(counter.get() - (maxPort - counter.get() + 1));
|
||||
port = counter.getAndIncrement();
|
||||
}
|
||||
return port;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* Hybrid storage: in-memory reads with async flush to disk.
|
||||
* Writes go to memory immediately, then flushed to disk periodically.
|
||||
*/
|
||||
public class HybridStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(HybridStorage.class);
|
||||
|
||||
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
private final Path filePath;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final TypeReference<Map<K, V>> typeReference;
|
||||
private final ScheduledExecutorService scheduler;
|
||||
private final AtomicBoolean dirty = new AtomicBoolean(false);
|
||||
|
||||
public HybridStorage(Path filePath, TypeReference<Map<K, V>> typeReference, long flushIntervalMs) {
|
||||
this.filePath = filePath;
|
||||
this.typeReference = typeReference;
|
||||
this.objectMapper = new ObjectMapper();
|
||||
this.objectMapper.registerModule(new JavaTimeModule());
|
||||
this.objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
this.objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
|
||||
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "hybrid-storage-flush");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
this.scheduler.scheduleAtFixedRate(this::flushIfDirty, flushIntervalMs, flushIntervalMs, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void put(K key, V value) {
|
||||
store.put(key, value);
|
||||
dirty.set(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<V> get(K key) {
|
||||
return Optional.ofNullable(store.get(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(K key) {
|
||||
store.remove(key);
|
||||
dirty.set(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<V> scan(Predicate<K> keyFilter) {
|
||||
return store.entrySet().stream()
|
||||
.filter(e -> keyFilter.test(e.getKey()))
|
||||
.map(Map.Entry::getValue)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<K> keys() {
|
||||
return Collections.unmodifiableSet(store.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
persistToDisk();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
if (!Files.exists(filePath)) {
|
||||
LOG.debugv("No persistent file found at {0}, starting with empty store", filePath);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Map<K, V> data = objectMapper.readValue(filePath.toFile(), typeReference);
|
||||
store.clear();
|
||||
store.putAll(data);
|
||||
LOG.infov("Loaded {0} entries from {1}", store.size(), filePath);
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to load data from {0}", filePath);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
store.clear();
|
||||
dirty.set(true);
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
scheduler.shutdown();
|
||||
try {
|
||||
if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
scheduler.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
scheduler.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
flush();
|
||||
}
|
||||
|
||||
private void flushIfDirty() {
|
||||
if (dirty.compareAndSet(true, false)) {
|
||||
persistToDisk();
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void persistToDisk() {
|
||||
try {
|
||||
Files.createDirectories(filePath.getParent());
|
||||
Path tempFile = filePath.resolveSibling(filePath.getFileName() + ".tmp");
|
||||
objectMapper.writeValue(tempFile.toFile(), store);
|
||||
Files.move(tempFile, filePath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
||||
LOG.debugv("Flushed {0} entries to {1}", store.size(), filePath);
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to persist data to {0}", filePath);
|
||||
dirty.set(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* Thread-safe in-memory storage backed by ConcurrentHashMap.
|
||||
* No persistence — data is lost on shutdown unless explicitly flushed.
|
||||
*/
|
||||
public class InMemoryStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public void put(K key, V value) {
|
||||
store.put(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<V> get(K key) {
|
||||
return Optional.ofNullable(store.get(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(K key) {
|
||||
store.remove(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<V> scan(Predicate<K> keyFilter) {
|
||||
List<V> result = new ArrayList<>();
|
||||
store.forEach((k, v) -> {
|
||||
if (keyFilter.test(k)) {
|
||||
result.add(v);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<K> keys() {
|
||||
return Collections.unmodifiableSet(store.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
// No-op for in-memory storage
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
// No-op for in-memory storage
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
store.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* JSON file-backed persistent storage.
|
||||
* Loads all data into memory on startup for fast reads.
|
||||
* Write-through on every put/delete.
|
||||
* Uses atomic writes (temp file + rename) for safety.
|
||||
*/
|
||||
public class PersistentStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(PersistentStorage.class);
|
||||
|
||||
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
private final Path filePath;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final TypeReference<Map<K, V>> typeReference;
|
||||
|
||||
public PersistentStorage(Path filePath, TypeReference<Map<K, V>> typeReference) {
|
||||
this.filePath = filePath;
|
||||
this.typeReference = typeReference;
|
||||
this.objectMapper = new ObjectMapper();
|
||||
this.objectMapper.registerModule(new JavaTimeModule());
|
||||
this.objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
this.objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void put(K key, V value) {
|
||||
store.put(key, value);
|
||||
persistToDisk();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<V> get(K key) {
|
||||
return Optional.ofNullable(store.get(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(K key) {
|
||||
store.remove(key);
|
||||
persistToDisk();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<V> scan(Predicate<K> keyFilter) {
|
||||
return store.entrySet().stream()
|
||||
.filter(e -> keyFilter.test(e.getKey()))
|
||||
.map(Map.Entry::getValue)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<K> keys() {
|
||||
return Collections.unmodifiableSet(store.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
persistToDisk();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
if (!Files.exists(filePath)) {
|
||||
LOG.debugv("No persistent file found at {0}, starting with empty store", filePath);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Map<K, V> data = objectMapper.readValue(filePath.toFile(), typeReference);
|
||||
store.clear();
|
||||
store.putAll(data);
|
||||
LOG.infov("Loaded {0} entries from {1}", store.size(), filePath);
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to load data from {0}", filePath);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
store.clear();
|
||||
persistToDisk();
|
||||
}
|
||||
|
||||
private synchronized void persistToDisk() {
|
||||
try {
|
||||
Files.createDirectories(filePath.getParent());
|
||||
Path tempFile = filePath.resolveSibling(filePath.getFileName() + ".tmp");
|
||||
objectMapper.writeValue(tempFile.toFile(), store);
|
||||
Files.move(tempFile, filePath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to persist data to {0}", filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* Generic storage abstraction for AWS emulator services.
|
||||
*
|
||||
* @param <K> the key type
|
||||
* @param <V> the value type
|
||||
*/
|
||||
public interface StorageBackend<K, V> {
|
||||
|
||||
void put(K key, V value);
|
||||
|
||||
Optional<V> get(K key);
|
||||
|
||||
void delete(K key);
|
||||
|
||||
List<V> scan(Predicate<K> keyFilter);
|
||||
|
||||
/** Return all keys in this store. */
|
||||
Set<K> keys();
|
||||
|
||||
/** Persist data to disk if applicable. */
|
||||
void flush();
|
||||
|
||||
/** Load data from disk on startup. */
|
||||
void load();
|
||||
|
||||
/** Clear all data. */
|
||||
void clear();
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Factory that creates StorageBackend instances based on configuration.
|
||||
* Tracks all created backends for lifecycle management.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class StorageFactory {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(StorageFactory.class);
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final List<StorageBackend<?, ?>> allBackends = new ArrayList<>();
|
||||
private final List<HybridStorage<?, ?>> hybridBackends = new ArrayList<>();
|
||||
private final List<WalStorage<?, ?>> walBackends = new ArrayList<>();
|
||||
|
||||
@Inject
|
||||
public StorageFactory(EmulatorConfig config) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a storage backend for the given service.
|
||||
*
|
||||
* @param serviceName the service name (ssm, sqs, s3)
|
||||
* @param fileName the JSON file name for persistent storage
|
||||
* @param typeReference Jackson type reference for deserialization
|
||||
*/
|
||||
public <K, V> StorageBackend<K, V> create(String serviceName, String fileName,
|
||||
TypeReference<Map<K, V>> typeReference) {
|
||||
String mode = resolveMode(serviceName);
|
||||
long flushInterval = resolveFlushInterval(serviceName);
|
||||
Path basePath = Path.of(config.storage().persistentPath());
|
||||
Path filePath = basePath.resolve(fileName);
|
||||
|
||||
LOG.infov("Creating {0} storage for service {1} (file: {2})", mode, serviceName, filePath);
|
||||
|
||||
StorageBackend<K, V> backend = switch (mode) {
|
||||
case "memory" -> new InMemoryStorage<>();
|
||||
case "persistent" -> new PersistentStorage<>(filePath, typeReference);
|
||||
case "hybrid" -> {
|
||||
var hybrid = new HybridStorage<>(filePath, typeReference, flushInterval);
|
||||
hybridBackends.add(hybrid);
|
||||
yield hybrid;
|
||||
}
|
||||
case "wal" -> {
|
||||
Path snapshotPath = basePath.resolve(fileName.replace(".json", "-snapshot.json"));
|
||||
Path walFilePath = basePath.resolve(fileName.replace(".json", ".wal"));
|
||||
long compactionInterval = config.storage().wal().compactionIntervalMs();
|
||||
var wal = new WalStorage<>(snapshotPath, walFilePath, typeReference, compactionInterval);
|
||||
walBackends.add(wal);
|
||||
yield wal;
|
||||
}
|
||||
default -> throw new IllegalArgumentException("Unknown storage mode: " + mode);
|
||||
};
|
||||
|
||||
allBackends.add(backend);
|
||||
return backend;
|
||||
}
|
||||
|
||||
/** Load all storage backends from disk. */
|
||||
public void loadAll() {
|
||||
for (StorageBackend<?, ?> backend : allBackends) {
|
||||
backend.load();
|
||||
}
|
||||
}
|
||||
|
||||
/** Flush all storage backends to disk. */
|
||||
public void flushAll() {
|
||||
for (StorageBackend<?, ?> backend : allBackends) {
|
||||
backend.flush();
|
||||
}
|
||||
}
|
||||
|
||||
/** Shutdown all managed backends (stop schedulers, close connections). */
|
||||
public void shutdownAll() {
|
||||
for (HybridStorage<?, ?> hybrid : hybridBackends) {
|
||||
hybrid.shutdown();
|
||||
}
|
||||
for (WalStorage<?, ?> wal : walBackends) {
|
||||
wal.shutdown();
|
||||
}
|
||||
flushAll();
|
||||
}
|
||||
|
||||
private String resolveMode(String serviceName) {
|
||||
return switch (serviceName) {
|
||||
case "ssm" -> config.storage().services().ssm().mode();
|
||||
case "sqs" -> config.storage().services().sqs().mode();
|
||||
case "s3" -> config.storage().services().s3().mode();
|
||||
case "dynamodb" -> config.storage().services().dynamodb().mode();
|
||||
case "sns" -> config.storage().services().sns().mode();
|
||||
case "lambda" -> config.storage().services().lambda().mode();
|
||||
case "cloudwatchlogs" -> config.storage().services().cloudwatchlogs().mode();
|
||||
case "cloudwatchmetrics" -> config.storage().services().cloudwatchmetrics().mode();
|
||||
case "secretsmanager" -> config.storage().services().secretsmanager().mode();
|
||||
default -> config.storage().mode();
|
||||
};
|
||||
}
|
||||
|
||||
private long resolveFlushInterval(String serviceName) {
|
||||
return switch (serviceName) {
|
||||
case "ssm" -> config.storage().services().ssm().flushIntervalMs();
|
||||
case "dynamodb" -> config.storage().services().dynamodb().flushIntervalMs();
|
||||
case "sns" -> config.storage().services().sns().flushIntervalMs();
|
||||
case "lambda" -> config.storage().services().lambda().flushIntervalMs();
|
||||
case "cloudwatchlogs" -> config.storage().services().cloudwatchlogs().flushIntervalMs();
|
||||
case "cloudwatchmetrics" -> config.storage().services().cloudwatchmetrics().flushIntervalMs();
|
||||
case "secretsmanager" -> config.storage().services().secretsmanager().flushIntervalMs();
|
||||
default -> 5000L;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
package io.github.hectorvent.floci.core.storage;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* Write-Ahead Log storage: in-memory reads with append-only binary WAL for durability.
|
||||
* Periodic compaction writes a full snapshot and truncates the WAL.
|
||||
* On startup: load snapshot, then replay WAL entries after snapshot.
|
||||
*
|
||||
* Binary WAL entry format:
|
||||
* PUT: [0x01] [4-byte key length] [key bytes] [4-byte value length] [value bytes]
|
||||
* DELETE: [0x02] [4-byte key length] [key bytes]
|
||||
*
|
||||
* Key and value bytes are serialized via Jackson CBOR (compact binary format).
|
||||
* Snapshot files use indented JSON for debuggability.
|
||||
*/
|
||||
public class WalStorage<K, V> implements StorageBackend<K, V> {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(WalStorage.class);
|
||||
|
||||
static final byte OP_PUT = 0x01;
|
||||
static final byte OP_DELETE = 0x02;
|
||||
|
||||
private final ConcurrentHashMap<K, V> store = new ConcurrentHashMap<>();
|
||||
private final Path snapshotPath;
|
||||
private final Path walPath;
|
||||
private final ObjectMapper snapshotMapper;
|
||||
private final ObjectMapper walMapper;
|
||||
private final TypeReference<Map<K, V>> typeReference;
|
||||
private final ReentrantReadWriteLock compactionLock = new ReentrantReadWriteLock();
|
||||
private final ScheduledExecutorService scheduler;
|
||||
private volatile DataOutputStream walWriter;
|
||||
|
||||
public WalStorage(Path snapshotPath, Path walPath, TypeReference<Map<K, V>> typeReference,
|
||||
long compactionIntervalMs) {
|
||||
this.snapshotPath = snapshotPath;
|
||||
this.walPath = walPath;
|
||||
this.typeReference = typeReference;
|
||||
|
||||
this.snapshotMapper = new ObjectMapper();
|
||||
this.snapshotMapper.registerModule(new JavaTimeModule());
|
||||
this.snapshotMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
this.snapshotMapper.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
|
||||
this.walMapper = new ObjectMapper(new CBORFactory());
|
||||
this.walMapper.registerModule(new JavaTimeModule());
|
||||
this.walMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
|
||||
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "wal-storage-compaction");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
this.scheduler.scheduleAtFixedRate(this::compact, compactionIntervalMs, compactionIntervalMs,
|
||||
TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void put(K key, V value) {
|
||||
compactionLock.readLock().lock();
|
||||
try {
|
||||
store.put(key, value);
|
||||
appendPut(key, value);
|
||||
} finally {
|
||||
compactionLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<V> get(K key) {
|
||||
return Optional.ofNullable(store.get(key));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(K key) {
|
||||
compactionLock.readLock().lock();
|
||||
try {
|
||||
store.remove(key);
|
||||
appendDelete(key);
|
||||
} finally {
|
||||
compactionLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<V> scan(Predicate<K> keyFilter) {
|
||||
return store.entrySet().stream()
|
||||
.filter(e -> keyFilter.test(e.getKey()))
|
||||
.map(Map.Entry::getValue)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<K> keys() {
|
||||
return Collections.unmodifiableSet(store.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
compact();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
if (Files.exists(snapshotPath)) {
|
||||
try {
|
||||
Map<K, V> data = snapshotMapper.readValue(snapshotPath.toFile(), typeReference);
|
||||
store.clear();
|
||||
store.putAll(data);
|
||||
LOG.infov("Loaded {0} entries from snapshot {1}", store.size(), snapshotPath);
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to load snapshot from {0}", snapshotPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (Files.exists(walPath)) {
|
||||
int replayed = replayWal();
|
||||
LOG.infov("Replayed {0} WAL entries from {1}", replayed, walPath);
|
||||
}
|
||||
|
||||
openWalWriter();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
compactionLock.writeLock().lock();
|
||||
try {
|
||||
store.clear();
|
||||
closeWalWriter();
|
||||
try {
|
||||
Files.deleteIfExists(walPath);
|
||||
Files.deleteIfExists(snapshotPath);
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to delete WAL/snapshot files");
|
||||
}
|
||||
openWalWriter();
|
||||
} finally {
|
||||
compactionLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
scheduler.shutdown();
|
||||
try {
|
||||
if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
scheduler.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
scheduler.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
compact();
|
||||
closeWalWriter();
|
||||
}
|
||||
|
||||
private void compact() {
|
||||
compactionLock.writeLock().lock();
|
||||
try {
|
||||
Files.createDirectories(snapshotPath.getParent());
|
||||
Path tempFile = snapshotPath.resolveSibling(snapshotPath.getFileName() + ".tmp");
|
||||
snapshotMapper.writeValue(tempFile.toFile(), store);
|
||||
Files.move(tempFile, snapshotPath, StandardCopyOption.REPLACE_EXISTING,
|
||||
StandardCopyOption.ATOMIC_MOVE);
|
||||
|
||||
closeWalWriter();
|
||||
Files.deleteIfExists(walPath);
|
||||
openWalWriter();
|
||||
|
||||
LOG.debugv("Compacted {0} entries to snapshot, WAL truncated", store.size());
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to compact WAL storage");
|
||||
} finally {
|
||||
compactionLock.writeLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private void appendPut(K key, V value) {
|
||||
DataOutputStream out = walWriter;
|
||||
if (out == null) return;
|
||||
try {
|
||||
byte[] keyBytes = walMapper.writeValueAsBytes(key);
|
||||
byte[] valueBytes = walMapper.writeValueAsBytes(value);
|
||||
synchronized (out) {
|
||||
out.writeByte(OP_PUT);
|
||||
out.writeInt(keyBytes.length);
|
||||
out.write(keyBytes);
|
||||
out.writeInt(valueBytes.length);
|
||||
out.write(valueBytes);
|
||||
out.flush();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to append PUT WAL entry");
|
||||
}
|
||||
}
|
||||
|
||||
private void appendDelete(K key) {
|
||||
DataOutputStream out = walWriter;
|
||||
if (out == null) return;
|
||||
try {
|
||||
byte[] keyBytes = walMapper.writeValueAsBytes(key);
|
||||
synchronized (out) {
|
||||
out.writeByte(OP_DELETE);
|
||||
out.writeInt(keyBytes.length);
|
||||
out.write(keyBytes);
|
||||
out.flush();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to append DELETE WAL entry");
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private int replayWal() {
|
||||
int replayed = 0;
|
||||
try (DataInputStream in = new DataInputStream(
|
||||
new BufferedInputStream(Files.newInputStream(walPath)))) {
|
||||
while (true) {
|
||||
int op;
|
||||
try {
|
||||
op = in.readByte();
|
||||
} catch (EOFException e) {
|
||||
break;
|
||||
}
|
||||
|
||||
int keyLen = in.readInt();
|
||||
byte[] keyBytes = in.readNBytes(keyLen);
|
||||
if (keyBytes.length < keyLen) break; // truncated entry
|
||||
|
||||
if (op == OP_PUT) {
|
||||
int valueLen = in.readInt();
|
||||
byte[] valueBytes = in.readNBytes(valueLen);
|
||||
if (valueBytes.length < valueLen) break; // truncated entry
|
||||
|
||||
K key = (K) walMapper.readValue(keyBytes, Object.class);
|
||||
V value = walMapper.readValue(valueBytes,
|
||||
walMapper.constructType(typeReference.getType()).getContentType());
|
||||
store.put(key, value);
|
||||
replayed++;
|
||||
} else if (op == OP_DELETE) {
|
||||
K key = (K) walMapper.readValue(keyBytes, Object.class);
|
||||
store.remove(key);
|
||||
replayed++;
|
||||
} else {
|
||||
LOG.errorv("Unknown WAL op byte: {0}, stopping replay", op);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to replay WAL from {0} (replayed {1} entries before error)",
|
||||
walPath, replayed);
|
||||
}
|
||||
return replayed;
|
||||
}
|
||||
|
||||
private void openWalWriter() {
|
||||
try {
|
||||
Files.createDirectories(walPath.getParent());
|
||||
walWriter = new DataOutputStream(
|
||||
new BufferedOutputStream(Files.newOutputStream(walPath,
|
||||
java.nio.file.StandardOpenOption.CREATE,
|
||||
java.nio.file.StandardOpenOption.APPEND)));
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to open WAL writer at {0}", walPath);
|
||||
}
|
||||
}
|
||||
|
||||
private void closeWalWriter() {
|
||||
if (walWriter != null) {
|
||||
try {
|
||||
walWriter.close();
|
||||
} catch (IOException e) {
|
||||
LOG.errorv(e, "Failed to close WAL writer");
|
||||
}
|
||||
walWriter = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package io.github.hectorvent.floci.lifecycle;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.ServiceRegistry;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
|
||||
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
|
||||
import io.quarkus.runtime.ShutdownEvent;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@ApplicationScoped
|
||||
public class EmulatorLifecycle {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EmulatorLifecycle.class);
|
||||
|
||||
private final StorageFactory storageFactory;
|
||||
private final ServiceRegistry serviceRegistry;
|
||||
private final EmulatorConfig config;
|
||||
private final ElastiCacheProxyManager elastiCacheProxyManager;
|
||||
private final RdsProxyManager rdsProxyManager;
|
||||
private final RdsContainerManager rdsContainerManager;
|
||||
|
||||
@Inject
|
||||
public EmulatorLifecycle(StorageFactory storageFactory, ServiceRegistry serviceRegistry,
|
||||
EmulatorConfig config, ElastiCacheProxyManager elastiCacheProxyManager,
|
||||
RdsProxyManager rdsProxyManager, RdsContainerManager rdsContainerManager) {
|
||||
this.storageFactory = storageFactory;
|
||||
this.serviceRegistry = serviceRegistry;
|
||||
this.config = config;
|
||||
this.elastiCacheProxyManager = elastiCacheProxyManager;
|
||||
this.rdsProxyManager = rdsProxyManager;
|
||||
this.rdsContainerManager = rdsContainerManager;
|
||||
}
|
||||
|
||||
void onStart(@Observes StartupEvent event) {
|
||||
LOG.info("=== AWS Local Emulator Starting ===");
|
||||
LOG.infov("Storage mode: {0}", config.storage().mode());
|
||||
LOG.infov("Persistent path: {0}", config.storage().persistentPath());
|
||||
serviceRegistry.logEnabledServices();
|
||||
|
||||
storageFactory.loadAll();
|
||||
LOG.info("=== AWS Local Emulator Ready ===");
|
||||
}
|
||||
|
||||
void onStop(@Observes ShutdownEvent event) {
|
||||
LOG.info("=== AWS Local Emulator Shutting Down ===");
|
||||
elastiCacheProxyManager.stopAll();
|
||||
rdsProxyManager.stopAll();
|
||||
storageFactory.shutdownAll();
|
||||
LOG.info("=== AWS Local Emulator Stopped ===");
|
||||
}
|
||||
}
|
||||
+993
@@ -0,0 +1,993 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.*;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
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.services.apigatewayv2.model.Api;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Unified AWS API Gateway management endpoints (v1 REST and v2 HTTP).
|
||||
*/
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes({MediaType.APPLICATION_JSON, "application/json-patch+json"})
|
||||
public class ApiGatewayController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ApiGatewayController.class);
|
||||
|
||||
private final ApiGatewayService service;
|
||||
private final ApiGatewayV2Service v2Service;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public ApiGatewayController(ApiGatewayService service, ApiGatewayV2Service v2Service,
|
||||
RegionResolver regionResolver, ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.v2Service = v2Service;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Specific v1 Paths (ORDER MATTERS) ────────────────────────────
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/responses/{statusCode}")
|
||||
public Response getMethodResponse(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod,
|
||||
@PathParam("statusCode") String statusCode) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toMethodResponseNode(service.getMethodResponse(region, apiId, resourceId, httpMethod, statusCode)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/responses/{statusCode}")
|
||||
public Response putMethodResponse(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod,
|
||||
@PathParam("statusCode") String statusCode,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
MethodResponse resp = service.putMethodResponse(region, apiId, resourceId, httpMethod, statusCode, request);
|
||||
return Response.status(201).entity(toMethodResponseNode(resp).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration/responses/{statusCode}")
|
||||
public Response getIntegrationResponse(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod,
|
||||
@PathParam("statusCode") String statusCode) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toIntegrationResponseNode(service.getIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration/responses/{statusCode}")
|
||||
public Response putIntegrationResponse(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod,
|
||||
@PathParam("statusCode") String statusCode,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
IntegrationResponse ir = service.putIntegrationResponse(region, apiId, resourceId, httpMethod, statusCode, request);
|
||||
return Response.status(201).entity(toIntegrationResponseNode(ir).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/authorizers/{authorizerId}")
|
||||
public Response getAuthorizer(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("authorizerId") String authorizerId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toAuthorizerNode(service.getAuthorizer(region, apiId, authorizerId)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/authorizers")
|
||||
public Response getAuthorizers(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<Authorizer> auths = service.getAuthorizers(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
auths.forEach(a -> items.add(toAuthorizerNode(a)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/stages/{stageName}")
|
||||
public Response getStage(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("stageName") String stageName) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toStageNode(service.getStage(region, apiId, stageName)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/stages")
|
||||
public Response getStages(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<Stage> stages = service.getStages(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
stages.forEach(s -> items.add(toStageNode(s)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── General REST APIs (v1) ────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/restapis")
|
||||
public Response createRestApi(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
RestApi api = service.createRestApi(region, request);
|
||||
return Response.status(201).entity(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis")
|
||||
public Response getRestApis(@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<RestApi> apis = service.getRestApis(region);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
apis.forEach(a -> items.add(toApiNode(a)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}")
|
||||
public Response getRestApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toApiNode(service.getRestApi(region, apiId)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/restapis/{apiId}")
|
||||
public Response updateRestApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
|
||||
RestApi api = service.updateRestApi(region, apiId, patchOperations);
|
||||
return Response.ok(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/restapis/{apiId}")
|
||||
public Response deleteRestApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteRestApi(region, apiId);
|
||||
return Response.accepted().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Resources (v1) ────────────────────────────
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/resources")
|
||||
public Response getResources(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<ApiGatewayResource> resources = service.getResources(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
resources.forEach(r -> items.add(toResourceNode(r)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}")
|
||||
public Response getResource(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toResourceNode(service.getResource(region, apiId, resourceId))).build();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}")
|
||||
public Response updateResource(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
|
||||
ApiGatewayResource resource = service.updateResource(region, apiId, resourceId, patchOperations);
|
||||
return Response.ok(toResourceNode(resource).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/restapis/{apiId}/resources/{parentId}")
|
||||
public Response createResource(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("parentId") String parentId,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
ApiGatewayResource resource = service.createResource(region, apiId, parentId, request);
|
||||
return Response.status(201).entity(toResourceNode(resource).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}")
|
||||
public Response deleteResource(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteResource(region, apiId, resourceId);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Methods (v1) ────────────────────────────
|
||||
|
||||
@PUT
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}")
|
||||
public Response putMethod(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
MethodConfig method = service.putMethod(region, apiId, resourceId, httpMethod, request);
|
||||
return Response.status(201).entity(toMethodNode(method).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}")
|
||||
public Response getMethod(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toMethodNode(service.getMethod(region, apiId, resourceId, httpMethod)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}")
|
||||
public Response updateMethod(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
|
||||
MethodConfig method = service.updateMethod(region, apiId, resourceId, httpMethod, patchOperations);
|
||||
return Response.ok(toMethodNode(method).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}")
|
||||
public Response deleteMethod(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteMethod(region, apiId, resourceId, httpMethod);
|
||||
return Response.accepted().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Integrations (v1) ────────────────────────────
|
||||
|
||||
@PUT
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration")
|
||||
public Response putIntegration(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
io.github.hectorvent.floci.services.apigateway.model.Integration integration = service.putIntegration(region, apiId, resourceId, httpMethod, request);
|
||||
return Response.status(201).entity(toIntegrationNode(integration).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration")
|
||||
public Response getIntegration(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toIntegrationNode(service.getIntegration(region, apiId, resourceId, httpMethod)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration")
|
||||
public Response updateIntegration(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
|
||||
io.github.hectorvent.floci.services.apigateway.model.Integration integration = service.updateIntegration(region, apiId, resourceId, httpMethod, patchOperations);
|
||||
return Response.ok(toIntegrationNode(integration).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/restapis/{apiId}/resources/{resourceId}/methods/{httpMethod}/integration")
|
||||
public Response deleteIntegration(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("resourceId") String resourceId,
|
||||
@PathParam("httpMethod") String httpMethod) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteIntegration(region, apiId, resourceId, httpMethod);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Deployments & Stages (v1) ────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/restapis/{apiId}/deployments")
|
||||
public Response createDeployment(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
Deployment deployment = service.createDeployment(region, apiId, request);
|
||||
return Response.status(201).entity(toDeploymentNode(deployment).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/deployments")
|
||||
public Response getDeployments(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<Deployment> deployments = service.getDeployments(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
deployments.forEach(d -> items.add(toDeploymentNode(d)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/restapis/{apiId}/stages")
|
||||
public Response createStage(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
Stage stage = service.createStage(region, apiId, request);
|
||||
return Response.status(201).entity(toStageNode(stage).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/restapis/{apiId}/stages/{stageName}")
|
||||
public Response updateStage(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("stageName") String stageName,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
com.fasterxml.jackson.databind.JsonNode node = objectMapper.readTree(body).path("patchOperations");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, String>> patchOperations = objectMapper.convertValue(node, List.class);
|
||||
Stage stage = service.updateStage(region, apiId, stageName, patchOperations);
|
||||
return Response.ok(toStageNode(stage).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/restapis/{apiId}/stages/{stageName}")
|
||||
public Response deleteStage(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("stageName") String stageName) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteStage(region, apiId, stageName);
|
||||
return Response.accepted().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Authorizers, API Keys, Usage Plans (v1) ────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/restapis/{apiId}/authorizers")
|
||||
public Response createAuthorizer(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
Authorizer auth = service.createAuthorizer(region, apiId, request);
|
||||
return Response.status(201).entity(toAuthorizerNode(auth).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/apikeys")
|
||||
public Response createApiKey(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
ApiKey key = service.createApiKey(region, request);
|
||||
return Response.status(201).entity(toApiKeyNode(key).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/apikeys")
|
||||
public Response getApiKeys(@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<ApiKey> keys = service.getApiKeys(region);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
keys.forEach(k -> items.add(toApiKeyNode(k)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/usageplans")
|
||||
public Response createUsagePlan(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
UsagePlan plan = service.createUsagePlan(region, request);
|
||||
return Response.status(201).entity(toUsagePlanNode(plan).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/usageplans")
|
||||
public Response getUsagePlans(@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<UsagePlan> plans = service.getUsagePlans(region);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
plans.forEach(p -> items.add(toUsagePlanNode(p)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/usageplans/{usagePlanId}")
|
||||
public Response deleteUsagePlan(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteUsagePlan(region, usagePlanId);
|
||||
return Response.accepted().build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/usageplans/{usagePlanId}/keys")
|
||||
public Response createUsagePlanKey(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
UsagePlanKey key = service.createUsagePlanKey(region, usagePlanId, request);
|
||||
return Response.status(201).entity(toUsagePlanKeyNode(key).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/usageplans/{usagePlanId}/keys")
|
||||
public Response getUsagePlanKeys(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<UsagePlanKey> keys = service.getUsagePlanKeys(region, usagePlanId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
keys.forEach(k -> items.add(toUsagePlanKeyNode(k)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/usageplans/{usagePlanId}/keys/{keyId}")
|
||||
public Response getUsagePlanKey(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId, @PathParam("keyId") String keyId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toUsagePlanKeyNode(service.getUsagePlanKey(region, usagePlanId, keyId)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/usageplans/{usagePlanId}/keys/{keyId}")
|
||||
public Response deleteUsagePlanKey(@Context HttpHeaders headers, @PathParam("usagePlanId") String usagePlanId, @PathParam("keyId") String keyId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteUsagePlanKey(region, usagePlanId, keyId);
|
||||
return Response.accepted().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Request Validators (v1) ────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/restapis/{apiId}/requestvalidators")
|
||||
public Response createRequestValidator(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
RequestValidator validator = service.createRequestValidator(region, apiId, request);
|
||||
return Response.status(201).entity(toRequestValidatorNode(validator).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/requestvalidators")
|
||||
public Response getRequestValidators(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<RequestValidator> validators = service.getRequestValidators(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
validators.forEach(v -> items.add(toRequestValidatorNode(v)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/restapis/{apiId}/requestvalidators/{validatorId}")
|
||||
public Response getRequestValidator(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("validatorId") String validatorId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toRequestValidatorNode(service.getRequestValidator(region, apiId, validatorId)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/restapis/{apiId}/requestvalidators/{validatorId}")
|
||||
public Response deleteRequestValidator(@Context HttpHeaders headers,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("validatorId") String validatorId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteRequestValidator(region, apiId, validatorId);
|
||||
return Response.accepted().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Custom Domains (v1) ────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/domainnames")
|
||||
public Response createDomainName(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
CustomDomain domain = service.createDomainName(region, request);
|
||||
return Response.status(201).entity(toDomainNode(domain).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/domainnames")
|
||||
public Response getDomainNames(@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<CustomDomain> domains = service.getDomainNames(region);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
domains.forEach(d -> items.add(toDomainNode(d)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/domainnames/{domainName}")
|
||||
public Response getDomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toDomainNode(service.getDomainName(region, domainName)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/domainnames/{domainName}")
|
||||
public Response deleteDomainName(@Context HttpHeaders headers, @PathParam("domainName") String domainName) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteDomainName(region, domainName);
|
||||
return Response.accepted().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Base Path Mappings (v1) ────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/domainnames/{domainName}/basepathmappings")
|
||||
public Response createBasePathMapping(@Context HttpHeaders headers, @PathParam("domainName") String domainName, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
BasePathMapping mapping = service.createBasePathMapping(region, domainName, request);
|
||||
return Response.status(201).entity(toMappingNode(mapping).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/domainnames/{domainName}/basepathmappings")
|
||||
public Response getBasePathMappings(@Context HttpHeaders headers, @PathParam("domainName") String domainName) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<BasePathMapping> mappings = service.getBasePathMappings(region, domainName);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("item");
|
||||
mappings.forEach(m -> items.add(toMappingNode(m)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/domainnames/{domainName}/basepathmappings/{basePath}")
|
||||
public Response getBasePathMapping(@Context HttpHeaders headers, @PathParam("domainName") String domainName, @PathParam("basePath") String basePath) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toMappingNode(service.getBasePathMapping(region, domainName, basePath)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/domainnames/{domainName}/basepathmappings/{basePath}")
|
||||
public Response deleteBasePathMapping(@Context HttpHeaders headers, @PathParam("domainName") String domainName, @PathParam("basePath") String basePath) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
service.deleteBasePathMapping(region, domainName, basePath);
|
||||
return Response.accepted().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── HTTP APIs (v2) ────────────────────────────
|
||||
|
||||
@POST
|
||||
@Path("/v2/apis")
|
||||
public Response createApi(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
Api api = v2Service.createApi(region, request);
|
||||
return Response.status(201).entity(toV2ApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/v2/apis")
|
||||
public Response getApis(@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<Api> apis = v2Service.getApis(region);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("items");
|
||||
apis.forEach(a -> items.add(toV2ApiNode(a)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/v2/apis/{apiId}")
|
||||
public Response getApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(toV2ApiNode(v2Service.getApi(region, apiId)).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/v2/apis/{apiId}")
|
||||
public Response deleteApi(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
v2Service.deleteApi(region, apiId);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/v2/apis/{apiId}/routes")
|
||||
public Response createRoute(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
Route route = v2Service.createRoute(region, apiId, request);
|
||||
return Response.status(201).entity(toV2RouteNode(route).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/v2/apis/{apiId}/routes")
|
||||
public Response getRoutes(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<Route> routes = v2Service.getRoutes(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("items");
|
||||
routes.forEach(r -> items.add(toV2RouteNode(r)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/v2/apis/{apiId}/integrations")
|
||||
public Response createIntegration(@Context HttpHeaders headers, @PathParam("apiId") String apiId, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = objectMapper.readValue(body, Map.class);
|
||||
Integration integration = v2Service.createIntegration(region, apiId, request);
|
||||
return Response.status(201).entity(toV2IntegrationNode(integration).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
} catch (IOException e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/v2/apis/{apiId}/integrations")
|
||||
public Response getIntegrations(@Context HttpHeaders headers, @PathParam("apiId") String apiId) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
List<Integration> integrations = v2Service.getIntegrations(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("items");
|
||||
integrations.forEach(i -> items.add(toV2IntegrationNode(i)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Tags ────────────────────────────
|
||||
|
||||
@GET
|
||||
@Path("/tags/{arn: .*}")
|
||||
public Response getTags(@Context HttpHeaders headers, @PathParam("arn") String arn) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
String apiId = apiIdFromArn(arn);
|
||||
Map<String, String> tags = service.getTags(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ObjectNode tagsNode = root.putObject("tags");
|
||||
tags.forEach(tagsNode::put);
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Helpers ────────────────────────────
|
||||
|
||||
private ObjectNode toApiNode(RestApi api) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", api.getId());
|
||||
node.put("name", api.getName());
|
||||
if (api.getDescription() != null) node.put("description", api.getDescription());
|
||||
node.put("createdDate", api.getCreatedDate());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toResourceNode(ApiGatewayResource r) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", r.getId());
|
||||
if (r.getParentId() != null) node.put("parentId", r.getParentId());
|
||||
if (r.getPathPart() != null) node.put("pathPart", r.getPathPart());
|
||||
node.put("path", r.getPath());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toMethodNode(MethodConfig m) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("httpMethod", m.getHttpMethod());
|
||||
node.put("authorizationType", m.getAuthorizationType());
|
||||
if (m.getAuthorizerId() != null) node.put("authorizerId", m.getAuthorizerId());
|
||||
if (m.getMethodIntegration() != null) {
|
||||
node.set("methodIntegration", toIntegrationNode(m.getMethodIntegration()));
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toMethodResponseNode(MethodResponse r) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("statusCode", r.statusCode());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toIntegrationNode(io.github.hectorvent.floci.services.apigateway.model.Integration i) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("type", i.getType());
|
||||
node.put("httpMethod", i.getHttpMethod());
|
||||
node.put("uri", i.getUri());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toIntegrationResponseNode(IntegrationResponse r) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("statusCode", r.statusCode());
|
||||
node.put("selectionPattern", r.selectionPattern());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toDeploymentNode(Deployment d) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", d.id());
|
||||
if (d.description() != null) node.put("description", d.description());
|
||||
node.put("createdDate", d.createdDate());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toStageNode(Stage s) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("stageName", s.getStageName());
|
||||
node.put("deploymentId", s.getDeploymentId());
|
||||
if (s.getDescription() != null) node.put("description", s.getDescription());
|
||||
node.put("createdDate", s.getCreatedDate());
|
||||
node.put("lastUpdatedDate", s.getLastUpdatedDate());
|
||||
if (!s.getVariables().isEmpty()) {
|
||||
ObjectNode vars = node.putObject("variables");
|
||||
s.getVariables().forEach(vars::put);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toAuthorizerNode(Authorizer a) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", a.getId());
|
||||
node.put("name", a.getName());
|
||||
node.put("type", a.getType());
|
||||
if (a.getAuthorizerUri() != null) node.put("authorizerUri", a.getAuthorizerUri());
|
||||
if (a.getIdentitySource() != null) node.put("identitySource", a.getIdentitySource());
|
||||
node.put("authorizerResultTtlInSeconds", Integer.parseInt(a.getAuthorizerResultTtlInSeconds()));
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toApiKeyNode(ApiKey k) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", k.getId());
|
||||
node.put("name", k.getName());
|
||||
node.put("value", k.getValue());
|
||||
node.put("enabled", k.isEnabled());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toUsagePlanNode(UsagePlan p) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", p.getId());
|
||||
node.put("name", p.getName());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toUsagePlanKeyNode(UsagePlanKey k) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", k.getId());
|
||||
node.put("name", k.getName());
|
||||
node.put("type", k.getType());
|
||||
node.put("value", k.getValue());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toDomainNode(CustomDomain d) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("domainName", d.getDomainName());
|
||||
node.put("domainNameStatus", d.getDomainNameStatus());
|
||||
node.put("endpointConfigurationType", d.getEndpointConfigurationType());
|
||||
if (d.getCertificateName() != null) node.put("certificateName", d.getCertificateName());
|
||||
if (d.getCertificateArn() != null) node.put("certificateArn", d.getCertificateArn());
|
||||
node.put("regionalDomainName", d.getRegionalDomainName());
|
||||
node.put("regionalHostedZoneId", d.getRegionalHostedZoneId());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toMappingNode(BasePathMapping m) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("basePath", m.getBasePath());
|
||||
node.put("restApiId", m.getRestApiId());
|
||||
node.put("stage", m.getStage());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toRequestValidatorNode(RequestValidator v) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("id", v.getId());
|
||||
node.put("name", v.getName());
|
||||
node.put("validateRequestBody", v.isValidateRequestBody());
|
||||
node.put("validateRequestParameters", v.isValidateRequestParameters());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toV2ApiNode(Api api) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("apiId", api.getApiId());
|
||||
node.put("name", api.getName());
|
||||
node.put("protocolType", api.getProtocolType());
|
||||
node.put("apiEndpoint", api.getApiEndpoint());
|
||||
node.put("createdDate", java.time.Instant.ofEpochMilli(api.getCreatedDate()).toString());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toV2RouteNode(Route r) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("routeId", r.getRouteId());
|
||||
node.put("routeKey", r.getRouteKey());
|
||||
node.put("authorizationType", r.getAuthorizationType());
|
||||
if (r.getTarget() != null) node.put("target", r.getTarget());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toV2IntegrationNode(Integration i) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("integrationId", i.getIntegrationId());
|
||||
node.put("integrationType", i.getIntegrationType());
|
||||
node.put("payloadFormatVersion", i.getPayloadFormatVersion());
|
||||
if (i.getIntegrationUri() != null) node.put("integrationUri", i.getIntegrationUri());
|
||||
return node;
|
||||
}
|
||||
|
||||
private String apiIdFromArn(String arn) {
|
||||
String[] parts = arn.split("/restapis/");
|
||||
if (parts.length < 2) return arn;
|
||||
return parts[1].split("/")[0];
|
||||
}
|
||||
}
|
||||
+645
@@ -0,0 +1,645 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.Integration;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.IntegrationResponse;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.*;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Executes API Gateway stage requests, routing them through the configured
|
||||
* integration (AWS_PROXY or MOCK).
|
||||
*
|
||||
* <p>Endpoint: {@code /{apiId}/{stageName}/{proxy+}}
|
||||
*
|
||||
* <p>This mirrors the real AWS execute-api URL format:
|
||||
* {@code https://{apiId}.execute-api.{region}.amazonaws.com/{stageName}/{path}}
|
||||
*/
|
||||
@Path("/execute-api/{apiId}/{stageName}")
|
||||
@Produces(MediaType.WILDCARD)
|
||||
public class ApiGatewayExecuteController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ApiGatewayExecuteController.class);
|
||||
|
||||
private final ApiGatewayService apiGatewayService;
|
||||
private final ApiGatewayV2Service apiGatewayV2Service;
|
||||
private final LambdaService lambdaService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,
|
||||
LambdaService lambdaService, RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper) {
|
||||
this.apiGatewayService = apiGatewayService;
|
||||
this.apiGatewayV2Service = apiGatewayV2Service;
|
||||
this.lambdaService = lambdaService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{proxy: .*}")
|
||||
public Response handleGet(@Context HttpHeaders headers, @Context UriInfo uriInfo,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("stageName") String stageName,
|
||||
@PathParam("proxy") String proxy) {
|
||||
return dispatch("GET", apiId, stageName, proxy, headers, uriInfo, null);
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/{proxy: .*}")
|
||||
public Response handlePost(@Context HttpHeaders headers, @Context UriInfo uriInfo,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("stageName") String stageName,
|
||||
@PathParam("proxy") String proxy,
|
||||
byte[] body) {
|
||||
return dispatch("POST", apiId, stageName, proxy, headers, uriInfo, body);
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/{proxy: .*}")
|
||||
public Response handlePut(@Context HttpHeaders headers, @Context UriInfo uriInfo,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("stageName") String stageName,
|
||||
@PathParam("proxy") String proxy,
|
||||
byte[] body) {
|
||||
return dispatch("PUT", apiId, stageName, proxy, headers, uriInfo, body);
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/{proxy: .*}")
|
||||
public Response handleDelete(@Context HttpHeaders headers, @Context UriInfo uriInfo,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("stageName") String stageName,
|
||||
@PathParam("proxy") String proxy) {
|
||||
return dispatch("DELETE", apiId, stageName, proxy, headers, uriInfo, null);
|
||||
}
|
||||
|
||||
@PATCH
|
||||
@Path("/{proxy: .*}")
|
||||
public Response handlePatch(@Context HttpHeaders headers, @Context UriInfo uriInfo,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("stageName") String stageName,
|
||||
@PathParam("proxy") String proxy,
|
||||
byte[] body) {
|
||||
return dispatch("PATCH", apiId, stageName, proxy, headers, uriInfo, body);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Core dispatch ────────────────────────────
|
||||
|
||||
private Response dispatch(String httpMethod, String apiId, String stageName,
|
||||
String proxy, HttpHeaders headers, UriInfo uriInfo, byte[] body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
|
||||
// Check if this is a v2 (HTTP API) or v1 (REST API)
|
||||
boolean isV2 = false;
|
||||
try {
|
||||
apiGatewayV2Service.getApi(region, apiId);
|
||||
isV2 = true;
|
||||
} catch (AwsException ignored) {
|
||||
// Not a v2 API — fall through to v1 handling
|
||||
}
|
||||
|
||||
if (isV2) {
|
||||
return dispatchV2(httpMethod, apiId, stageName, proxy, headers, uriInfo, body, region);
|
||||
}
|
||||
|
||||
// Verify API and stage exist
|
||||
try {
|
||||
apiGatewayService.getRestApi(region, apiId);
|
||||
apiGatewayService.getStage(region, apiId, stageName);
|
||||
} catch (AwsException e) {
|
||||
return Response.status(e.getHttpStatus())
|
||||
.entity(jsonMessage(e.getMessage()))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
String path = "/" + (proxy == null ? "" : proxy);
|
||||
|
||||
// Find matching resource and method
|
||||
List<ApiGatewayResource> resources = apiGatewayService.getResources(region, apiId);
|
||||
ApiGatewayResource matched = matchResource(resources, path);
|
||||
if (matched == null) {
|
||||
return Response.status(404)
|
||||
.entity(jsonMessage("Not Found"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
MethodConfig method = matched.getResourceMethods().get(httpMethod.toUpperCase());
|
||||
if (method == null) {
|
||||
return Response.status(405)
|
||||
.entity(jsonMessage("Method Not Allowed"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
// 1. Authorizer
|
||||
Response authResponse = invokeAuthorizer(region, apiId, method, headers, uriInfo);
|
||||
if (authResponse != null) return authResponse;
|
||||
|
||||
Integration integration = method.getMethodIntegration();
|
||||
if (integration == null) {
|
||||
return Response.status(500)
|
||||
.entity(jsonMessage("No integration configured"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
LOG.debugv("execute-api: {0} {1}/{2}{3} → {4}", httpMethod, apiId, stageName, path,
|
||||
integration.getType());
|
||||
|
||||
return switch (integration.getType().toUpperCase()) {
|
||||
case "AWS_PROXY" -> invokeProxy(region, httpMethod, path, proxy, stageName,
|
||||
matched, integration, headers, uriInfo, body);
|
||||
case "MOCK" -> invokeMock(integration);
|
||||
default -> Response.status(500)
|
||||
.entity(jsonMessage("Unsupported integration type: " + integration.getType()))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
};
|
||||
}
|
||||
|
||||
// ──────────────────────────── AWS_PROXY ────────────────────────────
|
||||
|
||||
private Response invokeProxy(String region, String httpMethod, String path, String proxy,
|
||||
String stageName, ApiGatewayResource resource,
|
||||
Integration integration, HttpHeaders headers,
|
||||
UriInfo uriInfo, byte[] body) {
|
||||
String functionName = functionNameFromUri(integration.getUri());
|
||||
if (functionName == null) {
|
||||
return Response.status(500)
|
||||
.entity(jsonMessage("Cannot resolve function from URI: " + integration.getUri()))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String eventJson = buildProxyEvent(httpMethod, path, proxy, resource.getPath(),
|
||||
stageName, headers, uriInfo, body, requestId);
|
||||
|
||||
try {
|
||||
InvokeResult result = lambdaService.invoke(region, functionName, eventJson.getBytes(),
|
||||
InvocationType.RequestResponse);
|
||||
return buildProxyResponse(result);
|
||||
} catch (AwsException e) {
|
||||
if (e.getHttpStatus() == 404) {
|
||||
return Response.status(404)
|
||||
.entity(jsonMessage("Function not found: " + functionName))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private Response invokeAuthorizer(String region, String apiId, MethodConfig method,
|
||||
HttpHeaders headers, UriInfo uriInfo) {
|
||||
if ("CUSTOM".equals(method.getAuthorizationType())) {
|
||||
String authorizerId = method.getAuthorizerId();
|
||||
if (authorizerId == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
io.github.hectorvent.floci.services.apigateway.model.Authorizer auth = apiGatewayService.getAuthorizer(region, apiId, authorizerId);
|
||||
String lambdaName = functionNameFromUri(auth.getAuthorizerUri());
|
||||
if (lambdaName == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String event = toAuthorizerEvent(auth, headers);
|
||||
try {
|
||||
InvokeResult result = lambdaService.invoke(region, lambdaName, event.getBytes(), InvocationType.RequestResponse);
|
||||
if (result.getFunctionError() != null) {
|
||||
return Response.status(403).build();
|
||||
}
|
||||
|
||||
JsonNode policy = objectMapper.readTree(result.getPayload());
|
||||
String effect = policy.path("policyDocument").path("Statement").get(0).path("Effect").asText("Deny");
|
||||
if ("Deny".equalsIgnoreCase(effect)) {
|
||||
return Response.status(403).entity(jsonMessage("User is not authorized to access this resource")).build();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Authorizer failure: {0}", e.getMessage());
|
||||
return Response.status(500).build();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String toAuthorizerEvent(io.github.hectorvent.floci.services.apigateway.model.Authorizer auth, HttpHeaders headers) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("type", auth.getType());
|
||||
node.put("methodArn", "arn:aws:execute-api:" + regionResolver.getDefaultRegion()
|
||||
+ ":" + regionResolver.getAccountId() + ":api/stage/METHOD/path");
|
||||
if ("TOKEN".equals(auth.getType())) {
|
||||
String headerName = auth.getIdentitySource().replace("method.request.header.", "");
|
||||
node.put("authorizationToken", headers.getHeaderString(headerName));
|
||||
}
|
||||
return node.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts function name from integration URI like
|
||||
* {@code arn:aws:apigateway:...:lambda:path/2015-03-31/functions/{fnArn}/invocations}.
|
||||
*/
|
||||
private String functionNameFromUri(String uri) {
|
||||
if (uri == null) {
|
||||
return null;
|
||||
}
|
||||
// URI contains "function:{name}" or "function:{arn}"
|
||||
int idx = uri.indexOf("function:");
|
||||
if (idx < 0) {
|
||||
return null;
|
||||
}
|
||||
String after = uri.substring(idx + "function:".length());
|
||||
// after may be "myFn/invocations" or "arn:aws:lambda:...:function:myFn/invocations"
|
||||
// If it starts with "arn:" recurse on the remaining ARN
|
||||
if (after.startsWith("arn:")) {
|
||||
int fnIdx = after.lastIndexOf(":function:");
|
||||
if (fnIdx < 0) {
|
||||
return null;
|
||||
}
|
||||
after = after.substring(fnIdx + ":function:".length());
|
||||
}
|
||||
// Strip trailing "/invocations" or any path suffix
|
||||
int slash = after.indexOf('/');
|
||||
return slash >= 0 ? after.substring(0, slash) : after;
|
||||
}
|
||||
|
||||
private String buildProxyEvent(String httpMethod, String path, String proxy,
|
||||
String resourcePath, String stageName,
|
||||
HttpHeaders headers, UriInfo uriInfo,
|
||||
byte[] body, String requestId) {
|
||||
ObjectNode event = objectMapper.createObjectNode();
|
||||
event.put("resource", resourcePath);
|
||||
event.put("path", path);
|
||||
event.put("httpMethod", httpMethod);
|
||||
|
||||
ObjectNode headersNode = event.putObject("headers");
|
||||
MultivaluedMap<String, String> reqHeaders = headers.getRequestHeaders();
|
||||
for (Map.Entry<String, java.util.List<String>> e : reqHeaders.entrySet()) {
|
||||
if (!e.getValue().isEmpty()) headersNode.put(e.getKey(), e.getValue().get(0));
|
||||
}
|
||||
|
||||
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
|
||||
if (!queryParams.isEmpty()) {
|
||||
ObjectNode qsp = event.putObject("queryStringParameters");
|
||||
for (Map.Entry<String, java.util.List<String>> e : queryParams.entrySet()) {
|
||||
if (!e.getValue().isEmpty()) qsp.put(e.getKey(), e.getValue().get(0));
|
||||
}
|
||||
} else {
|
||||
event.putNull("queryStringParameters");
|
||||
}
|
||||
|
||||
ObjectNode pathParams = event.putObject("pathParameters");
|
||||
if (proxy != null && !proxy.isEmpty()) pathParams.put("proxy", proxy);
|
||||
|
||||
event.putNull("stageVariables");
|
||||
|
||||
ObjectNode ctx = event.putObject("requestContext");
|
||||
ctx.put("resourcePath", resourcePath);
|
||||
ctx.put("httpMethod", httpMethod);
|
||||
ctx.put("stage", stageName);
|
||||
ctx.put("requestId", requestId);
|
||||
ctx.put("requestTimeEpoch", System.currentTimeMillis());
|
||||
ctx.putObject("identity").put("sourceIp", "127.0.0.1");
|
||||
|
||||
if (body != null && body.length > 0) {
|
||||
event.put("body", new String(body));
|
||||
event.put("isBase64Encoded", false);
|
||||
} else {
|
||||
event.putNull("body");
|
||||
event.put("isBase64Encoded", false);
|
||||
}
|
||||
|
||||
try {
|
||||
return objectMapper.writeValueAsString(event);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize proxy event", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Response buildProxyResponse(InvokeResult result) {
|
||||
if (result.getPayload() == null || result.getPayload().length == 0) {
|
||||
return Response.status(result.getFunctionError() != null ? 502 : result.getStatusCode()).build();
|
||||
}
|
||||
try {
|
||||
JsonNode node = objectMapper.readTree(result.getPayload());
|
||||
int statusCode = node.path("statusCode").asInt(200);
|
||||
if (result.getFunctionError() != null && !node.has("statusCode")) statusCode = 502;
|
||||
|
||||
Response.ResponseBuilder builder = Response.status(statusCode);
|
||||
|
||||
JsonNode respHeaders = node.get("headers");
|
||||
if (respHeaders != null && respHeaders.isObject()) {
|
||||
respHeaders.fields().forEachRemaining(e -> builder.header(e.getKey(), e.getValue().asText()));
|
||||
}
|
||||
JsonNode multiHeaders = node.get("multiValueHeaders");
|
||||
if (multiHeaders != null && multiHeaders.isObject()) {
|
||||
multiHeaders.fields().forEachRemaining(e -> {
|
||||
if (e.getValue().isArray()) e.getValue().forEach(v -> builder.header(e.getKey(), v.asText()));
|
||||
});
|
||||
}
|
||||
|
||||
JsonNode bodyNode = node.get("body");
|
||||
if (bodyNode != null && !bodyNode.isNull()) {
|
||||
String bodyStr = bodyNode.asText();
|
||||
boolean isBase64 = node.path("isBase64Encoded").asBoolean(false);
|
||||
byte[] bytes = isBase64 ? Base64.getDecoder().decode(bodyStr) : bodyStr.getBytes();
|
||||
String ct = MediaType.APPLICATION_JSON;
|
||||
JsonNode ctNode = node.path("headers").path("Content-Type");
|
||||
if (!ctNode.isMissingNode() && !ctNode.isNull()) ct = ctNode.asText();
|
||||
builder.entity(bytes).type(ct);
|
||||
}
|
||||
return builder.build();
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to parse Lambda response: {0}", e.getMessage());
|
||||
return Response.status(502).entity(result.getPayload()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── MOCK ────────────────────────────
|
||||
|
||||
private Response invokeMock(Integration integration) {
|
||||
// Use the "200" integration response if present, else return empty 200
|
||||
IntegrationResponse ir = integration.getIntegrationResponses().get("200");
|
||||
if (ir == null) {
|
||||
return Response.ok().build();
|
||||
}
|
||||
String template = ir.responseTemplates() != null
|
||||
? ir.responseTemplates().getOrDefault("application/json", "") : "";
|
||||
return Response.status(Integer.parseInt(ir.statusCode()))
|
||||
.entity(template)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── API Gateway v2 dispatch ────────────────────────────
|
||||
|
||||
private Response dispatchV2(String httpMethod, String apiId, String stageName,
|
||||
String proxy, HttpHeaders headers, UriInfo uriInfo,
|
||||
byte[] body, String region) {
|
||||
String path = "/" + (proxy == null ? "" : proxy);
|
||||
|
||||
Route route = apiGatewayV2Service.findMatchingRoute(region, apiId, httpMethod, path);
|
||||
if (route == null) {
|
||||
return Response.status(404)
|
||||
.entity(jsonMessage("Not Found"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
if ("JWT".equalsIgnoreCase(route.getAuthorizationType()) && route.getAuthorizerId() != null) {
|
||||
Response authError = enforceJwtAuthorizer(region, apiId, route, headers);
|
||||
if (authError != null) return authError;
|
||||
}
|
||||
|
||||
if (route.getTarget() == null) {
|
||||
return Response.status(500)
|
||||
.entity(jsonMessage("No integration configured"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
// target is "integrations/{integrationId}"
|
||||
String integrationId = route.getTarget().startsWith("integrations/")
|
||||
? route.getTarget().substring("integrations/".length()) : route.getTarget();
|
||||
|
||||
io.github.hectorvent.floci.services.apigatewayv2.model.Integration integration;
|
||||
try {
|
||||
integration = apiGatewayV2Service.getIntegration(region, apiId, integrationId);
|
||||
} catch (AwsException e) {
|
||||
return Response.status(500)
|
||||
.entity(jsonMessage("Integration not found: " + integrationId))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
String functionName = functionNameFromUri(integration.getIntegrationUri());
|
||||
if (functionName == null) {
|
||||
return Response.status(500)
|
||||
.entity(jsonMessage("Cannot resolve function from URI: " + integration.getIntegrationUri()))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String eventJson = buildV2ProxyEvent(httpMethod, path, route.getRouteKey(),
|
||||
apiId, stageName, headers, uriInfo, body, requestId);
|
||||
|
||||
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → Lambda {4}", httpMethod, apiId, stageName, path, functionName);
|
||||
|
||||
try {
|
||||
InvokeResult result = lambdaService.invoke(region, functionName,
|
||||
eventJson.getBytes(), InvocationType.RequestResponse);
|
||||
return buildProxyResponse(result);
|
||||
} catch (AwsException e) {
|
||||
if (e.getHttpStatus() == 404) {
|
||||
return Response.status(404)
|
||||
.entity(jsonMessage("Function not found: " + functionName))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private Response enforceJwtAuthorizer(String region, String apiId, Route route, HttpHeaders headers) {
|
||||
Authorizer authorizer;
|
||||
try {
|
||||
authorizer = apiGatewayV2Service.getAuthorizer(region, apiId, route.getAuthorizerId());
|
||||
} catch (AwsException e) {
|
||||
return Response.status(500)
|
||||
.entity(jsonMessage("Authorizer not found"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
String token = extractToken(authorizer, headers);
|
||||
if (token == null) {
|
||||
return Response.status(401)
|
||||
.entity(jsonMessage("Unauthorized"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
JwtClaims claims = parseJwtClaims(token);
|
||||
if (claims == null) {
|
||||
return Response.status(401)
|
||||
.entity(jsonMessage("Unauthorized"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
if (claims.exp > 0 && claims.exp < System.currentTimeMillis() / 1000) {
|
||||
return Response.status(401)
|
||||
.entity(jsonMessage("The incoming token has expired"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
if (authorizer.getJwtConfiguration() != null) {
|
||||
String issuer = authorizer.getJwtConfiguration().issuer();
|
||||
if (issuer != null && !issuer.isBlank() && !issuer.equals(claims.iss)) {
|
||||
return Response.status(401)
|
||||
.entity(jsonMessage("Unauthorized"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
List<String> audiences = authorizer.getJwtConfiguration().audience();
|
||||
if (audiences != null && !audiences.isEmpty()) {
|
||||
boolean audMatch = audiences.stream().anyMatch(a -> a.equals(claims.aud));
|
||||
if (!audMatch) {
|
||||
return Response.status(401)
|
||||
.entity(jsonMessage("Unauthorized"))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null; // authorized
|
||||
}
|
||||
|
||||
private String extractToken(Authorizer authorizer, HttpHeaders headers) {
|
||||
List<String> sources = authorizer.getIdentitySource();
|
||||
if (sources == null || sources.isEmpty()) {
|
||||
// Default: Authorization header
|
||||
String raw = headers.getHeaderString("Authorization");
|
||||
return stripBearer(raw);
|
||||
}
|
||||
for (String source : sources) {
|
||||
if (source.startsWith("$request.header.")) {
|
||||
String headerName = source.substring("$request.header.".length());
|
||||
String value = headers.getHeaderString(headerName);
|
||||
if (value != null) return stripBearer(value);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String stripBearer(String value) {
|
||||
if (value == null) return null;
|
||||
if (value.startsWith("Bearer ")) return value.substring(7);
|
||||
return value;
|
||||
}
|
||||
|
||||
private record JwtClaims(String iss, String aud, long exp) {}
|
||||
|
||||
private JwtClaims parseJwtClaims(String token) {
|
||||
try {
|
||||
String[] parts = token.split("\\.");
|
||||
if (parts.length < 2) return null;
|
||||
byte[] payloadBytes = Base64.getUrlDecoder().decode(padBase64(parts[1]));
|
||||
String payload = new String(payloadBytes, StandardCharsets.UTF_8);
|
||||
JsonNode claims = objectMapper.readTree(payload);
|
||||
String iss = claims.path("iss").asText(null);
|
||||
String aud = claims.path("aud").asText(null);
|
||||
long exp = claims.path("exp").asLong(0);
|
||||
return new JwtClaims(iss, aud, exp);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("JWT parse error: {0}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String padBase64(String base64) {
|
||||
return switch (base64.length() % 4) {
|
||||
case 2 -> base64 + "==";
|
||||
case 3 -> base64 + "=";
|
||||
default -> base64;
|
||||
};
|
||||
}
|
||||
|
||||
private String buildV2ProxyEvent(String httpMethod, String path, String routeKey,
|
||||
String apiId, String stageName,
|
||||
HttpHeaders headers, UriInfo uriInfo,
|
||||
byte[] body, String requestId) {
|
||||
ObjectNode event = objectMapper.createObjectNode();
|
||||
event.put("version", "2.0");
|
||||
event.put("routeKey", routeKey != null ? routeKey : "$default");
|
||||
event.put("rawPath", path);
|
||||
|
||||
MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
|
||||
event.put("rawQueryString", uriInfo.getRequestUri().getRawQuery() != null
|
||||
? uriInfo.getRequestUri().getRawQuery() : "");
|
||||
|
||||
ObjectNode headersNode = event.putObject("headers");
|
||||
for (Map.Entry<String, java.util.List<String>> e : headers.getRequestHeaders().entrySet()) {
|
||||
if (!e.getValue().isEmpty()) headersNode.put(e.getKey().toLowerCase(), e.getValue().get(0));
|
||||
}
|
||||
|
||||
if (!queryParams.isEmpty()) {
|
||||
ObjectNode qsp = event.putObject("queryStringParameters");
|
||||
for (Map.Entry<String, java.util.List<String>> e : queryParams.entrySet()) {
|
||||
if (!e.getValue().isEmpty()) qsp.put(e.getKey(), e.getValue().get(0));
|
||||
}
|
||||
}
|
||||
|
||||
ObjectNode ctx = event.putObject("requestContext");
|
||||
ctx.put("accountId", "000000000000");
|
||||
ctx.put("apiId", apiId);
|
||||
ctx.put("domainName", apiId + ".execute-api.us-east-1.amazonaws.com");
|
||||
ctx.put("domainPrefix", apiId);
|
||||
ctx.put("requestId", requestId);
|
||||
ctx.put("routeKey", routeKey != null ? routeKey : "$default");
|
||||
ctx.put("stage", stageName);
|
||||
ctx.put("time", java.time.format.DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z")
|
||||
.format(java.time.ZonedDateTime.now()));
|
||||
ctx.put("timeEpoch", System.currentTimeMillis());
|
||||
|
||||
ObjectNode http = ctx.putObject("http");
|
||||
http.put("method", httpMethod);
|
||||
http.put("path", path);
|
||||
http.put("protocol", "HTTP/1.1");
|
||||
http.put("sourceIp", "127.0.0.1");
|
||||
http.put("userAgent", headers.getHeaderString("User-Agent") != null
|
||||
? headers.getHeaderString("User-Agent") : "");
|
||||
|
||||
if (body != null && body.length > 0) {
|
||||
event.put("body", new String(body));
|
||||
event.put("isBase64Encoded", false);
|
||||
} else {
|
||||
event.putNull("body");
|
||||
event.put("isBase64Encoded", false);
|
||||
}
|
||||
|
||||
try {
|
||||
return objectMapper.writeValueAsString(event);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize v2 proxy event", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String jsonMessage(String message) {
|
||||
return objectMapper.createObjectNode().put("message", message).toString();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Path matching ────────────────────────────
|
||||
|
||||
/**
|
||||
* Finds the best-matching resource for {@code requestPath}.
|
||||
* Priority: exact match > wildcard/proxy+ match.
|
||||
*/
|
||||
private ApiGatewayResource matchResource(List<ApiGatewayResource> resources, String requestPath) {
|
||||
// 1. Exact match
|
||||
for (ApiGatewayResource r : resources) {
|
||||
if (requestPath.equals(r.getPath())) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
// 2. Wildcard / {proxy+} — any resource whose pathPart contains "{"
|
||||
for (ApiGatewayResource r : resources) {
|
||||
if (r.getPathPart() != null && r.getPathPart().contains("{")) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,737 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.*;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@ApplicationScoped
|
||||
public class ApiGatewayService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ApiGatewayService.class);
|
||||
|
||||
private final StorageBackend<String, RestApi> apiStore;
|
||||
private final StorageBackend<String, ApiGatewayResource> resourceStore;
|
||||
private final StorageBackend<String, Deployment> deploymentStore;
|
||||
private final StorageBackend<String, Stage> stageStore;
|
||||
private final StorageBackend<String, Authorizer> authorizerStore;
|
||||
private final StorageBackend<String, ApiKey> apiKeyStore;
|
||||
private final StorageBackend<String, UsagePlan> usagePlanStore;
|
||||
private final StorageBackend<String, UsagePlanKey> usagePlanKeyStore;
|
||||
private final StorageBackend<String, RequestValidator> requestValidatorStore;
|
||||
private final StorageBackend<String, CustomDomain> domainStore;
|
||||
private final StorageBackend<String, BasePathMapping> basePathMappingStore;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public ApiGatewayService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) {
|
||||
this.apiStore = storageFactory.create("apigateway", "apigateway-apis.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.resourceStore = storageFactory.create("apigateway", "apigateway-resources.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.deploymentStore = storageFactory.create("apigateway", "apigateway-deployments.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.stageStore = storageFactory.create("apigateway", "apigateway-stages.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.authorizerStore = storageFactory.create("apigateway", "apigateway-authorizers.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.apiKeyStore = storageFactory.create("apigateway", "apigateway-apikeys.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.usagePlanStore = storageFactory.create("apigateway", "apigateway-usageplans.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.usagePlanKeyStore = storageFactory.create("apigateway", "apigateway-usageplankeys.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.requestValidatorStore = storageFactory.create("apigateway", "apigateway-validators.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.domainStore = storageFactory.create("apigateway", "apigateway-domains.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.basePathMappingStore = storageFactory.create("apigateway", "apigateway-mappings.json",
|
||||
new TypeReference<>() {
|
||||
});
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
// ──────────────────────────── REST API CRUD ────────────────────────────
|
||||
|
||||
public RestApi createRestApi(String region, Map<String, Object> request) {
|
||||
String name = (String) request.get("name");
|
||||
String description = (String) request.get("description");
|
||||
|
||||
RestApi api = new RestApi();
|
||||
api.setId(shortId(10));
|
||||
api.setName(name);
|
||||
api.setDescription(description);
|
||||
api.setCreatedDate(System.currentTimeMillis() / 1000L);
|
||||
|
||||
apiStore.put(apiKey(region, api.getId()), api);
|
||||
|
||||
// Create root resource "/"
|
||||
ApiGatewayResource root = new ApiGatewayResource();
|
||||
root.setId(shortId(8));
|
||||
root.setPath("/");
|
||||
resourceStore.put(resourceKey(region, api.getId(), root.getId()), root);
|
||||
|
||||
LOG.infov("Created REST API: {0} ({1}) in {2}", name, api.getId(), region);
|
||||
return api;
|
||||
}
|
||||
|
||||
public RestApi getRestApi(String region, String apiId) {
|
||||
return apiStore.get(apiKey(region, apiId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid API id specified", 404));
|
||||
}
|
||||
|
||||
public List<RestApi> getRestApis(String region) {
|
||||
String prefix = region + "::";
|
||||
return apiStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteRestApi(String region, String apiId) {
|
||||
getRestApi(region, apiId);
|
||||
apiStore.delete(apiKey(region, apiId));
|
||||
// Simple cascade: delete resources for this API
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
resourceStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(resourceStore::delete);
|
||||
deploymentStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(deploymentStore::delete);
|
||||
stageStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(stageStore::delete);
|
||||
LOG.infov("Deleted REST API: {0} in {1}", apiId, region);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Resource CRUD ────────────────────────────
|
||||
|
||||
public List<ApiGatewayResource> getResources(String region, String apiId) {
|
||||
getRestApi(region, apiId);
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
return resourceStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public ApiGatewayResource getResource(String region, String apiId, String resourceId) {
|
||||
return resourceStore.get(resourceKey(region, apiId, resourceId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid resource id specified", 404));
|
||||
}
|
||||
|
||||
public ApiGatewayResource createResource(String region, String apiId, String parentId, Map<String, Object> request) {
|
||||
getRestApi(region, apiId);
|
||||
ApiGatewayResource parent = getResource(region, apiId, parentId);
|
||||
String pathPart = (String) request.get("pathPart");
|
||||
|
||||
ApiGatewayResource resource = new ApiGatewayResource();
|
||||
resource.setId(shortId(8));
|
||||
resource.setParentId(parentId);
|
||||
resource.setPathPart(pathPart);
|
||||
String childPath = parent.getPath().equals("/") ? "/" + pathPart : parent.getPath() + "/" + pathPart;
|
||||
resource.setPath(childPath);
|
||||
|
||||
resourceStore.put(resourceKey(region, apiId, resource.getId()), resource);
|
||||
LOG.infov("Created resource {0} path={1} in API {2}", resource.getId(), childPath, apiId);
|
||||
return resource;
|
||||
}
|
||||
|
||||
public void deleteResource(String region, String apiId, String resourceId) {
|
||||
getResource(region, apiId, resourceId);
|
||||
resourceStore.delete(resourceKey(region, apiId, resourceId));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Method CRUD ────────────────────────────
|
||||
|
||||
public MethodConfig putMethod(String region, String apiId, String resourceId, String httpMethod, Map<String, Object> request) {
|
||||
ApiGatewayResource resource = getResource(region, apiId, resourceId);
|
||||
MethodConfig method = new MethodConfig();
|
||||
method.setHttpMethod(httpMethod.toUpperCase());
|
||||
method.setAuthorizationType((String) request.getOrDefault("authorizationType", "NONE"));
|
||||
method.setAuthorizerId((String) request.get("authorizerId"));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Boolean> reqParams = (Map<String, Boolean>) request.get("requestParameters");
|
||||
if (reqParams != null) method.setRequestParameters(reqParams);
|
||||
|
||||
resource.getResourceMethods().put(httpMethod.toUpperCase(), method);
|
||||
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
|
||||
return method;
|
||||
}
|
||||
|
||||
public MethodConfig getMethod(String region, String apiId, String resourceId, String httpMethod) {
|
||||
ApiGatewayResource resource = getResource(region, apiId, resourceId);
|
||||
MethodConfig method = resource.getResourceMethods().get(httpMethod.toUpperCase());
|
||||
if (method == null) {
|
||||
throw new AwsException("NotFoundException", "Invalid method specified", 404);
|
||||
}
|
||||
return method;
|
||||
}
|
||||
|
||||
public void deleteMethod(String region, String apiId, String resourceId, String httpMethod) {
|
||||
ApiGatewayResource resource = getResource(region, apiId, resourceId);
|
||||
resource.getResourceMethods().remove(httpMethod.toUpperCase());
|
||||
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
|
||||
}
|
||||
|
||||
public MethodResponse putMethodResponse(String region, String apiId, String resourceId,
|
||||
String httpMethod, String statusCode,
|
||||
Map<String, Object> request) {
|
||||
MethodConfig method = getMethod(region, apiId, resourceId, httpMethod);
|
||||
MethodResponse mr = new MethodResponse(statusCode, new HashMap<>());
|
||||
method.getMethodResponses().put(statusCode, mr);
|
||||
resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId));
|
||||
return mr;
|
||||
}
|
||||
|
||||
public MethodResponse getMethodResponse(String region, String apiId, String resourceId,
|
||||
String httpMethod, String statusCode) {
|
||||
MethodConfig method = getMethod(region, apiId, resourceId, httpMethod);
|
||||
MethodResponse mr = method.getMethodResponses().get(statusCode);
|
||||
if (mr == null) {
|
||||
throw new AwsException("NotFoundException", "Invalid response status code specified", 404);
|
||||
}
|
||||
return mr;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Integrations ────────────────────────────
|
||||
|
||||
public Integration putIntegration(String region, String apiId, String resourceId, String httpMethod, Map<String, Object> request) {
|
||||
ApiGatewayResource resource = getResource(region, apiId, resourceId);
|
||||
MethodConfig method = getMethod(region, apiId, resourceId, httpMethod);
|
||||
|
||||
Integration integration = new Integration();
|
||||
integration.setType((String) request.get("type"));
|
||||
integration.setHttpMethod((String) request.get("httpMethod"));
|
||||
integration.setUri((String) request.get("uri"));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> reqTemplates = (Map<String, String>) request.get("requestTemplates");
|
||||
if (reqTemplates != null) integration.setRequestTemplates(reqTemplates);
|
||||
|
||||
method.setMethodIntegration(integration);
|
||||
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
|
||||
return integration;
|
||||
}
|
||||
|
||||
public Integration getIntegration(String region, String apiId, String resourceId, String httpMethod) {
|
||||
MethodConfig method = getMethod(region, apiId, resourceId, httpMethod);
|
||||
if (method.getMethodIntegration() == null) {
|
||||
throw new AwsException("NotFoundException", "Integration not found", 404);
|
||||
}
|
||||
return method.getMethodIntegration();
|
||||
}
|
||||
|
||||
public void deleteIntegration(String region, String apiId, String resourceId, String httpMethod) {
|
||||
ApiGatewayResource resource = getResource(region, apiId, resourceId);
|
||||
MethodConfig method = resource.getResourceMethods().get(httpMethod.toUpperCase());
|
||||
if (method == null || method.getMethodIntegration() == null) {
|
||||
throw new AwsException("NotFoundException", "Integration not found", 404);
|
||||
}
|
||||
method.setMethodIntegration(null);
|
||||
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Integration Responses ────────────────────────────
|
||||
|
||||
public IntegrationResponse putIntegrationResponse(String region, String apiId, String resourceId,
|
||||
String httpMethod, String statusCode,
|
||||
Map<String, Object> request) {
|
||||
Integration integration = getIntegration(region, apiId, resourceId, httpMethod);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> respParams = (Map<String, String>) request.get("responseParameters");
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> respTemplates = (Map<String, String>) request.get("responseTemplates");
|
||||
String selectionPattern = (String) request.getOrDefault("selectionPattern", "");
|
||||
|
||||
IntegrationResponse ir = new IntegrationResponse(statusCode, selectionPattern,
|
||||
respParams != null ? respParams : new HashMap<>(),
|
||||
respTemplates != null ? respTemplates : new HashMap<>());
|
||||
|
||||
integration.getIntegrationResponses().put(statusCode, ir);
|
||||
resourceStore.put(resourceKey(region, apiId, resourceId),
|
||||
getResource(region, apiId, resourceId));
|
||||
return ir;
|
||||
}
|
||||
|
||||
public IntegrationResponse getIntegrationResponse(String region, String apiId, String resourceId,
|
||||
String httpMethod, String statusCode) {
|
||||
Integration integration = getIntegration(region, apiId, resourceId, httpMethod);
|
||||
IntegrationResponse ir = integration.getIntegrationResponses().get(statusCode);
|
||||
if (ir == null) {
|
||||
throw new AwsException("NotFoundException", "Invalid response status code specified", 404);
|
||||
}
|
||||
return ir;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Deployments ────────────────────────────
|
||||
|
||||
public Deployment createDeployment(String region, String apiId, Map<String, Object> request) {
|
||||
getRestApi(region, apiId);
|
||||
String description = (String) request.getOrDefault("description", "");
|
||||
Deployment deployment = new Deployment(shortId(10), description, System.currentTimeMillis() / 1000L);
|
||||
deploymentStore.put(deploymentKey(region, apiId, deployment.id()), deployment);
|
||||
LOG.infov("Created deployment {0} for API {1}", deployment.id(), apiId);
|
||||
return deployment;
|
||||
}
|
||||
|
||||
public List<Deployment> getDeployments(String region, String apiId) {
|
||||
getRestApi(region, apiId);
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
return deploymentStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public Deployment getDeployment(String region, String apiId, String deploymentId) {
|
||||
return deploymentStore.get(deploymentKey(region, apiId, deploymentId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Deployment not found", 404));
|
||||
}
|
||||
|
||||
public void deleteDeployment(String region, String apiId, String deploymentId) {
|
||||
getDeployment(region, apiId, deploymentId);
|
||||
deploymentStore.delete(deploymentKey(region, apiId, deploymentId));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Stages ────────────────────────────
|
||||
|
||||
public Stage createStage(String region, String apiId, Map<String, Object> request) {
|
||||
getRestApi(region, apiId);
|
||||
String stageName = (String) request.get("stageName");
|
||||
String deploymentId = (String) request.get("deploymentId");
|
||||
|
||||
if (stageName == null || stageName.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "stageName is required", 400);
|
||||
}
|
||||
if (deploymentId == null || deploymentId.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "deploymentId is required", 400);
|
||||
}
|
||||
|
||||
Stage stage = new Stage();
|
||||
stage.setStageName(stageName);
|
||||
stage.setDeploymentId(deploymentId);
|
||||
stage.setDescription((String) request.get("description"));
|
||||
stage.setCreatedDate(System.currentTimeMillis() / 1000L);
|
||||
stage.setLastUpdatedDate(stage.getCreatedDate());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> variables = (Map<String, String>) request.get("variables");
|
||||
if (variables != null) stage.setVariables(variables);
|
||||
|
||||
stageStore.put(stageKey(region, apiId, stageName), stage);
|
||||
LOG.infov("Created stage {0} for API {1}", stageName, apiId);
|
||||
return stage;
|
||||
}
|
||||
|
||||
public Stage getStage(String region, String apiId, String stageName) {
|
||||
getRestApi(region, apiId);
|
||||
return stageStore.get(stageKey(region, apiId, stageName))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Stage not found", 404));
|
||||
}
|
||||
|
||||
public List<Stage> getStages(String region, String apiId) {
|
||||
getRestApi(region, apiId);
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
return stageStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public Stage updateStage(String region, String apiId, String stageName,
|
||||
List<Map<String, String>> patchOperations) {
|
||||
Stage stage = getStage(region, apiId, stageName);
|
||||
LOG.infov("Updating stage {0} with {1} operations", stageName, patchOperations != null ? patchOperations.size() : 0);
|
||||
if (patchOperations != null) {
|
||||
for (Map<String, String> op : patchOperations) {
|
||||
String opType = op.get("op");
|
||||
String path = op.getOrDefault("path", "");
|
||||
String value = op.get("value");
|
||||
LOG.infov("Patch operation: op={0}, path={1}, value={2}", opType, path, value);
|
||||
|
||||
if (!"replace" .equals(opType) && !"add" .equals(opType)) continue;
|
||||
|
||||
if ("/description" .equals(path)) {
|
||||
stage.setDescription(value);
|
||||
} else if ("/deploymentId" .equals(path)) {
|
||||
stage.setDeploymentId(value);
|
||||
} else if (path.startsWith("/variables/")) {
|
||||
String varKey = path.substring("/variables/" .length());
|
||||
LOG.infov("Setting stage variable {0} = {1}", varKey, value);
|
||||
stage.getVariables().put(varKey, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
stage.setLastUpdatedDate(System.currentTimeMillis() / 1000L);
|
||||
stageStore.put(stageKey(region, apiId, stageName), stage);
|
||||
return stage;
|
||||
}
|
||||
|
||||
public void deleteStage(String region, String apiId, String stageName) {
|
||||
getStage(region, apiId, stageName);
|
||||
stageStore.delete(stageKey(region, apiId, stageName));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Authorizers ────────────────────────────
|
||||
|
||||
public Authorizer createAuthorizer(String region, String apiId, Map<String, Object> request) {
|
||||
getRestApi(region, apiId);
|
||||
Authorizer authorizer = new Authorizer();
|
||||
authorizer.setId(shortId(6));
|
||||
authorizer.setName((String) request.get("name"));
|
||||
authorizer.setType((String) request.get("type"));
|
||||
authorizer.setAuthorizerUri((String) request.get("authorizerUri"));
|
||||
authorizer.setIdentitySource((String) request.get("identitySource"));
|
||||
authorizer.setAuthorizerResultTtlInSeconds(String.valueOf(request.getOrDefault("authorizerResultTtlInSeconds", "300")));
|
||||
|
||||
authorizerStore.put(authorizerKey(region, apiId, authorizer.getId()), authorizer);
|
||||
LOG.infov("Created authorizer {0} for API {1}", authorizer.getId(), apiId);
|
||||
return authorizer;
|
||||
}
|
||||
|
||||
public Authorizer getAuthorizer(String region, String apiId, String authorizerId) {
|
||||
return authorizerStore.get(authorizerKey(region, apiId, authorizerId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Authorizer not found", 404));
|
||||
}
|
||||
|
||||
public List<Authorizer> getAuthorizers(String region, String apiId) {
|
||||
getRestApi(region, apiId);
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
return authorizerStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteAuthorizer(String region, String apiId, String authorizerId) {
|
||||
getAuthorizer(region, apiId, authorizerId);
|
||||
authorizerStore.delete(authorizerKey(region, apiId, authorizerId));
|
||||
}
|
||||
|
||||
// ──────────────────────────── API Keys ────────────────────────────
|
||||
|
||||
public ApiKey createApiKey(String region, Map<String, Object> request) {
|
||||
ApiKey apiKey = new ApiKey();
|
||||
apiKey.setId(shortId(10));
|
||||
apiKey.setName((String) request.get("name"));
|
||||
apiKey.setValue((String) request.getOrDefault("value", UUID.randomUUID().toString().replace("-", "")));
|
||||
apiKey.setEnabled(!Boolean.FALSE.equals(request.get("enabled")));
|
||||
apiKey.setCreatedDate(System.currentTimeMillis() / 1000L);
|
||||
apiKey.setLastUpdatedDate(apiKey.getCreatedDate());
|
||||
|
||||
apiKeyStore.put(apiKeyGlobalKey(region, apiKey.getId()), apiKey);
|
||||
LOG.infov("Created API Key {0}", apiKey.getId());
|
||||
return apiKey;
|
||||
}
|
||||
|
||||
public ApiKey getApiKey(String region, String apiKeyId) {
|
||||
return apiKeyStore.get(apiKeyGlobalKey(region, apiKeyId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "API Key not found", 404));
|
||||
}
|
||||
|
||||
public List<ApiKey> getApiKeys(String region) {
|
||||
String prefix = region + "::";
|
||||
return apiKeyStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteApiKey(String region, String apiKeyId) {
|
||||
getApiKey(region, apiKeyId);
|
||||
apiKeyStore.delete(apiKeyGlobalKey(region, apiKeyId));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Usage Plans ────────────────────────────
|
||||
|
||||
public UsagePlan createUsagePlan(String region, Map<String, Object> request) {
|
||||
UsagePlan plan = new UsagePlan();
|
||||
plan.setId(shortId(10));
|
||||
plan.setName((String) request.get("name"));
|
||||
plan.setDescription((String) request.get("description"));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> apiStages = (List<Map<String, Object>>) request.get("apiStages");
|
||||
if (apiStages != null) {
|
||||
for (Map<String, Object> as : apiStages) {
|
||||
plan.getApiStages().add(new UsagePlan.ApiStage((String) as.get("apiId"), (String) as.get("stage")));
|
||||
}
|
||||
}
|
||||
|
||||
usagePlanStore.put(usagePlanKey(region, plan.getId()), plan);
|
||||
LOG.infov("Created Usage Plan {0}", plan.getId());
|
||||
return plan;
|
||||
}
|
||||
|
||||
public UsagePlan getUsagePlan(String region, String usagePlanId) {
|
||||
return usagePlanStore.get(usagePlanKey(region, usagePlanId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Usage Plan not found", 404));
|
||||
}
|
||||
|
||||
public List<UsagePlan> getUsagePlans(String region) {
|
||||
String prefix = region + "::";
|
||||
return usagePlanStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteUsagePlan(String region, String usagePlanId) {
|
||||
getUsagePlan(region, usagePlanId);
|
||||
usagePlanStore.delete(usagePlanKey(region, usagePlanId));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Usage Plan Keys ────────────────────────────
|
||||
|
||||
public UsagePlanKey createUsagePlanKey(String region, String usagePlanId, Map<String, Object> request) {
|
||||
getUsagePlan(region, usagePlanId);
|
||||
String keyId = (String) request.get("keyId");
|
||||
String keyType = (String) request.get("keyType");
|
||||
|
||||
ApiKey apiKey = getApiKey(region, keyId);
|
||||
|
||||
UsagePlanKey usagePlanKey = new UsagePlanKey();
|
||||
usagePlanKey.setId(apiKey.getId());
|
||||
usagePlanKey.setName(apiKey.getName());
|
||||
usagePlanKey.setType(keyType);
|
||||
usagePlanKey.setValue(apiKey.getValue());
|
||||
|
||||
usagePlanKeyStore.put(usagePlanKeyPathKey(region, usagePlanId, keyId), usagePlanKey);
|
||||
LOG.infov("Created Usage Plan Key {0} for Usage Plan {1}", keyId, usagePlanId);
|
||||
return usagePlanKey;
|
||||
}
|
||||
|
||||
public UsagePlanKey getUsagePlanKey(String region, String usagePlanId, String keyId) {
|
||||
return usagePlanKeyStore.get(usagePlanKeyPathKey(region, usagePlanId, keyId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Usage Plan Key not found", 404));
|
||||
}
|
||||
|
||||
public List<UsagePlanKey> getUsagePlanKeys(String region, String usagePlanId) {
|
||||
String prefix = region + "::" + usagePlanId + "::";
|
||||
return usagePlanKeyStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteUsagePlanKey(String region, String usagePlanId, String keyId) {
|
||||
getUsagePlanKey(region, usagePlanId, keyId);
|
||||
usagePlanKeyStore.delete(usagePlanKeyPathKey(region, usagePlanId, keyId));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Request Validators ────────────────────────────
|
||||
|
||||
public RequestValidator createRequestValidator(String region, String apiId, Map<String, Object> request) {
|
||||
getRestApi(region, apiId);
|
||||
RequestValidator validator = new RequestValidator();
|
||||
validator.setId(shortId(6));
|
||||
validator.setName((String) request.get("name"));
|
||||
validator.setValidateRequestBody(Boolean.TRUE.equals(request.get("validateRequestBody")));
|
||||
validator.setValidateRequestParameters(Boolean.TRUE.equals(request.get("validateRequestParameters")));
|
||||
|
||||
requestValidatorStore.put(requestValidatorKey(region, apiId, validator.getId()), validator);
|
||||
LOG.infov("Created request validator {0} for API {1}", validator.getId(), apiId);
|
||||
return validator;
|
||||
}
|
||||
|
||||
public RequestValidator getRequestValidator(String region, String apiId, String validatorId) {
|
||||
return requestValidatorStore.get(requestValidatorKey(region, apiId, validatorId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Request validator not found", 404));
|
||||
}
|
||||
|
||||
public List<RequestValidator> getRequestValidators(String region, String apiId) {
|
||||
getRestApi(region, apiId);
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
return requestValidatorStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteRequestValidator(String region, String apiId, String validatorId) {
|
||||
getRequestValidator(region, apiId, validatorId);
|
||||
requestValidatorStore.delete(requestValidatorKey(region, apiId, validatorId));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Custom Domains ────────────────────────────
|
||||
|
||||
public CustomDomain createDomainName(String region, Map<String, Object> request) {
|
||||
String domainName = (String) request.get("domainName");
|
||||
if (domainName == null) throw new AwsException("BadRequestException", "domainName is required", 400);
|
||||
|
||||
CustomDomain domain = new CustomDomain();
|
||||
domain.setDomainName(domainName);
|
||||
domain.setCertificateName((String) request.get("certificateName"));
|
||||
domain.setCertificateArn((String) request.get("certificateArn"));
|
||||
domain.setRegionalDomainName(domainName + ".regional.local");
|
||||
domain.setRegionalHostedZoneId("Z2FDTNDATAQYL2");
|
||||
|
||||
domainStore.put(domainKey(region, domainName), domain);
|
||||
LOG.infov("Created custom domain {0} in {1}", domainName, region);
|
||||
return domain;
|
||||
}
|
||||
|
||||
public CustomDomain getDomainName(String region, String domainName) {
|
||||
return domainStore.get(domainKey(region, domainName))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Domain name not found", 404));
|
||||
}
|
||||
|
||||
public List<CustomDomain> getDomainNames(String region) {
|
||||
String prefix = region + "::";
|
||||
return domainStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteDomainName(String region, String domainName) {
|
||||
getDomainName(region, domainName);
|
||||
domainStore.delete(domainKey(region, domainName));
|
||||
// Delete associated mappings
|
||||
String prefix = region + "::" + domainName + "::";
|
||||
basePathMappingStore.keys().stream().filter(k -> k.startsWith(prefix)).forEach(basePathMappingStore::delete);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Base Path Mappings ────────────────────────────
|
||||
|
||||
public BasePathMapping createBasePathMapping(String region, String domainName, Map<String, Object> request) {
|
||||
getDomainName(region, domainName);
|
||||
String basePath = (String) request.getOrDefault("basePath", "(none)");
|
||||
String apiId = (String) request.get("restApiId");
|
||||
String stage = (String) request.get("stage");
|
||||
|
||||
BasePathMapping mapping = new BasePathMapping(basePath, apiId, stage);
|
||||
basePathMappingStore.put(mappingKey(region, domainName, basePath), mapping);
|
||||
LOG.infov("Created mapping for {0} path={1} -> API {2}", domainName, basePath, apiId);
|
||||
return mapping;
|
||||
}
|
||||
|
||||
public BasePathMapping getBasePathMapping(String region, String domainName, String basePath) {
|
||||
String path = (basePath == null || basePath.isEmpty() || "/" .equals(basePath)) ? "(none)" : basePath;
|
||||
return basePathMappingStore.get(mappingKey(region, domainName, path))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Base path mapping not found", 404));
|
||||
}
|
||||
|
||||
public List<BasePathMapping> getBasePathMappings(String region, String domainName) {
|
||||
getDomainName(region, domainName);
|
||||
String prefix = region + "::" + domainName + "::";
|
||||
return basePathMappingStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteBasePathMapping(String region, String domainName, String basePath) {
|
||||
getBasePathMapping(region, domainName, basePath);
|
||||
String path = (basePath == null || basePath.isEmpty() || "/" .equals(basePath)) ? "(none)" : basePath;
|
||||
basePathMappingStore.delete(mappingKey(region, domainName, path));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Update Methods ────────────────────────────
|
||||
|
||||
public RestApi updateRestApi(String region, String apiId, List<Map<String, String>> patchOperations) {
|
||||
RestApi api = getRestApi(region, apiId);
|
||||
if (patchOperations != null) {
|
||||
for (Map<String, String> op : patchOperations) {
|
||||
if (!"replace" .equals(op.get("op"))) continue;
|
||||
String path = op.getOrDefault("path", "");
|
||||
String value = op.get("value");
|
||||
if ("/name" .equals(path)) api.setName(value);
|
||||
else if ("/description" .equals(path)) api.setDescription(value);
|
||||
}
|
||||
}
|
||||
apiStore.put(apiKey(region, apiId), api);
|
||||
return api;
|
||||
}
|
||||
|
||||
public ApiGatewayResource updateResource(String region, String apiId, String resourceId, List<Map<String, String>> patchOperations) {
|
||||
ApiGatewayResource resource = getResource(region, apiId, resourceId);
|
||||
// Minimal update support
|
||||
resourceStore.put(resourceKey(region, apiId, resourceId), resource);
|
||||
return resource;
|
||||
}
|
||||
|
||||
public MethodConfig updateMethod(String region, String apiId, String resourceId, String httpMethod, List<Map<String, String>> patchOperations) {
|
||||
MethodConfig method = getMethod(region, apiId, resourceId, httpMethod);
|
||||
if (patchOperations != null) {
|
||||
for (Map<String, String> op : patchOperations) {
|
||||
if (!"replace" .equals(op.get("op"))) continue;
|
||||
String path = op.getOrDefault("path", "");
|
||||
String value = op.get("value");
|
||||
if ("/authorizationType" .equals(path)) method.setAuthorizationType(value);
|
||||
else if ("/authorizerId" .equals(path)) method.setAuthorizerId(value);
|
||||
}
|
||||
}
|
||||
resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId));
|
||||
return method;
|
||||
}
|
||||
|
||||
public Integration updateIntegration(String region, String apiId, String resourceId, String httpMethod, List<Map<String, String>> patchOperations) {
|
||||
Integration integration = getIntegration(region, apiId, resourceId, httpMethod);
|
||||
if (patchOperations != null) {
|
||||
for (Map<String, String> op : patchOperations) {
|
||||
if (!"replace" .equals(op.get("op"))) continue;
|
||||
String path = op.getOrDefault("path", "");
|
||||
String value = op.get("value");
|
||||
if ("/type" .equals(path)) integration.setType(value);
|
||||
else if ("/httpMethod" .equals(path)) integration.setHttpMethod(value);
|
||||
else if ("/uri" .equals(path)) integration.setUri(value);
|
||||
}
|
||||
}
|
||||
resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId));
|
||||
return integration;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Tags ────────────────────────────
|
||||
|
||||
public Map<String, String> getTags(String region, String apiId) {
|
||||
return getRestApi(region, apiId).getTags();
|
||||
}
|
||||
|
||||
public void tagResource(String region, String apiId, Map<String, String> tags) {
|
||||
RestApi api = getRestApi(region, apiId);
|
||||
api.getTags().putAll(tags);
|
||||
apiStore.put(apiKey(region, apiId), api);
|
||||
}
|
||||
|
||||
public void untagResource(String region, String apiId, List<String> tagKeys) {
|
||||
RestApi api = getRestApi(region, apiId);
|
||||
tagKeys.forEach(api.getTags()::remove);
|
||||
apiStore.put(apiKey(region, apiId), api);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Key helpers ────────────────────────────
|
||||
|
||||
private String apiKey(String region, String apiId) {
|
||||
return region + "::" + apiId;
|
||||
}
|
||||
|
||||
private String resourceKey(String region, String apiId, String resourceId) {
|
||||
return region + "::" + apiId + "::" + resourceId;
|
||||
}
|
||||
|
||||
private String deploymentKey(String region, String apiId, String deploymentId) {
|
||||
return region + "::" + apiId + "::" + deploymentId;
|
||||
}
|
||||
|
||||
private String stageKey(String region, String apiId, String stageName) {
|
||||
return region + "::" + apiId + "::" + stageName;
|
||||
}
|
||||
|
||||
private String authorizerKey(String region, String apiId, String authorizerId) {
|
||||
return region + "::" + apiId + "::" + authorizerId;
|
||||
}
|
||||
|
||||
private String requestValidatorKey(String region, String apiId, String validatorId) {
|
||||
return region + "::" + apiId + "::" + validatorId;
|
||||
}
|
||||
|
||||
private String apiKeyGlobalKey(String region, String apiKeyId) {
|
||||
return region + "::" + apiKeyId;
|
||||
}
|
||||
|
||||
private String usagePlanKey(String region, String usagePlanId) {
|
||||
return region + "::" + usagePlanId;
|
||||
}
|
||||
|
||||
private String usagePlanKeyPathKey(String region, String usagePlanId, String keyId) {
|
||||
return region + "::" + usagePlanId + "::" + keyId;
|
||||
}
|
||||
|
||||
private String domainKey(String region, String domainName) {
|
||||
return region + "::" + domainName;
|
||||
}
|
||||
|
||||
private String mappingKey(String region, String domainName, String basePath) {
|
||||
return region + "::" + domainName + "::" + basePath;
|
||||
}
|
||||
|
||||
private static String shortId(int length) {
|
||||
return UUID.randomUUID().toString().replace("-", "").substring(0, length);
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* AWS API Gateway tag endpoints at /tags/{resourceArn}.
|
||||
*/
|
||||
@Path("/tags")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public class ApiGatewayTagsController {
|
||||
|
||||
private final ApiGatewayService service;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public ApiGatewayTagsController(ApiGatewayService service, RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{arn: .*}")
|
||||
public Response getTags(@Context HttpHeaders headers, @PathParam("arn") String arn) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
String apiId = apiIdFromArn(arn);
|
||||
Map<String, String> tags = service.getTags(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ObjectNode tagsNode = root.putObject("tags");
|
||||
tags.forEach(tagsNode::put);
|
||||
return Response.ok(root).build();
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/{arn: .*}")
|
||||
public Response tagResource(@Context HttpHeaders headers,
|
||||
@PathParam("arn") String arn,
|
||||
String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
String apiId = apiIdFromArn(arn);
|
||||
try {
|
||||
JsonNode node = objectMapper.readTree(body);
|
||||
Map<String, String> tags = new java.util.HashMap<>();
|
||||
node.path("tags").fields().forEachRemaining(e -> tags.put(e.getKey(), e.getValue().asText()));
|
||||
service.tagResource(region, apiId, tags);
|
||||
return Response.noContent().build();
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("BadRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/{arn: .*}")
|
||||
public Response untagResource(@Context HttpHeaders headers,
|
||||
@PathParam("arn") String arn,
|
||||
@QueryParam("tagKeys") List<String> tagKeys) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
String apiId = apiIdFromArn(arn);
|
||||
service.untagResource(region, apiId, tagKeys);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts apiId from ARN: arn:aws:apigateway:region::/restapis/{apiId}
|
||||
*/
|
||||
private String apiIdFromArn(String arn) {
|
||||
String[] parts = arn.split("/restapis/");
|
||||
if (parts.length < 2) {
|
||||
throw new AwsException("BadRequestException", "Invalid resource ARN: " + arn, 400);
|
||||
}
|
||||
return parts[1].split("/")[0];
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class ApiGatewayResource {
|
||||
|
||||
private String id;
|
||||
private String apiId;
|
||||
private String parentId;
|
||||
private String pathPart;
|
||||
private String path;
|
||||
private Map<String, MethodConfig> resourceMethods = new HashMap<>();
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
|
||||
public String getApiId() { return apiId; }
|
||||
public void setApiId(String apiId) { this.apiId = apiId; }
|
||||
|
||||
public String getParentId() { return parentId; }
|
||||
public void setParentId(String parentId) { this.parentId = parentId; }
|
||||
|
||||
public String getPathPart() { return pathPart; }
|
||||
public void setPathPart(String pathPart) { this.pathPart = pathPart; }
|
||||
|
||||
public String getPath() { return path; }
|
||||
public void setPath(String path) { this.path = path; }
|
||||
|
||||
public Map<String, MethodConfig> getResourceMethods() { return resourceMethods; }
|
||||
public void setResourceMethods(Map<String, MethodConfig> resourceMethods) {
|
||||
this.resourceMethods = resourceMethods != null ? resourceMethods : new HashMap<>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class ApiKey {
|
||||
private String id;
|
||||
private String name;
|
||||
private String value;
|
||||
private boolean enabled;
|
||||
private long createdDate;
|
||||
private long lastUpdatedDate;
|
||||
|
||||
public ApiKey() {}
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getValue() { return value; }
|
||||
public void setValue(String value) { this.value = value; }
|
||||
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public void setEnabled(boolean enabled) { this.enabled = enabled; }
|
||||
|
||||
public long getCreatedDate() { return createdDate; }
|
||||
public void setCreatedDate(long createdDate) { this.createdDate = createdDate; }
|
||||
|
||||
public long getLastUpdatedDate() { return lastUpdatedDate; }
|
||||
public void setLastUpdatedDate(long lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Authorizer {
|
||||
private String id;
|
||||
private String name;
|
||||
private String type; // TOKEN, REQUEST
|
||||
private String authorizerUri;
|
||||
private String identitySource;
|
||||
private String authorizerResultTtlInSeconds;
|
||||
|
||||
public Authorizer() {}
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getType() { return type; }
|
||||
public void setType(String type) { this.type = type; }
|
||||
|
||||
public String getAuthorizerUri() { return authorizerUri; }
|
||||
public void setAuthorizerUri(String authorizerUri) { this.authorizerUri = authorizerUri; }
|
||||
|
||||
public String getIdentitySource() { return identitySource; }
|
||||
public void setIdentitySource(String identitySource) { this.identitySource = identitySource; }
|
||||
|
||||
public String getAuthorizerResultTtlInSeconds() { return authorizerResultTtlInSeconds; }
|
||||
public void setAuthorizerResultTtlInSeconds(String ttl) { this.authorizerResultTtlInSeconds = ttl; }
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class BasePathMapping {
|
||||
private String basePath;
|
||||
private String restApiId;
|
||||
private String stage;
|
||||
|
||||
public BasePathMapping() {
|
||||
this.basePath = "(none)";
|
||||
}
|
||||
|
||||
public BasePathMapping(String basePath, String restApiId, String stage) {
|
||||
this.basePath = (basePath == null || basePath.isEmpty()) ? "(none)" : basePath;
|
||||
this.restApiId = restApiId;
|
||||
this.stage = stage;
|
||||
}
|
||||
|
||||
public String getBasePath() { return basePath; }
|
||||
public void setBasePath(String basePath) { this.basePath = basePath; }
|
||||
|
||||
public String getRestApiId() { return restApiId; }
|
||||
public void setRestApiId(String restApiId) { this.restApiId = restApiId; }
|
||||
|
||||
public String getStage() { return stage; }
|
||||
public void setStage(String stage) { this.stage = stage; }
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class CustomDomain {
|
||||
private String domainName;
|
||||
private String certificateName;
|
||||
private String certificateArn;
|
||||
private String certificateUploadDate;
|
||||
private String regionalDomainName;
|
||||
private String regionalHostedZoneId;
|
||||
private String regionalCertificateName;
|
||||
private String regionalCertificateArn;
|
||||
private String distributionDomainName;
|
||||
private String distributionHostedZoneId;
|
||||
private String endpointConfigurationType; // REGIONAL or EDGE
|
||||
private String domainNameStatus; // AVAILABLE, UPDATING, PENDING
|
||||
private String securityPolicy;
|
||||
|
||||
public CustomDomain() {
|
||||
this.domainNameStatus = "AVAILABLE";
|
||||
this.endpointConfigurationType = "REGIONAL";
|
||||
this.securityPolicy = "TLS_1_2";
|
||||
}
|
||||
|
||||
public String getDomainName() { return domainName; }
|
||||
public void setDomainName(String domainName) { this.domainName = domainName; }
|
||||
|
||||
public String getCertificateName() { return certificateName; }
|
||||
public void setCertificateName(String certificateName) { this.certificateName = certificateName; }
|
||||
|
||||
public String getCertificateArn() { return certificateArn; }
|
||||
public void setCertificateArn(String certificateArn) { this.certificateArn = certificateArn; }
|
||||
|
||||
public String getCertificateUploadDate() { return certificateUploadDate; }
|
||||
public void setCertificateUploadDate(String certificateUploadDate) { this.certificateUploadDate = certificateUploadDate; }
|
||||
|
||||
public String getRegionalDomainName() { return regionalDomainName; }
|
||||
public void setRegionalDomainName(String regionalDomainName) { this.regionalDomainName = regionalDomainName; }
|
||||
|
||||
public String getRegionalHostedZoneId() { return regionalHostedZoneId; }
|
||||
public void setRegionalHostedZoneId(String regionalHostedZoneId) { this.regionalHostedZoneId = regionalHostedZoneId; }
|
||||
|
||||
public String getRegionalCertificateName() { return regionalCertificateName; }
|
||||
public void setRegionalCertificateName(String regionalCertificateName) { this.regionalCertificateName = regionalCertificateName; }
|
||||
|
||||
public String getRegionalCertificateArn() { return regionalCertificateArn; }
|
||||
public void setRegionalCertificateArn(String regionalCertificateArn) { this.regionalCertificateArn = regionalCertificateArn; }
|
||||
|
||||
public String getDistributionDomainName() { return distributionDomainName; }
|
||||
public void setDistributionDomainName(String distributionDomainName) { this.distributionDomainName = distributionDomainName; }
|
||||
|
||||
public String getDistributionHostedZoneId() { return distributionHostedZoneId; }
|
||||
public void setDistributionHostedZoneId(String distributionHostedZoneId) { this.distributionHostedZoneId = distributionHostedZoneId; }
|
||||
|
||||
public String getEndpointConfigurationType() { return endpointConfigurationType; }
|
||||
public void setEndpointConfigurationType(String endpointConfigurationType) { this.endpointConfigurationType = endpointConfigurationType; }
|
||||
|
||||
public String getDomainNameStatus() { return domainNameStatus; }
|
||||
public void setDomainNameStatus(String domainNameStatus) { this.domainNameStatus = domainNameStatus; }
|
||||
|
||||
public String getSecurityPolicy() { return securityPolicy; }
|
||||
public void setSecurityPolicy(String securityPolicy) { this.securityPolicy = securityPolicy; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record Deployment(
|
||||
String id,
|
||||
String description,
|
||||
long createdDate
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Integration {
|
||||
|
||||
private String type; // MOCK, HTTP, AWS, HTTP_PROXY, AWS_PROXY
|
||||
private String uri;
|
||||
private String httpMethod;
|
||||
private Map<String, String> requestTemplates = new HashMap<>();
|
||||
private Map<String, IntegrationResponse> integrationResponses = new HashMap<>();
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
|
||||
public void setUri(String uri) {
|
||||
this.uri = uri;
|
||||
}
|
||||
|
||||
public String getHttpMethod() {
|
||||
return httpMethod;
|
||||
}
|
||||
|
||||
public void setHttpMethod(String httpMethod) {
|
||||
this.httpMethod = httpMethod;
|
||||
}
|
||||
|
||||
public Map<String, String> getRequestTemplates() {
|
||||
return requestTemplates;
|
||||
}
|
||||
|
||||
public void setRequestTemplates(Map<String, String> requestTemplates) {
|
||||
this.requestTemplates = requestTemplates != null ? requestTemplates : new HashMap<>();
|
||||
}
|
||||
|
||||
public Map<String, IntegrationResponse> getIntegrationResponses() {
|
||||
return integrationResponses;
|
||||
}
|
||||
|
||||
public void setIntegrationResponses(Map<String, IntegrationResponse> integrationResponses) {
|
||||
this.integrationResponses = integrationResponses != null ? integrationResponses : new HashMap<>();
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record IntegrationResponse(
|
||||
String statusCode,
|
||||
String selectionPattern,
|
||||
Map<String, String> responseParameters,
|
||||
Map<String, String> responseTemplates
|
||||
) {}
|
||||
@@ -0,0 +1,39 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class MethodConfig {
|
||||
|
||||
private String httpMethod;
|
||||
private String authorizationType;
|
||||
private String authorizerId;
|
||||
private Map<String, Boolean> requestParameters = new HashMap<>();
|
||||
private Map<String, MethodResponse> methodResponses = new HashMap<>();
|
||||
private Integration methodIntegration;
|
||||
|
||||
public String getHttpMethod() { return httpMethod; }
|
||||
public void setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; }
|
||||
|
||||
public String getAuthorizationType() { return authorizationType; }
|
||||
public void setAuthorizationType(String authorizationType) { this.authorizationType = authorizationType; }
|
||||
|
||||
public String getAuthorizerId() { return authorizerId; }
|
||||
public void setAuthorizerId(String authorizerId) { this.authorizerId = authorizerId; }
|
||||
|
||||
public Map<String, Boolean> getRequestParameters() { return requestParameters; }
|
||||
public void setRequestParameters(Map<String, Boolean> requestParameters) {
|
||||
this.requestParameters = requestParameters != null ? requestParameters : new HashMap<>();
|
||||
}
|
||||
|
||||
public Map<String, MethodResponse> getMethodResponses() { return methodResponses; }
|
||||
public void setMethodResponses(Map<String, MethodResponse> methodResponses) {
|
||||
this.methodResponses = methodResponses != null ? methodResponses : new HashMap<>();
|
||||
}
|
||||
|
||||
public Integration getMethodIntegration() { return methodIntegration; }
|
||||
public void setMethodIntegration(Integration methodIntegration) { this.methodIntegration = methodIntegration; }
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record MethodResponse(
|
||||
String statusCode,
|
||||
Map<String, Boolean> responseParameters
|
||||
) {
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class RequestValidator {
|
||||
private String id;
|
||||
private String name;
|
||||
private boolean validateRequestBody;
|
||||
private boolean validateRequestParameters;
|
||||
|
||||
public RequestValidator() {}
|
||||
|
||||
public RequestValidator(String id, String name, boolean validateRequestBody, boolean validateRequestParameters) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.validateRequestBody = validateRequestBody;
|
||||
this.validateRequestParameters = validateRequestParameters;
|
||||
}
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public boolean isValidateRequestBody() { return validateRequestBody; }
|
||||
public void setValidateRequestBody(boolean validateRequestBody) { this.validateRequestBody = validateRequestBody; }
|
||||
|
||||
public boolean isValidateRequestParameters() { return validateRequestParameters; }
|
||||
public void setValidateRequestParameters(boolean validateRequestParameters) { this.validateRequestParameters = validateRequestParameters; }
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class RestApi {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
private String description;
|
||||
private long createdDate;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public long getCreatedDate() {
|
||||
return createdDate;
|
||||
}
|
||||
|
||||
public void setCreatedDate(long createdDate) {
|
||||
this.createdDate = createdDate;
|
||||
}
|
||||
|
||||
public Map<String, String> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(Map<String, String> tags) {
|
||||
this.tags = tags != null ? tags : new HashMap<>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Stage {
|
||||
|
||||
private String stageName;
|
||||
private String deploymentId;
|
||||
private String description;
|
||||
private Map<String, String> variables = new HashMap<>();
|
||||
private long createdDate;
|
||||
private long lastUpdatedDate;
|
||||
|
||||
public String getStageName() {
|
||||
return stageName;
|
||||
}
|
||||
|
||||
public void setStageName(String stageName) {
|
||||
this.stageName = stageName;
|
||||
}
|
||||
|
||||
public String getDeploymentId() {
|
||||
return deploymentId;
|
||||
}
|
||||
|
||||
public void setDeploymentId(String deploymentId) {
|
||||
this.deploymentId = deploymentId;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Map<String, String> getVariables() {
|
||||
return variables;
|
||||
}
|
||||
|
||||
public void setVariables(Map<String, String> variables) {
|
||||
this.variables = variables != null ? variables : new HashMap<>();
|
||||
}
|
||||
|
||||
public long getCreatedDate() {
|
||||
return createdDate;
|
||||
}
|
||||
|
||||
public void setCreatedDate(long createdDate) {
|
||||
this.createdDate = createdDate;
|
||||
}
|
||||
|
||||
public long getLastUpdatedDate() {
|
||||
return lastUpdatedDate;
|
||||
}
|
||||
|
||||
public void setLastUpdatedDate(long lastUpdatedDate) {
|
||||
this.lastUpdatedDate = lastUpdatedDate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class UsagePlan {
|
||||
private String id;
|
||||
private String name;
|
||||
private String description;
|
||||
private List<ApiStage> apiStages = new ArrayList<>();
|
||||
|
||||
public UsagePlan() {}
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public List<ApiStage> getApiStages() { return apiStages; }
|
||||
public void setApiStages(List<ApiStage> apiStages) { this.apiStages = apiStages; }
|
||||
|
||||
@RegisterForReflection
|
||||
public record ApiStage(String apiId, String stage) {}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package io.github.hectorvent.floci.services.apigateway.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class UsagePlanKey {
|
||||
private String id;
|
||||
private String name;
|
||||
private String type;
|
||||
private String value;
|
||||
|
||||
public UsagePlanKey() {}
|
||||
|
||||
public UsagePlanKey(String id, String name, String type, String value) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.type = type;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getType() { return type; }
|
||||
public void setType(String type) { this.type = type; }
|
||||
|
||||
public String getValue() { return value; }
|
||||
public void setValue(String value) { this.value = value; }
|
||||
}
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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.services.apigatewayv2.model.*;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ApplicationScoped
|
||||
public class ApiGatewayV2JsonHandler {
|
||||
|
||||
private final ApiGatewayV2Service service;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public ApiGatewayV2JsonHandler(ApiGatewayV2Service service, ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
try {
|
||||
return switch (action) {
|
||||
case "CreateApi" -> handleCreateApi(request, region);
|
||||
case "GetApis" -> handleGetApis(region);
|
||||
case "GetApi" -> handleGetApi(request, region);
|
||||
case "DeleteApi" -> handleDeleteApi(request, region);
|
||||
case "CreateRoute" -> handleCreateRoute(request, region);
|
||||
case "GetRoute" -> handleGetRoute(request, region);
|
||||
case "GetRoutes" -> handleGetRoutes(request, region);
|
||||
case "DeleteRoute" -> handleDeleteRoute(request, region);
|
||||
case "CreateIntegration" -> handleCreateIntegration(request, region);
|
||||
case "GetIntegration" -> handleGetIntegration(request, region);
|
||||
case "GetIntegrations" -> handleGetIntegrations(request, region);
|
||||
case "CreateAuthorizer" -> handleCreateAuthorizer(request, region);
|
||||
case "GetAuthorizer" -> handleGetAuthorizer(request, region);
|
||||
case "GetAuthorizers" -> handleGetAuthorizers(request, region);
|
||||
case "DeleteAuthorizer" -> handleDeleteAuthorizer(request, region);
|
||||
case "CreateStage" -> handleCreateStage(request, region);
|
||||
case "GetStage" -> handleGetStage(request, region);
|
||||
case "GetStages" -> handleGetStages(request, region);
|
||||
case "DeleteStage" -> handleDeleteStage(request, region);
|
||||
case "CreateDeployment" -> handleCreateDeployment(request, region);
|
||||
case "GetDeployments" -> handleGetDeployments(request, region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported."))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
};
|
||||
} catch (AwsException e) {
|
||||
return Response.status(e.getHttpStatus())
|
||||
.entity(new AwsErrorResponse(e.getErrorCode(), e.getMessage()))
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── API ────────────────────────────
|
||||
|
||||
private Response handleCreateApi(JsonNode request, String region) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Api api = service.createApi(region, map);
|
||||
return Response.status(201).entity(toApiNode(api).toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleGetApis(String region) {
|
||||
List<Api> apis = service.getApis(region);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
apis.forEach(a -> items.add(toApiNode(a)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleGetApi(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
return Response.ok(toApiNode(service.getApi(region, apiId)).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteApi(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
service.deleteApi(region, apiId);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Authorizer ────────────────────────────
|
||||
|
||||
private Response handleCreateAuthorizer(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Authorizer auth = service.createAuthorizer(region, apiId, map);
|
||||
return Response.status(201).entity(toAuthorizerNode(auth).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleGetAuthorizer(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String authorizerId = request.path("AuthorizerId").asText();
|
||||
return Response.ok(toAuthorizerNode(service.getAuthorizer(region, apiId, authorizerId)).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleGetAuthorizers(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
List<Authorizer> authorizers = service.getAuthorizers(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
authorizers.forEach(a -> items.add(toAuthorizerNode(a)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteAuthorizer(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String authorizerId = request.path("AuthorizerId").asText();
|
||||
service.deleteAuthorizer(region, apiId, authorizerId);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Route ────────────────────────────
|
||||
|
||||
private Response handleCreateRoute(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Route route = service.createRoute(region, apiId, map);
|
||||
return Response.status(201).entity(toRouteNode(route).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleGetRoute(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String routeId = request.path("RouteId").asText();
|
||||
return Response.ok(toRouteNode(service.getRoute(region, apiId, routeId)).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleGetRoutes(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
List<Route> routes = service.getRoutes(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
routes.forEach(r -> items.add(toRouteNode(r)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteRoute(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String routeId = request.path("RouteId").asText();
|
||||
service.deleteRoute(region, apiId, routeId);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Integration ────────────────────────────
|
||||
|
||||
private Response handleCreateIntegration(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Integration integration = service.createIntegration(region, apiId, map);
|
||||
return Response.status(201).entity(toIntegrationNode(integration).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleGetIntegration(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String integrationId = request.path("IntegrationId").asText();
|
||||
return Response.ok(toIntegrationNode(service.getIntegration(region, apiId, integrationId)).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleGetIntegrations(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
List<Integration> integrations = service.getIntegrations(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
integrations.forEach(i -> items.add(toIntegrationNode(i)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Stage ────────────────────────────
|
||||
|
||||
private Response handleCreateStage(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Stage stage = service.createStage(region, apiId, map);
|
||||
return Response.status(201).entity(toStageNode(stage).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleGetStage(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String stageName = request.path("StageName").asText();
|
||||
return Response.ok(toStageNode(service.getStage(region, apiId, stageName)).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleGetStages(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
List<Stage> stages = service.getStages(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
stages.forEach(s -> items.add(toStageNode(s)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteStage(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
String stageName = request.path("StageName").asText();
|
||||
service.deleteStage(region, apiId, stageName);
|
||||
return Response.noContent().build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Deployment ────────────────────────────
|
||||
|
||||
private Response handleCreateDeployment(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> map = objectMapper.convertValue(request, Map.class);
|
||||
Deployment deployment = service.createDeployment(region, apiId, map);
|
||||
return Response.status(201).entity(toDeploymentNode(deployment).toString())
|
||||
.type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleGetDeployments(JsonNode request, String region) {
|
||||
String apiId = request.path("ApiId").asText();
|
||||
List<Deployment> deployments = service.getDeployments(region, apiId);
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
ArrayNode items = root.putArray("Items");
|
||||
deployments.forEach(d -> items.add(toDeploymentNode(d)));
|
||||
return Response.ok(root.toString()).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Serializers ────────────────────────────
|
||||
|
||||
private ObjectNode toApiNode(Api api) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("ApiId", api.getApiId());
|
||||
node.put("Name", api.getName());
|
||||
node.put("ProtocolType", api.getProtocolType());
|
||||
node.put("ApiEndpoint", api.getApiEndpoint());
|
||||
node.put("CreatedDate", api.getCreatedDate() / 1000.0);
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toAuthorizerNode(Authorizer auth) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("AuthorizerId", auth.getAuthorizerId());
|
||||
node.put("Name", auth.getName());
|
||||
node.put("AuthorizerType", auth.getAuthorizerType());
|
||||
if (auth.getIdentitySource() != null) {
|
||||
ArrayNode sources = node.putArray("IdentitySource");
|
||||
auth.getIdentitySource().forEach(sources::add);
|
||||
}
|
||||
if (auth.getJwtConfiguration() != null) {
|
||||
ObjectNode jwt = node.putObject("JwtConfiguration");
|
||||
if (auth.getJwtConfiguration().issuer() != null) {
|
||||
jwt.put("Issuer", auth.getJwtConfiguration().issuer());
|
||||
}
|
||||
if (auth.getJwtConfiguration().audience() != null) {
|
||||
ArrayNode aud = jwt.putArray("Audience");
|
||||
auth.getJwtConfiguration().audience().forEach(aud::add);
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toRouteNode(Route r) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("RouteId", r.getRouteId());
|
||||
node.put("RouteKey", r.getRouteKey());
|
||||
node.put("AuthorizationType", r.getAuthorizationType());
|
||||
if (r.getAuthorizerId() != null) node.put("AuthorizerId", r.getAuthorizerId());
|
||||
if (r.getTarget() != null) node.put("Target", r.getTarget());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toIntegrationNode(Integration i) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("IntegrationId", i.getIntegrationId());
|
||||
node.put("IntegrationType", i.getIntegrationType());
|
||||
node.put("PayloadFormatVersion", i.getPayloadFormatVersion());
|
||||
if (i.getIntegrationUri() != null) node.put("IntegrationUri", i.getIntegrationUri());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toStageNode(Stage s) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("StageName", s.getStageName());
|
||||
node.put("AutoDeploy", s.isAutoDeploy());
|
||||
node.put("CreatedDate", s.getCreatedDate() / 1000.0);
|
||||
node.put("LastUpdatedDate", s.getLastUpdatedDate() / 1000.0);
|
||||
if (s.getDeploymentId() != null) node.put("DeploymentId", s.getDeploymentId());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode toDeploymentNode(Deployment d) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("DeploymentId", d.getDeploymentId());
|
||||
node.put("DeploymentStatus", d.getDeploymentStatus());
|
||||
node.put("CreatedDate", d.getCreatedDate() / 1000.0);
|
||||
if (d.getDescription() != null) node.put("Description", d.getDescription());
|
||||
return node;
|
||||
}
|
||||
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.*;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class ApiGatewayV2Service {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ApiGatewayV2Service.class);
|
||||
|
||||
private final StorageBackend<String, Api> apiStore;
|
||||
private final StorageBackend<String, Route> routeStore;
|
||||
private final StorageBackend<String, Integration> integrationStore;
|
||||
private final StorageBackend<String, Authorizer> authorizerStore;
|
||||
private final StorageBackend<String, Deployment> deploymentStore;
|
||||
private final StorageBackend<String, Stage> stageStore;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public ApiGatewayV2Service(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) {
|
||||
this.apiStore = storageFactory.create("apigatewayv2", "apigatewayv2-apis.json",
|
||||
new TypeReference<>() {});
|
||||
this.routeStore = storageFactory.create("apigatewayv2", "apigatewayv2-routes.json",
|
||||
new TypeReference<>() {});
|
||||
this.integrationStore = storageFactory.create("apigatewayv2", "apigatewayv2-integrations.json",
|
||||
new TypeReference<>() {});
|
||||
this.authorizerStore = storageFactory.create("apigatewayv2", "apigatewayv2-authorizers.json",
|
||||
new TypeReference<>() {});
|
||||
this.deploymentStore = storageFactory.create("apigatewayv2", "apigatewayv2-deployments.json",
|
||||
new TypeReference<>() {});
|
||||
this.stageStore = storageFactory.create("apigatewayv2", "apigatewayv2-stages.json",
|
||||
new TypeReference<>() {});
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
// ──────────────────────────── API CRUD ────────────────────────────
|
||||
|
||||
public Api createApi(String region, Map<String, Object> request) {
|
||||
String name = (String) request.get("name");
|
||||
String protocolType = (String) request.getOrDefault("protocolType", "HTTP");
|
||||
|
||||
Api api = new Api();
|
||||
api.setApiId(shortId(10));
|
||||
api.setName(name);
|
||||
api.setProtocolType(protocolType);
|
||||
api.setCreatedDate(System.currentTimeMillis());
|
||||
api.setApiEndpoint(String.format("https://%s.execute-api.%s.amazonaws.com", api.getApiId(), region));
|
||||
|
||||
apiStore.put(apiKey(region, api.getApiId()), api);
|
||||
LOG.infov("Created HTTP API: {0} ({1}) in {2}", api.getName(), api.getApiId(), region);
|
||||
return api;
|
||||
}
|
||||
|
||||
public Api getApi(String region, String apiId) {
|
||||
return apiStore.get(apiKey(region, apiId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Invalid API id specified", 404));
|
||||
}
|
||||
|
||||
public List<Api> getApis(String region) {
|
||||
String prefix = region + "::";
|
||||
return apiStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteApi(String region, String apiId) {
|
||||
getApi(region, apiId);
|
||||
apiStore.delete(apiKey(region, apiId));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Authorizer CRUD ────────────────────────────
|
||||
|
||||
public Authorizer createAuthorizer(String region, String apiId, Map<String, Object> request) {
|
||||
getApi(region, apiId);
|
||||
Authorizer auth = new Authorizer();
|
||||
auth.setAuthorizerId(shortId(8));
|
||||
auth.setName((String) request.get("name"));
|
||||
auth.setAuthorizerType((String) request.get("authorizerType"));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> identitySource = (List<String>) request.get("identitySource");
|
||||
auth.setIdentitySource(identitySource);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> jwtConfig = (Map<String, Object>) request.get("jwtConfiguration");
|
||||
if (jwtConfig != null) {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> audience = (List<String>) jwtConfig.get("audience");
|
||||
String issuer = (String) jwtConfig.get("issuer");
|
||||
auth.setJwtConfiguration(new Authorizer.JwtConfiguration(audience, issuer));
|
||||
}
|
||||
|
||||
authorizerStore.put(authorizerKey(region, apiId, auth.getAuthorizerId()), auth);
|
||||
LOG.infov("Created JWT authorizer: {0} ({1}) for API {2}", auth.getName(), auth.getAuthorizerId(), apiId);
|
||||
return auth;
|
||||
}
|
||||
|
||||
public Authorizer getAuthorizer(String region, String apiId, String authorizerId) {
|
||||
return authorizerStore.get(authorizerKey(region, apiId, authorizerId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Authorizer not found", 404));
|
||||
}
|
||||
|
||||
public List<Authorizer> getAuthorizers(String region, String apiId) {
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
return authorizerStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteAuthorizer(String region, String apiId, String authorizerId) {
|
||||
getAuthorizer(region, apiId, authorizerId);
|
||||
authorizerStore.delete(authorizerKey(region, apiId, authorizerId));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Route CRUD ────────────────────────────
|
||||
|
||||
public Route createRoute(String region, String apiId, Map<String, Object> request) {
|
||||
getApi(region, apiId);
|
||||
Route route = new Route();
|
||||
route.setRouteId(shortId(8));
|
||||
route.setRouteKey((String) request.get("routeKey"));
|
||||
route.setAuthorizationType((String) request.getOrDefault("authorizationType", "NONE"));
|
||||
route.setAuthorizerId((String) request.get("authorizerId"));
|
||||
route.setTarget((String) request.get("target"));
|
||||
|
||||
routeStore.put(routeKey(region, apiId, route.getRouteId()), route);
|
||||
return route;
|
||||
}
|
||||
|
||||
public Route getRoute(String region, String apiId, String routeId) {
|
||||
return routeStore.get(routeKey(region, apiId, routeId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Route not found", 404));
|
||||
}
|
||||
|
||||
public List<Route> getRoutes(String region, String apiId) {
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
return routeStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteRoute(String region, String apiId, String routeId) {
|
||||
getRoute(region, apiId, routeId);
|
||||
routeStore.delete(routeKey(region, apiId, routeId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the best matching route for the given HTTP method and path.
|
||||
* Priority: exact match > path-template match > $default.
|
||||
*/
|
||||
public Route findMatchingRoute(String region, String apiId, String httpMethod, String path) {
|
||||
List<Route> routes = getRoutes(region, apiId);
|
||||
String candidate = httpMethod.toUpperCase() + " " + path;
|
||||
|
||||
// 1. Exact match
|
||||
for (Route r : routes) {
|
||||
if (candidate.equals(r.getRouteKey())) return r;
|
||||
}
|
||||
|
||||
// 2. Path-template match (e.g. "GET /users/{id}")
|
||||
for (Route r : routes) {
|
||||
if (r.getRouteKey() == null || r.getRouteKey().equals("$default")) continue;
|
||||
if (routeKeyMatchesPath(r.getRouteKey(), httpMethod, path)) return r;
|
||||
}
|
||||
|
||||
// 3. $default catch-all
|
||||
for (Route r : routes) {
|
||||
if ("$default".equals(r.getRouteKey())) return r;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean routeKeyMatchesPath(String routeKey, String httpMethod, String path) {
|
||||
int space = routeKey.indexOf(' ');
|
||||
if (space < 0) return false;
|
||||
String method = routeKey.substring(0, space);
|
||||
String pattern = routeKey.substring(space + 1);
|
||||
if (!method.equalsIgnoreCase(httpMethod)) return false;
|
||||
|
||||
// Convert path template to regex: {param} → [^/]+, {proxy+} → .+
|
||||
String regex = "^" + Pattern.quote(pattern)
|
||||
.replace("\\{proxy+\\}", "\\E.+\\Q")
|
||||
.replace("\\{", "\\E[^/]+\\Q")
|
||||
.replaceAll("\\\\Q\\\\E", "") + "$";
|
||||
return path.matches(regex);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Integration CRUD ────────────────────────────
|
||||
|
||||
public Integration createIntegration(String region, String apiId, Map<String, Object> request) {
|
||||
getApi(region, apiId);
|
||||
Integration integration = new Integration();
|
||||
integration.setIntegrationId(shortId(8));
|
||||
integration.setIntegrationType((String) request.get("integrationType"));
|
||||
integration.setIntegrationUri((String) request.get("integrationUri"));
|
||||
integration.setPayloadFormatVersion((String) request.getOrDefault("payloadFormatVersion", "2.0"));
|
||||
|
||||
integrationStore.put(integrationKey(region, apiId, integration.getIntegrationId()), integration);
|
||||
return integration;
|
||||
}
|
||||
|
||||
public Integration getIntegration(String region, String apiId, String integrationId) {
|
||||
return integrationStore.get(integrationKey(region, apiId, integrationId))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Integration not found", 404));
|
||||
}
|
||||
|
||||
public List<Integration> getIntegrations(String region, String apiId) {
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
return integrationStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Stage CRUD ────────────────────────────
|
||||
|
||||
public Stage createStage(String region, String apiId, Map<String, Object> request) {
|
||||
getApi(region, apiId);
|
||||
Stage stage = new Stage();
|
||||
stage.setStageName((String) request.getOrDefault("stageName", "$default"));
|
||||
stage.setAutoDeploy(Boolean.parseBoolean(String.valueOf(request.getOrDefault("autoDeploy", "false"))));
|
||||
stage.setCreatedDate(System.currentTimeMillis());
|
||||
stage.setLastUpdatedDate(System.currentTimeMillis());
|
||||
|
||||
stageStore.put(stageKey(region, apiId, stage.getStageName()), stage);
|
||||
LOG.infov("Created stage: {0} for API {1}", stage.getStageName(), apiId);
|
||||
return stage;
|
||||
}
|
||||
|
||||
public Stage getStage(String region, String apiId, String stageName) {
|
||||
return stageStore.get(stageKey(region, apiId, stageName))
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Stage not found", 404));
|
||||
}
|
||||
|
||||
public List<Stage> getStages(String region, String apiId) {
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
return stageStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
public void deleteStage(String region, String apiId, String stageName) {
|
||||
getStage(region, apiId, stageName);
|
||||
stageStore.delete(stageKey(region, apiId, stageName));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Deployment CRUD ────────────────────────────
|
||||
|
||||
public Deployment createDeployment(String region, String apiId, Map<String, Object> request) {
|
||||
getApi(region, apiId);
|
||||
Deployment deployment = new Deployment();
|
||||
deployment.setDeploymentId(shortId(8));
|
||||
deployment.setDeploymentStatus("DEPLOYED");
|
||||
deployment.setDescription((String) request.get("description"));
|
||||
deployment.setCreatedDate(System.currentTimeMillis());
|
||||
|
||||
deploymentStore.put(deploymentKey(region, apiId, deployment.getDeploymentId()), deployment);
|
||||
return deployment;
|
||||
}
|
||||
|
||||
public List<Deployment> getDeployments(String region, String apiId) {
|
||||
String prefix = region + "::" + apiId + "::";
|
||||
return deploymentStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Key helpers ────────────────────────────
|
||||
|
||||
private String apiKey(String region, String apiId) {
|
||||
return region + "::" + apiId;
|
||||
}
|
||||
|
||||
private String routeKey(String region, String apiId, String routeId) {
|
||||
return region + "::" + apiId + "::" + routeId;
|
||||
}
|
||||
|
||||
private String integrationKey(String region, String apiId, String integrationId) {
|
||||
return region + "::" + apiId + "::" + integrationId;
|
||||
}
|
||||
|
||||
private String authorizerKey(String region, String apiId, String authorizerId) {
|
||||
return region + "::" + apiId + "::" + authorizerId;
|
||||
}
|
||||
|
||||
private String stageKey(String region, String apiId, String stageName) {
|
||||
return region + "::" + apiId + "::" + stageName;
|
||||
}
|
||||
|
||||
private String deploymentKey(String region, String apiId, String deploymentId) {
|
||||
return region + "::" + apiId + "::" + deploymentId;
|
||||
}
|
||||
|
||||
private static String shortId(int length) {
|
||||
return UUID.randomUUID().toString().replace("-", "").substring(0, length);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Api {
|
||||
private String apiId;
|
||||
private String name;
|
||||
private String protocolType; // HTTP, WEBSOCKET
|
||||
private String apiEndpoint;
|
||||
private long createdDate;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
|
||||
public Api() {}
|
||||
|
||||
public String getApiId() { return apiId; }
|
||||
public void setApiId(String apiId) { this.apiId = apiId; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getProtocolType() { return protocolType; }
|
||||
public void setProtocolType(String protocolType) { this.protocolType = protocolType; }
|
||||
|
||||
public String getApiEndpoint() { return apiEndpoint; }
|
||||
public void setApiEndpoint(String apiEndpoint) { this.apiEndpoint = apiEndpoint; }
|
||||
|
||||
public long getCreatedDate() { return createdDate; }
|
||||
public void setCreatedDate(long createdDate) { this.createdDate = createdDate; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Authorizer {
|
||||
private String authorizerId;
|
||||
private String authorizerType; // JWT, REQUEST
|
||||
private String name;
|
||||
private JwtConfiguration jwtConfiguration;
|
||||
private List<String> identitySource;
|
||||
|
||||
public Authorizer() {}
|
||||
|
||||
public String getAuthorizerId() { return authorizerId; }
|
||||
public void setAuthorizerId(String authorizerId) { this.authorizerId = authorizerId; }
|
||||
|
||||
public String getAuthorizerType() { return authorizerType; }
|
||||
public void setAuthorizerType(String authorizerType) { this.authorizerType = authorizerType; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public JwtConfiguration getJwtConfiguration() { return jwtConfiguration; }
|
||||
public void setJwtConfiguration(JwtConfiguration jwtConfiguration) { this.jwtConfiguration = jwtConfiguration; }
|
||||
|
||||
public List<String> getIdentitySource() { return identitySource; }
|
||||
public void setIdentitySource(List<String> identitySource) { this.identitySource = identitySource; }
|
||||
|
||||
@RegisterForReflection
|
||||
public record JwtConfiguration(List<String> audience, String issuer) {}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Deployment {
|
||||
private String deploymentId;
|
||||
private String deploymentStatus;
|
||||
private String description;
|
||||
private long createdDate;
|
||||
|
||||
public Deployment() {}
|
||||
|
||||
public String getDeploymentId() { return deploymentId; }
|
||||
public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; }
|
||||
|
||||
public String getDeploymentStatus() { return deploymentStatus; }
|
||||
public void setDeploymentStatus(String deploymentStatus) { this.deploymentStatus = deploymentStatus; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public long getCreatedDate() { return createdDate; }
|
||||
public void setCreatedDate(long createdDate) { this.createdDate = createdDate; }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Integration {
|
||||
private String integrationId;
|
||||
private String integrationType; // AWS_PROXY, HTTP_PROXY
|
||||
private String integrationUri;
|
||||
private String payloadFormatVersion; // 1.0, 2.0
|
||||
private String integrationMethod;
|
||||
private int timeoutInMillis;
|
||||
|
||||
public Integration() {}
|
||||
|
||||
public String getIntegrationId() { return integrationId; }
|
||||
public void setIntegrationId(String integrationId) { this.integrationId = integrationId; }
|
||||
|
||||
public String getIntegrationType() { return integrationType; }
|
||||
public void setIntegrationType(String integrationType) { this.integrationType = integrationType; }
|
||||
|
||||
public String getIntegrationUri() { return integrationUri; }
|
||||
public void setIntegrationUri(String integrationUri) { this.integrationUri = integrationUri; }
|
||||
|
||||
public String getPayloadFormatVersion() { return payloadFormatVersion; }
|
||||
public void setPayloadFormatVersion(String payloadFormatVersion) { this.payloadFormatVersion = payloadFormatVersion; }
|
||||
|
||||
public String getIntegrationMethod() { return integrationMethod; }
|
||||
public void setIntegrationMethod(String integrationMethod) { this.integrationMethod = integrationMethod; }
|
||||
|
||||
public int getTimeoutInMillis() { return timeoutInMillis; }
|
||||
public void setTimeoutInMillis(int timeoutInMillis) { this.timeoutInMillis = timeoutInMillis; }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Route {
|
||||
private String routeId;
|
||||
private String routeKey;
|
||||
private String authorizationType; // NONE, AWS_IAM, CUSTOM, JWT
|
||||
private String authorizerId;
|
||||
private String target; // integrations/{integrationId}
|
||||
|
||||
public Route() {}
|
||||
|
||||
public String getRouteId() { return routeId; }
|
||||
public void setRouteId(String routeId) { this.routeId = routeId; }
|
||||
|
||||
public String getRouteKey() { return routeKey; }
|
||||
public void setRouteKey(String routeKey) { this.routeKey = routeKey; }
|
||||
|
||||
public String getAuthorizationType() { return authorizationType; }
|
||||
public void setAuthorizationType(String authorizationType) { this.authorizationType = authorizationType; }
|
||||
|
||||
public String getAuthorizerId() { return authorizerId; }
|
||||
public void setAuthorizerId(String authorizerId) { this.authorizerId = authorizerId; }
|
||||
|
||||
public String getTarget() { return target; }
|
||||
public void setTarget(String target) { this.target = target; }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Stage {
|
||||
private String stageName;
|
||||
private String deploymentId;
|
||||
private boolean autoDeploy;
|
||||
private long createdDate;
|
||||
private long lastUpdatedDate;
|
||||
|
||||
public Stage() {}
|
||||
|
||||
public String getStageName() { return stageName; }
|
||||
public void setStageName(String stageName) { this.stageName = stageName; }
|
||||
|
||||
public String getDeploymentId() { return deploymentId; }
|
||||
public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; }
|
||||
|
||||
public boolean isAutoDeploy() { return autoDeploy; }
|
||||
public void setAutoDeploy(boolean autoDeploy) { this.autoDeploy = autoDeploy; }
|
||||
|
||||
public long getCreatedDate() { return createdDate; }
|
||||
public void setCreatedDate(long createdDate) { this.createdDate = createdDate; }
|
||||
|
||||
public long getLastUpdatedDate() { return lastUpdatedDate; }
|
||||
public void setLastUpdatedDate(long lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; }
|
||||
}
|
||||
+533
@@ -0,0 +1,533 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Handles CloudFormation Query-protocol API calls (form-encoded POST, XML response).
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CloudFormationQueryHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFormationQueryHandler.class);
|
||||
private static final DateTimeFormatter ISO = DateTimeFormatter.ISO_INSTANT;
|
||||
private static final String CF_NS = "http://cloudformation.amazonaws.com/doc/2010-05-15/";
|
||||
|
||||
private final CloudFormationService cfnService;
|
||||
|
||||
@Inject
|
||||
public CloudFormationQueryHandler(CloudFormationService cfnService) {
|
||||
this.cfnService = cfnService;
|
||||
}
|
||||
|
||||
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
|
||||
return switch (action) {
|
||||
case "DescribeStacks" -> describeStacks(params, region);
|
||||
case "CreateStack" -> createStack(params, region);
|
||||
case "UpdateStack" -> updateStack(params, region);
|
||||
case "DeleteStack" -> deleteStack(params, region);
|
||||
case "CreateChangeSet" -> createChangeSet(params, region);
|
||||
case "DescribeChangeSet" -> describeChangeSet(params, region);
|
||||
case "ExecuteChangeSet" -> executeChangeSet(params, region);
|
||||
case "ListChangeSets" -> listChangeSets(params, region);
|
||||
case "DescribeStackEvents" -> describeStackEvents(params, region);
|
||||
case "DescribeStackResources" -> describeStackResources(params, region);
|
||||
case "ListStackResources" -> listStackResources(params, region);
|
||||
case "GetTemplate" -> getTemplate(params, region);
|
||||
case "ValidateTemplate" -> validateTemplate(params);
|
||||
case "ListStacks" -> listStacks(params, region);
|
||||
case "SetStackPolicy" -> Response.ok(emptyResult("SetStackPolicyResponse")).build();
|
||||
case "GetStackPolicy" -> Response.ok(emptyResult("GetStackPolicyResponse")).build();
|
||||
case "DescribeStackResource" -> describeStackResource(params, region);
|
||||
case "ListStackSets", "DescribeStackSet", "CreateStackSet" ->
|
||||
Response.ok(emptyResult(action + "Response")).build();
|
||||
default -> xmlError("UnknownAction", "Action " + action + " is not supported.", 400);
|
||||
};
|
||||
}
|
||||
|
||||
// ── DescribeStacks ────────────────────────────────────────────────────────
|
||||
|
||||
private Response describeStacks(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
try {
|
||||
List<Stack> stacks = cfnService.describeStacks(stackName, region);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeStacksResponse", CF_NS)
|
||||
.start("DescribeStacksResult")
|
||||
.start("Stacks");
|
||||
for (Stack s : stacks) {
|
||||
xml.raw(stackToXml(s));
|
||||
}
|
||||
xml.end("Stacks").end("DescribeStacksResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("DescribeStacksResponse");
|
||||
return Response.ok(xml.build()).type("text/xml").build();
|
||||
} catch (AwsException e) {
|
||||
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
// ── CreateStack ───────────────────────────────────────────────────────────
|
||||
|
||||
private Response createStack(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
String templateBody = params.getFirst("TemplateBody");
|
||||
String templateUrl = params.getFirst("TemplateURL");
|
||||
Map<String, String> parameters = extractParameters(params);
|
||||
List<String> capabilities = extractList(params, "Capabilities.member.");
|
||||
Map<String, String> tags = extractTags(params);
|
||||
|
||||
cfnService.createChangeSet(stackName, "initial-create", "CREATE",
|
||||
templateBody, templateUrl, parameters, capabilities, tags, region);
|
||||
cfnService.executeChangeSet(stackName, "initial-create", region);
|
||||
|
||||
Stack stack = cfnService.describeStacks(stackName, region).get(0);
|
||||
String xml = new XmlBuilder()
|
||||
.start("CreateStackResponse", CF_NS)
|
||||
.start("CreateStackResult")
|
||||
.elem("StackId", stack.getStackId())
|
||||
.end("CreateStackResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("CreateStackResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type("text/xml").build();
|
||||
}
|
||||
|
||||
// ── UpdateStack ───────────────────────────────────────────────────────────
|
||||
|
||||
private Response updateStack(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
String templateBody = params.getFirst("TemplateBody");
|
||||
String templateUrl = params.getFirst("TemplateURL");
|
||||
Map<String, String> parameters = extractParameters(params);
|
||||
List<String> capabilities = extractList(params, "Capabilities.member.");
|
||||
|
||||
ChangeSet cs = cfnService.createChangeSet(stackName, "update-" + UUID.randomUUID().toString().substring(0, 8),
|
||||
"UPDATE", templateBody, templateUrl, parameters, capabilities, Map.of(), region);
|
||||
cfnService.executeChangeSet(stackName, cs.getChangeSetName(), region);
|
||||
|
||||
Stack stack = cfnService.describeStacks(stackName, region).get(0);
|
||||
String xml = new XmlBuilder()
|
||||
.start("UpdateStackResponse", CF_NS)
|
||||
.start("UpdateStackResult")
|
||||
.elem("StackId", stack.getStackId())
|
||||
.end("UpdateStackResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("UpdateStackResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type("text/xml").build();
|
||||
}
|
||||
|
||||
// ── DeleteStack ───────────────────────────────────────────────────────────
|
||||
|
||||
private Response deleteStack(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
cfnService.deleteStack(stackName, region);
|
||||
String xml = new XmlBuilder()
|
||||
.start("DeleteStackResponse", CF_NS)
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("DeleteStackResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type("text/xml").build();
|
||||
}
|
||||
|
||||
// ── CreateChangeSet ───────────────────────────────────────────────────────
|
||||
|
||||
private Response createChangeSet(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
String changeSetName = params.getFirst("ChangeSetName");
|
||||
String changeSetType = params.getFirst("ChangeSetType");
|
||||
String templateBody = params.getFirst("TemplateBody");
|
||||
String templateUrl = params.getFirst("TemplateURL");
|
||||
Map<String, String> parameters = extractParameters(params);
|
||||
List<String> capabilities = extractList(params, "Capabilities.member.");
|
||||
Map<String, String> tags = extractTags(params);
|
||||
|
||||
ChangeSet cs = cfnService.createChangeSet(stackName, changeSetName, changeSetType,
|
||||
templateBody, templateUrl, parameters, capabilities, tags, region);
|
||||
|
||||
String xml = new XmlBuilder()
|
||||
.start("CreateChangeSetResponse", CF_NS)
|
||||
.start("CreateChangeSetResult")
|
||||
.elem("Id", cs.getChangeSetId())
|
||||
.elem("StackId", cs.getStackId())
|
||||
.end("CreateChangeSetResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("CreateChangeSetResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type("text/xml").build();
|
||||
}
|
||||
|
||||
// ── DescribeChangeSet ─────────────────────────────────────────────────────
|
||||
|
||||
private Response describeChangeSet(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
String changeSetName = params.getFirst("ChangeSetName");
|
||||
try {
|
||||
ChangeSet cs = cfnService.describeChangeSet(stackName, changeSetName, region);
|
||||
String xml = new XmlBuilder()
|
||||
.start("DescribeChangeSetResponse", CF_NS)
|
||||
.start("DescribeChangeSetResult")
|
||||
.elem("ChangeSetId", cs.getChangeSetId())
|
||||
.elem("ChangeSetName", cs.getChangeSetName())
|
||||
.elem("StackId", cs.getStackId())
|
||||
.elem("StackName", cs.getStackName())
|
||||
.elem("Status", cs.getStatus())
|
||||
.elem("ExecutionStatus", cs.getExecutionStatus())
|
||||
.raw("<Changes/>")
|
||||
.elem("CreationTime", ISO.format(cs.getCreationTime()))
|
||||
.end("DescribeChangeSetResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("DescribeChangeSetResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type("text/xml").build();
|
||||
} catch (AwsException e) {
|
||||
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
// ── ExecuteChangeSet ──────────────────────────────────────────────────────
|
||||
|
||||
private Response executeChangeSet(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
String changeSetName = params.getFirst("ChangeSetName");
|
||||
try {
|
||||
cfnService.executeChangeSet(stackName, changeSetName, region);
|
||||
} catch (AwsException e) {
|
||||
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
|
||||
}
|
||||
String xml = new XmlBuilder()
|
||||
.start("ExecuteChangeSetResponse", CF_NS)
|
||||
.raw("<ExecuteChangeSetResult/>")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("ExecuteChangeSetResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type("text/xml").build();
|
||||
}
|
||||
|
||||
// ── ListChangeSets ────────────────────────────────────────────────────────
|
||||
|
||||
private Response listChangeSets(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListChangeSetsResponse", CF_NS)
|
||||
.start("ListChangeSetsResult")
|
||||
.start("Summaries");
|
||||
try {
|
||||
List<Stack> stacks = cfnService.describeStacks(stackName, region);
|
||||
if (!stacks.isEmpty()) {
|
||||
for (ChangeSet cs : stacks.get(0).getChangeSets().values()) {
|
||||
xml.start("member")
|
||||
.elem("ChangeSetName", cs.getChangeSetName())
|
||||
.elem("ChangeSetId", cs.getChangeSetId())
|
||||
.elem("Status", cs.getStatus())
|
||||
.elem("ExecutionStatus", cs.getExecutionStatus())
|
||||
.end("member");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Stack not found for listChangeSets: {0}", e.getMessage());
|
||||
}
|
||||
xml.end("Summaries").end("ListChangeSetsResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("ListChangeSetsResponse");
|
||||
return Response.ok(xml.build()).type("text/xml").build();
|
||||
}
|
||||
|
||||
// ── DescribeStackEvents ───────────────────────────────────────────────────
|
||||
|
||||
private Response describeStackEvents(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
try {
|
||||
List<StackEvent> events = cfnService.describeStackEvents(stackName, region);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeStackEventsResponse", CF_NS)
|
||||
.start("DescribeStackEventsResult")
|
||||
.start("StackEvents");
|
||||
for (StackEvent e : events) {
|
||||
xml.start("member")
|
||||
.elem("EventId", e.getEventId())
|
||||
.elem("StackId", e.getStackId())
|
||||
.elem("StackName", e.getStackName())
|
||||
.elem("LogicalResourceId", e.getLogicalResourceId())
|
||||
.elem("PhysicalResourceId", e.getPhysicalResourceId())
|
||||
.elem("ResourceType", e.getResourceType())
|
||||
.elem("ResourceStatus", e.getResourceStatus())
|
||||
.elem("ResourceStatusReason", e.getResourceStatusReason())
|
||||
.elem("Timestamp", ISO.format(e.getTimestamp()))
|
||||
.end("member");
|
||||
}
|
||||
xml.end("StackEvents").end("DescribeStackEventsResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("DescribeStackEventsResponse");
|
||||
return Response.ok(xml.build()).type("text/xml").build();
|
||||
} catch (AwsException e) {
|
||||
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
// ── DescribeStackResources ────────────────────────────────────────────────
|
||||
|
||||
private Response describeStackResources(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
try {
|
||||
List<StackResource> resources = cfnService.describeStackResources(stackName, region);
|
||||
return stackResourcesXml(resources, stackName, region);
|
||||
} catch (AwsException e) {
|
||||
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response listStackResources(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
try {
|
||||
List<StackResource> resources = cfnService.describeStackResources(stackName, region);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListStackResourcesResponse", CF_NS)
|
||||
.start("ListStackResourcesResult")
|
||||
.start("StackResourceSummaries");
|
||||
for (StackResource r : resources) {
|
||||
xml.start("member")
|
||||
.elem("LogicalResourceId", r.getLogicalId())
|
||||
.elem("PhysicalResourceId", r.getPhysicalId())
|
||||
.elem("ResourceType", r.getResourceType())
|
||||
.elem("ResourceStatus", r.getStatus())
|
||||
.elem("LastUpdatedTimestamp", ISO.format(r.getTimestamp()))
|
||||
.end("member");
|
||||
}
|
||||
xml.end("StackResourceSummaries").end("ListStackResourcesResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("ListStackResourcesResponse");
|
||||
return Response.ok(xml.build()).type("text/xml").build();
|
||||
} catch (AwsException e) {
|
||||
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response describeStackResource(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
String logicalId = params.getFirst("LogicalResourceId");
|
||||
try {
|
||||
List<StackResource> resources = cfnService.describeStackResources(stackName, region);
|
||||
StackResource res = resources.stream()
|
||||
.filter(r -> logicalId.equals(r.getLogicalId()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Resource " + logicalId + " does not exist in stack " + stackName, 400));
|
||||
String xml = new XmlBuilder()
|
||||
.start("DescribeStackResourceResponse", CF_NS)
|
||||
.start("DescribeStackResourceResult")
|
||||
.start("StackResourceDetail")
|
||||
.elem("LogicalResourceId", res.getLogicalId())
|
||||
.elem("PhysicalResourceId", res.getPhysicalId())
|
||||
.elem("ResourceType", res.getResourceType())
|
||||
.elem("ResourceStatus", res.getStatus())
|
||||
.elem("LastUpdatedTimestamp", ISO.format(res.getTimestamp()))
|
||||
.end("StackResourceDetail")
|
||||
.end("DescribeStackResourceResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("DescribeStackResourceResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type("text/xml").build();
|
||||
} catch (AwsException e) {
|
||||
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
// ── GetTemplate ───────────────────────────────────────────────────────────
|
||||
|
||||
private Response getTemplate(MultivaluedMap<String, String> params, String region) {
|
||||
String stackName = params.getFirst("StackName");
|
||||
try {
|
||||
String template = cfnService.getTemplate(stackName, region);
|
||||
String xml = new XmlBuilder()
|
||||
.start("GetTemplateResponse", CF_NS)
|
||||
.start("GetTemplateResult")
|
||||
.elem("TemplateBody", template)
|
||||
.end("GetTemplateResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("GetTemplateResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type("text/xml").build();
|
||||
} catch (AwsException e) {
|
||||
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
// ── ValidateTemplate ──────────────────────────────────────────────────────
|
||||
|
||||
private Response validateTemplate(MultivaluedMap<String, String> params) {
|
||||
String xml = new XmlBuilder()
|
||||
.start("ValidateTemplateResponse", CF_NS)
|
||||
.start("ValidateTemplateResult")
|
||||
.raw("<Parameters/><Capabilities/><CapabilitiesReason/>")
|
||||
.end("ValidateTemplateResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("ValidateTemplateResponse")
|
||||
.build();
|
||||
return Response.ok(xml).type("text/xml").build();
|
||||
}
|
||||
|
||||
// ── ListStacks ────────────────────────────────────────────────────────────
|
||||
|
||||
private Response listStacks(MultivaluedMap<String, String> params, String region) {
|
||||
List<Stack> stacks = cfnService.listStacks(region);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListStacksResponse", CF_NS)
|
||||
.start("ListStacksResult")
|
||||
.start("StackSummaries");
|
||||
for (Stack s : stacks) {
|
||||
xml.start("member")
|
||||
.elem("StackId", s.getStackId())
|
||||
.elem("StackName", s.getStackName())
|
||||
.elem("StackStatus", s.getStatus())
|
||||
.elem("CreationTime", ISO.format(s.getCreationTime()))
|
||||
.end("member");
|
||||
}
|
||||
xml.end("StackSummaries").end("ListStacksResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("ListStacksResponse");
|
||||
return Response.ok(xml.build()).type("text/xml").build();
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private String stackToXml(Stack s) {
|
||||
XmlBuilder xml = new XmlBuilder().start("member")
|
||||
.elem("StackId", s.getStackId())
|
||||
.elem("StackName", s.getStackName())
|
||||
.elem("StackStatus", s.getStatus())
|
||||
.elem("CreationTime", ISO.format(s.getCreationTime()));
|
||||
if (s.getLastUpdatedTime() != null) {
|
||||
xml.elem("LastUpdatedTime", ISO.format(s.getLastUpdatedTime()));
|
||||
}
|
||||
if (s.getStatusReason() != null) {
|
||||
xml.elem("StackStatusReason", s.getStatusReason());
|
||||
}
|
||||
xml.start("Capabilities");
|
||||
for (String cap : s.getCapabilities()) {
|
||||
xml.elem("member", cap);
|
||||
}
|
||||
xml.end("Capabilities");
|
||||
xml.start("Outputs");
|
||||
s.getOutputs().forEach((k, v) ->
|
||||
xml.start("member")
|
||||
.elem("OutputKey", k)
|
||||
.elem("OutputValue", v)
|
||||
.end("member"));
|
||||
xml.end("Outputs");
|
||||
xml.start("Tags");
|
||||
s.getTags().forEach((k, v) ->
|
||||
xml.start("member")
|
||||
.elem("Key", k)
|
||||
.elem("Value", v)
|
||||
.end("member"));
|
||||
xml.end("Tags");
|
||||
xml.end("member");
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private Response stackResourcesXml(List<StackResource> resources, String stackName, String region) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("DescribeStackResourcesResponse", CF_NS)
|
||||
.start("DescribeStackResourcesResult")
|
||||
.start("StackResources");
|
||||
for (StackResource r : resources) {
|
||||
xml.start("member")
|
||||
.elem("StackName", stackName)
|
||||
.elem("LogicalResourceId", r.getLogicalId())
|
||||
.elem("PhysicalResourceId", r.getPhysicalId())
|
||||
.elem("ResourceType", r.getResourceType())
|
||||
.elem("ResourceStatus", r.getStatus())
|
||||
.elem("Timestamp", ISO.format(r.getTimestamp()))
|
||||
.end("member");
|
||||
}
|
||||
xml.end("StackResources").end("DescribeStackResourcesResult")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("DescribeStackResourcesResponse");
|
||||
return Response.ok(xml.build()).type("text/xml").build();
|
||||
}
|
||||
|
||||
private Map<String, String> extractParameters(MultivaluedMap<String, String> params) {
|
||||
Map<String, String> result = new HashMap<>();
|
||||
int i = 1;
|
||||
while (true) {
|
||||
String key = params.getFirst("Parameters.member." + i + ".ParameterKey");
|
||||
String value = params.getFirst("Parameters.member." + i + ".ParameterValue");
|
||||
if (key == null) {
|
||||
break;
|
||||
}
|
||||
result.put(key, value != null ? value : "");
|
||||
i++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<String, String> extractTags(MultivaluedMap<String, String> params) {
|
||||
Map<String, String> result = new HashMap<>();
|
||||
int i = 1;
|
||||
while (true) {
|
||||
String key = params.getFirst("Tags.member." + i + ".Key");
|
||||
String value = params.getFirst("Tags.member." + i + ".Value");
|
||||
if (key == null) {
|
||||
break;
|
||||
}
|
||||
result.put(key, value != null ? value : "");
|
||||
i++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<String> extractList(MultivaluedMap<String, String> params, String prefix) {
|
||||
List<String> result = new ArrayList<>();
|
||||
int i = 1;
|
||||
while (true) {
|
||||
String val = params.getFirst(prefix + i);
|
||||
if (val == null) {
|
||||
break;
|
||||
}
|
||||
result.add(val);
|
||||
i++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String emptyResult(String responseName) {
|
||||
return new XmlBuilder()
|
||||
.start(responseName, CF_NS)
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end(responseName)
|
||||
.build();
|
||||
}
|
||||
|
||||
private Response xmlError(String code, String message, int status) {
|
||||
String xml = new XmlBuilder()
|
||||
.start("ErrorResponse", CF_NS)
|
||||
.start("Error")
|
||||
.elem("Type", "Sender")
|
||||
.elem("Code", code)
|
||||
.elem("Message", message)
|
||||
.end("Error")
|
||||
.raw(AwsQueryResponse.responseMetadata())
|
||||
.end("ErrorResponse")
|
||||
.build();
|
||||
return Response.status(status).entity(xml).type("text/xml").build();
|
||||
}
|
||||
}
|
||||
+486
@@ -0,0 +1,486 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.kms.KmsService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.ssm.SsmService;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Provisions individual CloudFormation resource types using Floci's existing service implementations.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CloudFormationResourceProvisioner {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFormationResourceProvisioner.class);
|
||||
|
||||
private final S3Service s3Service;
|
||||
private final SqsService sqsService;
|
||||
private final SnsService snsService;
|
||||
private final DynamoDbService dynamoDbService;
|
||||
private final LambdaService lambdaService;
|
||||
private final IamService iamService;
|
||||
private final SsmService ssmService;
|
||||
private final KmsService kmsService;
|
||||
private final SecretsManagerService secretsManagerService;
|
||||
|
||||
@Inject
|
||||
public CloudFormationResourceProvisioner(S3Service s3Service, SqsService sqsService,
|
||||
SnsService snsService, DynamoDbService dynamoDbService,
|
||||
LambdaService lambdaService, IamService iamService,
|
||||
SsmService ssmService, KmsService kmsService,
|
||||
SecretsManagerService secretsManagerService) {
|
||||
this.s3Service = s3Service;
|
||||
this.sqsService = sqsService;
|
||||
this.snsService = snsService;
|
||||
this.dynamoDbService = dynamoDbService;
|
||||
this.lambdaService = lambdaService;
|
||||
this.iamService = iamService;
|
||||
this.ssmService = ssmService;
|
||||
this.kmsService = kmsService;
|
||||
this.secretsManagerService = secretsManagerService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provisions a single resource. Returns the populated StackResource (physicalId + attributes set).
|
||||
* Returns null and logs a warning for unsupported types.
|
||||
*/
|
||||
public StackResource provision(String logicalId, String resourceType, JsonNode properties,
|
||||
CloudFormationTemplateEngine engine, String region, String accountId) {
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId(logicalId);
|
||||
resource.setResourceType(resourceType);
|
||||
|
||||
try {
|
||||
switch (resourceType) {
|
||||
case "AWS::S3::Bucket" -> provisionS3Bucket(resource, properties, engine, region, accountId);
|
||||
case "AWS::SQS::Queue" -> provisionSqsQueue(resource, properties, engine, region, accountId);
|
||||
case "AWS::SNS::Topic" -> provisionSnsTopic(resource, properties, engine, region, accountId);
|
||||
case "AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable" ->
|
||||
provisionDynamoTable(resource, properties, engine, region, accountId);
|
||||
case "AWS::Lambda::Function" -> provisionLambda(resource, properties, engine, region, accountId);
|
||||
case "AWS::IAM::Role" -> provisionIamRole(resource, properties, engine, accountId);
|
||||
case "AWS::IAM::User" -> provisionIamUser(resource, properties, engine);
|
||||
case "AWS::IAM::AccessKey" -> provisionIamAccessKey(resource, properties, engine);
|
||||
case "AWS::IAM::Policy", "AWS::IAM::ManagedPolicy" ->
|
||||
provisionIamPolicy(resource, properties, engine, accountId);
|
||||
case "AWS::IAM::InstanceProfile" -> provisionInstanceProfile(resource, properties, engine, accountId);
|
||||
case "AWS::SSM::Parameter" -> provisionSsmParameter(resource, properties, engine, region);
|
||||
case "AWS::KMS::Key" -> provisionKmsKey(resource, properties, engine, region, accountId);
|
||||
case "AWS::KMS::Alias" -> provisionKmsAlias(resource, properties, engine, region);
|
||||
case "AWS::SecretsManager::Secret" -> provisionSecret(resource, properties, engine, region, accountId);
|
||||
case "AWS::CloudFormation::Stack" -> provisionNestedStack(resource, properties, engine, region);
|
||||
case "AWS::CDK::Metadata" -> provisionCdkMetadata(resource);
|
||||
case "AWS::S3::BucketPolicy" -> provisionS3BucketPolicy(resource, properties, engine);
|
||||
case "AWS::SQS::QueuePolicy" -> provisionSqsQueuePolicy(resource, properties, engine);
|
||||
case "AWS::ECR::Repository" -> provisionEcrRepository(resource, properties, engine);
|
||||
case "AWS::Route53::HostedZone" -> provisionRoute53HostedZone(resource, properties, engine);
|
||||
case "AWS::Route53::RecordSet" -> provisionRoute53RecordSet(resource, properties, engine);
|
||||
default -> {
|
||||
LOG.debugv("Stubbing unsupported resource type: {0} ({1})", resourceType, logicalId);
|
||||
resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
resource.getAttributes().put("Arn", "arn:aws:stub:::" + logicalId);
|
||||
}
|
||||
}
|
||||
resource.setStatus("CREATE_COMPLETE");
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to provision {0} ({1}): {2}", resourceType, logicalId, e.getMessage());
|
||||
resource.setStatus("CREATE_FAILED");
|
||||
resource.setStatusReason(e.getMessage());
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
try {
|
||||
switch (resourceType) {
|
||||
case "AWS::S3::Bucket" -> s3Service.deleteBucket(physicalId);
|
||||
case "AWS::SQS::Queue" -> sqsService.deleteQueue(physicalId, region);
|
||||
case "AWS::SNS::Topic" -> snsService.deleteTopic(physicalId, region);
|
||||
case "AWS::DynamoDB::Table" -> dynamoDbService.deleteTable(physicalId, region);
|
||||
case "AWS::Lambda::Function" -> lambdaService.deleteFunction(region, physicalId);
|
||||
case "AWS::IAM::Role" -> deleteRoleSafe(physicalId);
|
||||
case "AWS::IAM::Policy", "AWS::IAM::ManagedPolicy" -> deletePolicySafe(physicalId);
|
||||
case "AWS::IAM::InstanceProfile" -> iamService.deleteInstanceProfile(physicalId);
|
||||
case "AWS::SSM::Parameter" -> ssmService.deleteParameter(physicalId, region);
|
||||
case "AWS::KMS::Key" -> {
|
||||
} // KMS keys can't be immediately deleted; skip
|
||||
case "AWS::KMS::Alias" -> kmsService.deleteAlias(physicalId, region);
|
||||
case "AWS::SecretsManager::Secret" ->
|
||||
secretsManagerService.deleteSecret(physicalId, null, true, region);
|
||||
default -> LOG.debugv("Skipping delete of unsupported resource type: {0}", resourceType);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Error deleting {0} ({1}): {2}", resourceType, physicalId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// ── S3 ────────────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionS3Bucket(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region, String accountId) {
|
||||
String bucketName = resolveOptional(props, "BucketName", engine);
|
||||
if (bucketName == null || bucketName.isBlank()) {
|
||||
bucketName = "cfn-" + UUID.randomUUID().toString().substring(0, 12).toLowerCase();
|
||||
}
|
||||
s3Service.createBucket(bucketName);
|
||||
r.setPhysicalId(bucketName);
|
||||
r.getAttributes().put("Arn", "arn:aws:s3:::" + bucketName);
|
||||
r.getAttributes().put("DomainName", bucketName + ".s3.amazonaws.com");
|
||||
r.getAttributes().put("RegionalDomainName", bucketName + ".s3." + region + ".amazonaws.com");
|
||||
r.getAttributes().put("WebsiteURL", "http://" + bucketName + ".s3-website." + region + ".amazonaws.com");
|
||||
r.getAttributes().put("BucketName", bucketName);
|
||||
}
|
||||
|
||||
// ── SQS ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionSqsQueue(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region, String accountId) {
|
||||
String queueName = resolveOptional(props, "QueueName", engine);
|
||||
if (queueName == null || queueName.isBlank()) {
|
||||
queueName = "cfn-" + UUID.randomUUID().toString().substring(0, 12);
|
||||
}
|
||||
Map<String, String> attrs = new HashMap<>();
|
||||
if (props != null && props.has("VisibilityTimeout")) {
|
||||
attrs.put("VisibilityTimeout", engine.resolve(props.get("VisibilityTimeout")));
|
||||
}
|
||||
var queue = sqsService.createQueue(queueName, attrs, region);
|
||||
String queueArn = queue.getAttributes().getOrDefault("QueueArn", "");
|
||||
r.setPhysicalId(queue.getQueueUrl());
|
||||
r.getAttributes().put("Arn", queueArn);
|
||||
r.getAttributes().put("QueueName", queueName);
|
||||
r.getAttributes().put("QueueUrl", queue.getQueueUrl());
|
||||
}
|
||||
|
||||
// ── SNS ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionSnsTopic(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region, String accountId) {
|
||||
String topicName = resolveOptional(props, "TopicName", engine);
|
||||
if (topicName == null || topicName.isBlank()) {
|
||||
topicName = "cfn-" + UUID.randomUUID().toString().substring(0, 12);
|
||||
}
|
||||
var topic = snsService.createTopic(topicName, Map.of(), Map.of(), region);
|
||||
r.setPhysicalId(topic.getTopicArn());
|
||||
r.getAttributes().put("Arn", topic.getTopicArn());
|
||||
r.getAttributes().put("TopicName", topicName);
|
||||
}
|
||||
|
||||
// ── DynamoDB ──────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionDynamoTable(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region, String accountId) {
|
||||
String tableName = resolveOptional(props, "TableName", engine);
|
||||
if (tableName == null || tableName.isBlank()) {
|
||||
tableName = "cfn-" + UUID.randomUUID().toString().substring(0, 12);
|
||||
}
|
||||
|
||||
List<KeySchemaElement> keySchema = new ArrayList<>();
|
||||
List<AttributeDefinition> attrDefs = new ArrayList<>();
|
||||
|
||||
if (props != null && props.has("KeySchema")) {
|
||||
for (JsonNode ks : props.get("KeySchema")) {
|
||||
String attrName = engine.resolve(ks.get("AttributeName"));
|
||||
String keyType = engine.resolve(ks.get("KeyType"));
|
||||
keySchema.add(new KeySchemaElement(attrName, keyType));
|
||||
}
|
||||
}
|
||||
if (props != null && props.has("AttributeDefinitions")) {
|
||||
for (JsonNode ad : props.get("AttributeDefinitions")) {
|
||||
String attrName = engine.resolve(ad.get("AttributeName"));
|
||||
String attrType = engine.resolve(ad.get("AttributeType"));
|
||||
attrDefs.add(new AttributeDefinition(attrName, attrType));
|
||||
}
|
||||
}
|
||||
|
||||
if (keySchema.isEmpty()) {
|
||||
keySchema.add(new KeySchemaElement("id", "HASH"));
|
||||
attrDefs.add(new AttributeDefinition("id", "S"));
|
||||
}
|
||||
|
||||
var table = dynamoDbService.createTable(tableName, keySchema, attrDefs, null, null, region);
|
||||
r.setPhysicalId(tableName);
|
||||
r.getAttributes().put("Arn", table.getTableArn());
|
||||
r.getAttributes().put("StreamArn", table.getTableArn() + "/stream/2024-01-01T00:00:00.000");
|
||||
}
|
||||
|
||||
// ── Lambda ────────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionLambda(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region, String accountId) {
|
||||
String funcName = resolveOptional(props, "FunctionName", engine);
|
||||
if (funcName == null || funcName.isBlank()) {
|
||||
funcName = "cfn-func-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("FunctionName", funcName);
|
||||
req.put("Runtime", props != null && props.has("Runtime") ? engine.resolve(props.get("Runtime")) : "nodejs18.x");
|
||||
req.put("Handler", props != null && props.has("Handler") ? engine.resolve(props.get("Handler")) : "index.handler");
|
||||
req.put("Role", props != null && props.has("Role") ? engine.resolve(props.get("Role")) : "arn:aws:iam::" + accountId + ":role/default");
|
||||
if (props != null && props.has("Code")) {
|
||||
req.put("Code", Map.of("ZipFile", "exports.handler=async(e)=>({statusCode:200})"));
|
||||
} else {
|
||||
req.put("Code", Map.of("ZipFile", "exports.handler=async(e)=>({statusCode:200})"));
|
||||
}
|
||||
var func = lambdaService.createFunction(region, req);
|
||||
r.setPhysicalId(funcName);
|
||||
r.getAttributes().put("Arn", func.getFunctionArn());
|
||||
}
|
||||
|
||||
// ── IAM Role ──────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionIamRole(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String accountId) {
|
||||
String roleName = resolveOptional(props, "RoleName", engine);
|
||||
if (roleName == null || roleName.isBlank()) {
|
||||
roleName = "cfn-role-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
String assumeDoc = props != null && props.has("AssumeRolePolicyDocument")
|
||||
? props.get("AssumeRolePolicyDocument").toString()
|
||||
: "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
|
||||
String path = resolveOptional(props, "Path", engine);
|
||||
if (path == null) {
|
||||
path = "/";
|
||||
}
|
||||
String description = resolveOptional(props, "Description", engine);
|
||||
|
||||
try {
|
||||
var role = iamService.createRole(roleName, path, assumeDoc, description, 3600, Map.of());
|
||||
r.setPhysicalId(roleName);
|
||||
r.getAttributes().put("Arn", role.getArn());
|
||||
r.getAttributes().put("RoleId", role.getRoleId());
|
||||
} catch (Exception e) {
|
||||
// Role might already exist (e.g., re-deploy) — look it up
|
||||
var role = iamService.getRole(roleName);
|
||||
r.setPhysicalId(roleName);
|
||||
r.getAttributes().put("Arn", role.getArn());
|
||||
r.getAttributes().put("RoleId", role.getRoleId());
|
||||
}
|
||||
|
||||
// Attach managed policies if specified
|
||||
if (props != null && props.has("ManagedPolicyArns")) {
|
||||
for (JsonNode policyArn : props.get("ManagedPolicyArns")) {
|
||||
try {
|
||||
iamService.attachRolePolicy(roleName, engine.resolve(policyArn));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── IAM Policy ────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionIamPolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String accountId) {
|
||||
String policyName = resolveOptional(props, "PolicyName", engine);
|
||||
if (policyName == null || policyName.isBlank()) {
|
||||
policyName = "cfn-policy-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
String document = props != null && props.has("PolicyDocument")
|
||||
? props.get("PolicyDocument").toString()
|
||||
: "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
|
||||
|
||||
var policy = iamService.createPolicy(policyName, "/", null, document, Map.of());
|
||||
r.setPhysicalId(policy.getArn());
|
||||
r.getAttributes().put("Arn", policy.getArn());
|
||||
|
||||
// Attach to roles if specified
|
||||
if (props != null && props.has("Roles")) {
|
||||
for (JsonNode role : props.get("Roles")) {
|
||||
try {
|
||||
iamService.attachRolePolicy(engine.resolve(role), policy.getArn());
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void provisionIamManagedPolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String accountId) {
|
||||
provisionIamPolicy(r, props, engine, accountId);
|
||||
}
|
||||
|
||||
// ── IAM Instance Profile ──────────────────────────────────────────────────
|
||||
|
||||
private void provisionInstanceProfile(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String accountId) {
|
||||
String name = resolveOptional(props, "InstanceProfileName", engine);
|
||||
if (name == null || name.isBlank()) {
|
||||
name = "cfn-profile-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
try {
|
||||
var profile = iamService.createInstanceProfile(name, "/");
|
||||
r.setPhysicalId(name);
|
||||
r.getAttributes().put("Arn", profile.getArn());
|
||||
} catch (Exception e) {
|
||||
r.setPhysicalId(name);
|
||||
r.getAttributes().put("Arn", "arn:aws:iam::" + accountId + ":instance-profile/" + name);
|
||||
}
|
||||
}
|
||||
|
||||
// ── SSM Parameter ─────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionSsmParameter(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region) {
|
||||
String name = resolveOptional(props, "Name", engine);
|
||||
if (name == null || name.isBlank()) {
|
||||
name = "/cfn/" + UUID.randomUUID().toString().substring(0, 12);
|
||||
}
|
||||
String value = resolveOptional(props, "Value", engine);
|
||||
if (value == null) {
|
||||
value = "";
|
||||
}
|
||||
String type = resolveOptional(props, "Type", engine);
|
||||
if (type == null) {
|
||||
type = "String";
|
||||
}
|
||||
ssmService.putParameter(name, value, type, null, true, region);
|
||||
r.setPhysicalId(name);
|
||||
}
|
||||
|
||||
// ── KMS ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionKmsKey(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region, String accountId) {
|
||||
String description = resolveOptional(props, "Description", engine);
|
||||
var key = kmsService.createKey(description, region);
|
||||
r.setPhysicalId(key.getKeyId());
|
||||
r.getAttributes().put("Arn", key.getArn());
|
||||
r.getAttributes().put("KeyId", key.getKeyId());
|
||||
}
|
||||
|
||||
private void provisionKmsAlias(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region) {
|
||||
String aliasName = resolveOptional(props, "AliasName", engine);
|
||||
String targetKeyId = resolveOptional(props, "TargetKeyId", engine);
|
||||
if (aliasName != null && targetKeyId != null) {
|
||||
kmsService.createAlias(aliasName, targetKeyId, region);
|
||||
}
|
||||
r.setPhysicalId(aliasName != null ? aliasName : "alias/cfn-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
}
|
||||
|
||||
// ── Secrets Manager ───────────────────────────────────────────────────────
|
||||
|
||||
private void provisionSecret(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region, String accountId) {
|
||||
String name = resolveOptional(props, "Name", engine);
|
||||
if (name == null || name.isBlank()) {
|
||||
name = "cfn-secret-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
String value = resolveOptional(props, "SecretString", engine);
|
||||
if (value == null) {
|
||||
value = "{}";
|
||||
}
|
||||
var secret = secretsManagerService.createSecret(name, value, null, null, null, List.of(), region);
|
||||
r.setPhysicalId(secret.getArn());
|
||||
r.getAttributes().put("Arn", secret.getArn());
|
||||
r.getAttributes().put("Name", name);
|
||||
}
|
||||
|
||||
// ── Nested Stack ──────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionNestedStack(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
|
||||
String region) {
|
||||
// Nested stacks are stubbed — return a synthetic stack ID
|
||||
String nestedId = "arn:aws:cloudformation:" + region + "::stack/nested-" +
|
||||
UUID.randomUUID().toString().substring(0, 8) + "/";
|
||||
r.setPhysicalId(nestedId);
|
||||
r.getAttributes().put("Arn", nestedId);
|
||||
r.getAttributes().put("Outputs.BootstrapVersion", "21");
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private void provisionCdkMetadata(StackResource r) {
|
||||
r.setPhysicalId("cdk-metadata-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
}
|
||||
|
||||
private void provisionS3BucketPolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
|
||||
r.setPhysicalId("bucket-policy-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
}
|
||||
|
||||
private void provisionSqsQueuePolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
|
||||
r.setPhysicalId("queue-policy-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
}
|
||||
|
||||
private void provisionIamUser(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
|
||||
String userName = resolveOptional(props, "UserName", engine);
|
||||
if (userName == null || userName.isBlank()) {
|
||||
userName = "cfn-user-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
var user = iamService.createUser(userName, "/");
|
||||
r.setPhysicalId(userName);
|
||||
r.getAttributes().put("Arn", user.getArn());
|
||||
}
|
||||
|
||||
private void provisionIamAccessKey(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
|
||||
String userName = resolveOptional(props, "UserName", engine);
|
||||
if (userName != null) {
|
||||
var key = iamService.createAccessKey(userName);
|
||||
r.setPhysicalId(key.getAccessKeyId());
|
||||
r.getAttributes().put("SecretAccessKey", key.getSecretAccessKey());
|
||||
}
|
||||
}
|
||||
|
||||
private void provisionEcrRepository(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
|
||||
String repoName = resolveOptional(props, "RepositoryName", engine);
|
||||
if (repoName == null || repoName.isBlank()) {
|
||||
repoName = "cfn-repo-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
r.setPhysicalId(repoName);
|
||||
r.getAttributes().put("Arn", "arn:aws:ecr:us-east-1:000000000000:repository/" + repoName);
|
||||
}
|
||||
|
||||
private void provisionRoute53HostedZone(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
|
||||
String zoneId = "Z" + UUID.randomUUID().toString().substring(0, 12).toUpperCase();
|
||||
r.setPhysicalId(zoneId);
|
||||
}
|
||||
|
||||
private void provisionRoute53RecordSet(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) {
|
||||
String name = resolveOptional(props, "Name", engine);
|
||||
r.setPhysicalId(name != null ? name : "record-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
}
|
||||
|
||||
private String resolveOptional(JsonNode props, String name, CloudFormationTemplateEngine engine) {
|
||||
if (props == null || !props.has(name) || props.get(name).isNull()) {
|
||||
return null;
|
||||
}
|
||||
return engine.resolve(props.get(name));
|
||||
}
|
||||
|
||||
private void deleteRoleSafe(String roleName) {
|
||||
try {
|
||||
var role = iamService.getRole(roleName);
|
||||
for (String policyArn : new ArrayList<>(role.getAttachedPolicyArns())) {
|
||||
iamService.detachRolePolicy(roleName, policyArn);
|
||||
}
|
||||
for (String policyName : new ArrayList<>(role.getInlinePolicies().keySet())) {
|
||||
iamService.deleteRolePolicy(roleName, policyName);
|
||||
}
|
||||
iamService.deleteRole(roleName);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not delete role {0}: {1}", roleName, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void deletePolicySafe(String policyArn) {
|
||||
try {
|
||||
iamService.deletePolicy(policyArn);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not delete policy {0}: {1}", policyArn, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+471
@@ -0,0 +1,471 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* CloudFormation stack lifecycle management — Create, Update, Delete stacks via ChangeSets.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CloudFormationService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFormationService.class);
|
||||
|
||||
private final ConcurrentHashMap<String, Stack> stacks = new ConcurrentHashMap<>();
|
||||
private final ExecutorService executor = Executors.newCachedThreadPool();
|
||||
|
||||
private final CloudFormationResourceProvisioner provisioner;
|
||||
private final S3Service s3Service;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
public CloudFormationService(CloudFormationResourceProvisioner provisioner, S3Service s3Service,
|
||||
ObjectMapper objectMapper, EmulatorConfig config) {
|
||||
this.provisioner = provisioner;
|
||||
this.s3Service = s3Service;
|
||||
this.objectMapper = objectMapper;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
// ── DescribeStacks ────────────────────────────────────────────────────────
|
||||
|
||||
public List<Stack> describeStacks(String stackName, String region) {
|
||||
if (stackName != null && !stackName.isBlank()) {
|
||||
Stack stack = stacks.get(key(stackName, region));
|
||||
if (stack == null) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Stack with id " + stackName + " does not exist", 400);
|
||||
}
|
||||
return List.of(stack);
|
||||
}
|
||||
return stacks.values().stream()
|
||||
.filter(s -> region.equals(s.getRegion()))
|
||||
.sorted(Comparator.comparing(Stack::getCreationTime))
|
||||
.toList();
|
||||
}
|
||||
|
||||
// ── CreateChangeSet ───────────────────────────────────────────────────────
|
||||
|
||||
public ChangeSet createChangeSet(String stackName, String changeSetName, String changeSetType,
|
||||
String templateBody, String templateUrl,
|
||||
Map<String, String> parameters, List<String> capabilities,
|
||||
Map<String, String> tags, String region) {
|
||||
String resolvedTemplate = resolveTemplate(templateBody, templateUrl);
|
||||
|
||||
Stack stack = stacks.computeIfAbsent(key(stackName, region), k -> {
|
||||
Stack s = newStack(stackName, region);
|
||||
if (tags != null) s.getTags().putAll(tags);
|
||||
return s;
|
||||
});
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
cs.setChangeSetId("arn:aws:cloudformation:" + region + ":" + config.defaultAccountId() +
|
||||
":changeSet/" + changeSetName + "/" + UUID.randomUUID());
|
||||
cs.setChangeSetName(changeSetName);
|
||||
cs.setStackName(stackName);
|
||||
cs.setStackId(stack.getStackId());
|
||||
cs.setChangeSetType(changeSetType != null ? changeSetType : "CREATE");
|
||||
cs.setTemplateBody(resolvedTemplate);
|
||||
cs.setParameters(parameters);
|
||||
cs.setCapabilities(capabilities);
|
||||
cs.setStatus("CREATE_COMPLETE");
|
||||
cs.setExecutionStatus("AVAILABLE");
|
||||
|
||||
stack.getChangeSets().put(changeSetName, cs);
|
||||
return cs;
|
||||
}
|
||||
|
||||
// ── DescribeChangeSet ─────────────────────────────────────────────────────
|
||||
|
||||
public ChangeSet describeChangeSet(String stackName, String changeSetName, String region) {
|
||||
Stack stack = getStackOrThrow(stackName, region);
|
||||
ChangeSet cs = stack.getChangeSets().get(changeSetName);
|
||||
if (cs == null) {
|
||||
throw new AwsException("ChangeSetNotFoundException",
|
||||
"ChangeSet [" + changeSetName + "] does not exist", 400);
|
||||
}
|
||||
return cs;
|
||||
}
|
||||
|
||||
// ── ExecuteChangeSet ──────────────────────────────────────────────────────
|
||||
|
||||
public void executeChangeSet(String stackName, String changeSetName, String region) {
|
||||
Stack stack = getStackOrThrow(stackName, region);
|
||||
ChangeSet cs = stack.getChangeSets().get(changeSetName);
|
||||
if (cs == null) {
|
||||
throw new AwsException("ChangeSetNotFoundException",
|
||||
"ChangeSet [" + changeSetName + "] does not exist", 400);
|
||||
}
|
||||
|
||||
boolean isCreate = "CREATE".equalsIgnoreCase(cs.getChangeSetType()) ||
|
||||
"CREATE_IN_PROGRESS".equals(stack.getStatus());
|
||||
|
||||
stack.setStatus(isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS");
|
||||
stack.setLastUpdatedTime(Instant.now());
|
||||
addEvent(stack, stack.getStackName(), stack.getStackId(),
|
||||
"AWS::CloudFormation::Stack", isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS", null);
|
||||
|
||||
String templateBody = cs.getTemplateBody();
|
||||
Map<String, String> params = cs.getParameters() != null ? cs.getParameters() : Map.of();
|
||||
|
||||
executor.submit(() -> executeTemplate(stack, templateBody, params, isCreate, region));
|
||||
}
|
||||
|
||||
// ── DeleteStack ───────────────────────────────────────────────────────────
|
||||
|
||||
public void deleteStack(String stackName, String region) {
|
||||
Stack stack = stacks.get(key(stackName, region));
|
||||
if (stack == null) {
|
||||
return; // Already gone — no-op
|
||||
}
|
||||
stack.setStatus("DELETE_IN_PROGRESS");
|
||||
addEvent(stack, stack.getStackName(), stack.getStackId(),
|
||||
"AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null);
|
||||
|
||||
executor.submit(() -> deleteStackResources(stack, region));
|
||||
}
|
||||
|
||||
// ── GetTemplate ───────────────────────────────────────────────────────────
|
||||
|
||||
public String getTemplate(String stackName, String region) {
|
||||
Stack stack = getStackOrThrow(stackName, region);
|
||||
return stack.getTemplateBody() != null ? stack.getTemplateBody() : "{}";
|
||||
}
|
||||
|
||||
// ── DescribeStackEvents ───────────────────────────────────────────────────
|
||||
|
||||
public List<StackEvent> describeStackEvents(String stackName, String region) {
|
||||
Stack stack = getStackOrThrow(stackName, region);
|
||||
List<StackEvent> events = new ArrayList<>(stack.getEvents());
|
||||
Collections.reverse(events);
|
||||
return events;
|
||||
}
|
||||
|
||||
// ── DescribeStackResources ────────────────────────────────────────────────
|
||||
|
||||
public List<StackResource> describeStackResources(String stackName, String region) {
|
||||
Stack stack = getStackOrThrow(stackName, region);
|
||||
return new ArrayList<>(stack.getResources().values());
|
||||
}
|
||||
|
||||
// ── ListStacks ────────────────────────────────────────────────────────────
|
||||
|
||||
public List<Stack> listStacks(String region) {
|
||||
return stacks.values().stream()
|
||||
.filter(s -> region.equals(s.getRegion()))
|
||||
.sorted(Comparator.comparing(Stack::getCreationTime))
|
||||
.toList();
|
||||
}
|
||||
|
||||
// ── Private ───────────────────────────────────────────────────────────────
|
||||
|
||||
private void executeTemplate(Stack stack, String templateBody, Map<String, String> params,
|
||||
boolean isCreate, String region) {
|
||||
try {
|
||||
JsonNode template = parseTemplate(templateBody);
|
||||
stack.setTemplateBody(templateBody);
|
||||
|
||||
// Merge default parameter values from the template with caller-supplied params
|
||||
Map<String, String> resolvedParams = resolveDefaultParameters(template, params);
|
||||
|
||||
// Resolve conditions first
|
||||
Map<String, Boolean> conditions = resolveConditions(template, resolvedParams, stack, region);
|
||||
|
||||
// Process resources in order
|
||||
JsonNode resources = template.path("Resources");
|
||||
Map<String, String> physicalIds = new LinkedHashMap<>();
|
||||
Map<String, Map<String, String>> resourceAttrs = new LinkedHashMap<>();
|
||||
|
||||
// First pass: collect existing physicalIds
|
||||
for (var r : stack.getResources().values()) {
|
||||
if (r.getPhysicalId() != null) {
|
||||
physicalIds.put(r.getLogicalId(), r.getPhysicalId());
|
||||
resourceAttrs.put(r.getLogicalId(), r.getAttributes());
|
||||
}
|
||||
}
|
||||
|
||||
if (resources.isObject()) {
|
||||
Iterator<Map.Entry<String, JsonNode>> it = resources.fields();
|
||||
while (it.hasNext()) {
|
||||
var entry = it.next();
|
||||
String logicalId = entry.getKey();
|
||||
JsonNode resDef = entry.getValue();
|
||||
String type = resDef.path("Type").asText();
|
||||
JsonNode props = resDef.path("Properties");
|
||||
|
||||
CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine(
|
||||
config.defaultAccountId(), region, stack.getStackName(),
|
||||
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, objectMapper);
|
||||
|
||||
StackResource resource = stack.getResources().get(logicalId);
|
||||
if (resource == null) {
|
||||
resource = new StackResource();
|
||||
resource.setLogicalId(logicalId);
|
||||
resource.setResourceType(type);
|
||||
stack.getResources().put(logicalId, resource);
|
||||
}
|
||||
|
||||
addEvent(stack, logicalId, null, type, "CREATE_IN_PROGRESS", null);
|
||||
resource = provisioner.provision(logicalId, type, props.isMissingNode() ? null : props,
|
||||
engine, region, config.defaultAccountId());
|
||||
stack.getResources().put(logicalId, resource);
|
||||
|
||||
physicalIds.put(logicalId, resource.getPhysicalId());
|
||||
resourceAttrs.put(logicalId, resource.getAttributes());
|
||||
|
||||
addEvent(stack, logicalId, resource.getPhysicalId(), type,
|
||||
resource.getStatus(), resource.getStatusReason());
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve outputs
|
||||
stack.getOutputs().clear();
|
||||
CloudFormationTemplateEngine finalEngine = new CloudFormationTemplateEngine(
|
||||
config.defaultAccountId(), region, stack.getStackName(),
|
||||
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, objectMapper);
|
||||
|
||||
JsonNode outputs = template.path("Outputs");
|
||||
if (outputs.isObject()) {
|
||||
outputs.fields().forEachRemaining(e -> {
|
||||
JsonNode outputDef = e.getValue();
|
||||
String value = finalEngine.resolve(outputDef.path("Value"));
|
||||
stack.getOutputs().put(e.getKey(), value);
|
||||
});
|
||||
}
|
||||
|
||||
String completeStatus = isCreate ? "CREATE_COMPLETE" : "UPDATE_COMPLETE";
|
||||
stack.setStatus(completeStatus);
|
||||
stack.setLastUpdatedTime(Instant.now());
|
||||
addEvent(stack, stack.getStackName(), stack.getStackId(),
|
||||
"AWS::CloudFormation::Stack", completeStatus, null);
|
||||
LOG.infov("Stack {0} execution complete: {1}", stack.getStackName(), completeStatus);
|
||||
|
||||
} catch (Exception e) {
|
||||
LOG.errorv("Stack {0} execution failed: {1}", stack.getStackName(), e.getMessage());
|
||||
String failStatus = isCreate ? "CREATE_FAILED" : "UPDATE_FAILED";
|
||||
stack.setStatus(failStatus);
|
||||
stack.setStatusReason(e.getMessage());
|
||||
addEvent(stack, stack.getStackName(), stack.getStackId(),
|
||||
"AWS::CloudFormation::Stack", failStatus, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteStackResources(Stack stack, String region) {
|
||||
try {
|
||||
List<StackResource> resources = new ArrayList<>(stack.getResources().values());
|
||||
Collections.reverse(resources); // Delete in reverse order
|
||||
|
||||
for (StackResource resource : resources) {
|
||||
if (resource.getPhysicalId() != null && "CREATE_COMPLETE".equals(resource.getStatus())) {
|
||||
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
|
||||
resource.getResourceType(), "DELETE_IN_PROGRESS", null);
|
||||
provisioner.delete(resource.getResourceType(), resource.getPhysicalId(), region);
|
||||
resource.setStatus("DELETE_COMPLETE");
|
||||
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
|
||||
resource.getResourceType(), "DELETE_COMPLETE", null);
|
||||
}
|
||||
}
|
||||
|
||||
stack.setStatus("DELETE_COMPLETE");
|
||||
addEvent(stack, stack.getStackName(), stack.getStackId(),
|
||||
"AWS::CloudFormation::Stack", "DELETE_COMPLETE", null);
|
||||
stacks.remove(key(stack.getStackName(), region));
|
||||
LOG.infov("Stack {0} deleted", stack.getStackName());
|
||||
|
||||
} catch (Exception e) {
|
||||
LOG.errorv("Stack {0} delete failed: {1}", stack.getStackName(), e.getMessage());
|
||||
stack.setStatus("DELETE_FAILED");
|
||||
stack.setStatusReason(e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> resolveDefaultParameters(JsonNode template, Map<String, String> callerParams) {
|
||||
Map<String, String> resolved = new HashMap<>(callerParams != null ? callerParams : Map.of());
|
||||
JsonNode paramDefs = template.path("Parameters");
|
||||
if (paramDefs.isObject()) {
|
||||
paramDefs.fields().forEachRemaining(e -> {
|
||||
String paramName = e.getKey();
|
||||
JsonNode paramDef = e.getValue();
|
||||
if (!resolved.containsKey(paramName) && paramDef.has("Default")) {
|
||||
resolved.put(paramName, paramDef.path("Default").asText());
|
||||
}
|
||||
});
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private Map<String, Boolean> resolveConditions(JsonNode template, Map<String, String> params,
|
||||
Stack stack, String region) {
|
||||
Map<String, Boolean> conditions = new HashMap<>();
|
||||
JsonNode condNode = template.path("Conditions");
|
||||
if (!condNode.isObject()) {
|
||||
return conditions;
|
||||
}
|
||||
// Two-pass: collect all names first, then evaluate (handles forward references)
|
||||
condNode.fields().forEachRemaining(e -> conditions.put(e.getKey(), false));
|
||||
condNode.fields().forEachRemaining(e ->
|
||||
conditions.put(e.getKey(), evaluateCondition(e.getValue(), params, conditions)));
|
||||
return conditions;
|
||||
}
|
||||
|
||||
private boolean evaluateCondition(JsonNode expr, Map<String, String> params,
|
||||
Map<String, Boolean> conditions) {
|
||||
if (expr == null || expr.isNull()) {
|
||||
return false;
|
||||
}
|
||||
if (expr.isBoolean()) {
|
||||
return expr.booleanValue();
|
||||
}
|
||||
if (expr.isObject()) {
|
||||
if (expr.has("Condition")) {
|
||||
return conditions.getOrDefault(expr.get("Condition").asText(), false);
|
||||
}
|
||||
if (expr.has("Fn::Equals")) {
|
||||
JsonNode args = expr.get("Fn::Equals");
|
||||
if (args.isArray() && args.size() == 2) {
|
||||
String left = resolveConditionValue(args.get(0), params);
|
||||
String right = resolveConditionValue(args.get(1), params);
|
||||
return left.equals(right);
|
||||
}
|
||||
}
|
||||
if (expr.has("Fn::Not")) {
|
||||
JsonNode args = expr.get("Fn::Not");
|
||||
if (args.isArray() && !args.isEmpty()) {
|
||||
return !evaluateCondition(args.get(0), params, conditions);
|
||||
}
|
||||
}
|
||||
if (expr.has("Fn::And")) {
|
||||
for (JsonNode item : expr.get("Fn::And")) {
|
||||
if (!evaluateCondition(item, params, conditions)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (expr.has("Fn::Or")) {
|
||||
for (JsonNode item : expr.get("Fn::Or")) {
|
||||
if (evaluateCondition(item, params, conditions)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String resolveConditionValue(JsonNode node, Map<String, String> params) {
|
||||
if (node.isTextual()) {
|
||||
return node.textValue();
|
||||
}
|
||||
if (node.isObject() && node.has("Ref")) {
|
||||
String name = node.get("Ref").asText();
|
||||
return switch (name) {
|
||||
case "AWS::AccountId" -> config.defaultAccountId();
|
||||
case "AWS::Region" -> "us-east-1";
|
||||
case "AWS::NoValue" -> "";
|
||||
default -> params.getOrDefault(name, "");
|
||||
};
|
||||
}
|
||||
return node.asText();
|
||||
}
|
||||
|
||||
private JsonNode parseTemplate(String templateBody) throws Exception {
|
||||
String trimmed = templateBody != null ? templateBody.trim() : "{}";
|
||||
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
||||
return objectMapper.readTree(trimmed);
|
||||
}
|
||||
// YAML template — use CF-aware parser to handle !Sub, !Ref, !GetAtt etc.
|
||||
return new CloudFormationYamlParser(objectMapper).parse(trimmed);
|
||||
}
|
||||
|
||||
private String resolveTemplate(String templateBody, String templateUrl) {
|
||||
if (templateBody != null && !templateBody.isBlank()) {
|
||||
return templateBody;
|
||||
}
|
||||
if (templateUrl != null && !templateUrl.isBlank()) {
|
||||
return fetchTemplateFromS3(templateUrl);
|
||||
}
|
||||
return "{}";
|
||||
}
|
||||
|
||||
private String fetchTemplateFromS3(String url) {
|
||||
try {
|
||||
// Parse S3 URL: http://host:port/bucket/key or https://bucket.s3.amazonaws.com/key
|
||||
String bucket;
|
||||
String key;
|
||||
if (url.contains(".s3.amazonaws.com") || url.contains(".s3.")) {
|
||||
// Virtual-hosted: https://bucket.s3.region.amazonaws.com/key
|
||||
String host = url.replaceFirst("https?://", "").split("/")[0];
|
||||
bucket = host.split("\\.")[0];
|
||||
key = url.substring(url.indexOf('/', url.indexOf("://") + 3) + 1);
|
||||
} else {
|
||||
// Path-style: http://host:port/bucket/key
|
||||
String path = url.replaceFirst("https?://[^/]+/", "");
|
||||
int slash = path.indexOf('/');
|
||||
bucket = slash > 0 ? path.substring(0, slash) : path;
|
||||
key = slash > 0 ? path.substring(slash + 1) : "";
|
||||
}
|
||||
var obj = s3Service.getObject(bucket, key);
|
||||
return new String(obj.getData());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to fetch template from {0}: {1}", url, e.getMessage());
|
||||
return "{}";
|
||||
}
|
||||
}
|
||||
|
||||
private Stack newStack(String stackName, String region) {
|
||||
Stack stack = new Stack();
|
||||
stack.setStackName(stackName);
|
||||
stack.setRegion(region);
|
||||
stack.setStatus("REVIEW_IN_PROGRESS");
|
||||
String stackId = "arn:aws:cloudformation:" + region + ":" + config.defaultAccountId() +
|
||||
":stack/" + stackName + "/" + UUID.randomUUID();
|
||||
stack.setStackId(stackId);
|
||||
stack.setCreationTime(Instant.now());
|
||||
return stack;
|
||||
}
|
||||
|
||||
private void addEvent(Stack stack, String logicalId, String physicalId,
|
||||
String resourceType, String status, String reason) {
|
||||
StackEvent event = new StackEvent();
|
||||
event.setStackId(stack.getStackId());
|
||||
event.setStackName(stack.getStackName());
|
||||
event.setLogicalResourceId(logicalId);
|
||||
event.setPhysicalResourceId(physicalId);
|
||||
event.setResourceType(resourceType);
|
||||
event.setResourceStatus(status);
|
||||
event.setResourceStatusReason(reason);
|
||||
stack.getEvents().add(event);
|
||||
}
|
||||
|
||||
private Stack getStackOrThrow(String stackName, String region) {
|
||||
Stack stack = stacks.get(key(stackName, region));
|
||||
if (stack == null) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Stack with id " + stackName + " does not exist", 400);
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
|
||||
private static String key(String stackName, String region) {
|
||||
return region + ":" + stackName;
|
||||
}
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Resolves CloudFormation intrinsic functions and pseudo-parameters in template nodes.
|
||||
* Supported: Ref, Fn::Sub, Fn::Join, Fn::Select, Fn::If, Fn::Split, Fn::Base64,
|
||||
* Fn::GetAtt, Condition.
|
||||
*/
|
||||
public class CloudFormationTemplateEngine {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFormationTemplateEngine.class);
|
||||
|
||||
private final String accountId;
|
||||
private final String region;
|
||||
private final String stackName;
|
||||
private final String stackId;
|
||||
private final Map<String, String> parameters;
|
||||
private final Map<String, String> physicalIds;
|
||||
private final Map<String, Map<String, String>> resourceAttributes;
|
||||
private final Map<String, Boolean> conditions;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
CloudFormationTemplateEngine(String accountId, String region, String stackName, String stackId,
|
||||
Map<String, String> parameters,
|
||||
Map<String, String> physicalIds,
|
||||
Map<String, Map<String, String>> resourceAttributes,
|
||||
Map<String, Boolean> conditions,
|
||||
ObjectMapper objectMapper) {
|
||||
this.accountId = accountId;
|
||||
this.region = region;
|
||||
this.stackName = stackName;
|
||||
this.stackId = stackId;
|
||||
this.parameters = parameters;
|
||||
this.physicalIds = physicalIds;
|
||||
this.resourceAttributes = resourceAttributes;
|
||||
this.conditions = conditions;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public String resolve(JsonNode node) {
|
||||
if (node == null || node.isNull() || node.isMissingNode()) {
|
||||
return "";
|
||||
}
|
||||
if (node.isTextual()) {
|
||||
return node.textValue();
|
||||
}
|
||||
if (node.isNumber()) {
|
||||
return node.asText();
|
||||
}
|
||||
if (node.isBoolean()) {
|
||||
return node.asText();
|
||||
}
|
||||
if (node.isObject()) {
|
||||
if (node.has("Ref")) {
|
||||
return resolveRef(node.get("Ref").asText());
|
||||
}
|
||||
if (node.has("Fn::Sub")) {
|
||||
return resolveSub(node.get("Fn::Sub"));
|
||||
}
|
||||
if (node.has("Fn::Join")) {
|
||||
return resolveJoin(node.get("Fn::Join"));
|
||||
}
|
||||
if (node.has("Fn::Select")) {
|
||||
return resolveSelect(node.get("Fn::Select"));
|
||||
}
|
||||
if (node.has("Fn::If")) {
|
||||
return resolveIf(node.get("Fn::If"));
|
||||
}
|
||||
if (node.has("Fn::Base64")) {
|
||||
return Base64.getEncoder().encodeToString(resolve(node.get("Fn::Base64")).getBytes());
|
||||
}
|
||||
if (node.has("Fn::Split")) {
|
||||
return resolve(node.get("Fn::Split").get(1));
|
||||
}
|
||||
if (node.has("Fn::GetAtt")) {
|
||||
return resolveGetAtt(node.get("Fn::GetAtt"));
|
||||
}
|
||||
if (node.has("Fn::ImportValue")) {
|
||||
return resolve(node.get("Fn::ImportValue"));
|
||||
}
|
||||
}
|
||||
return node.asText();
|
||||
}
|
||||
|
||||
public JsonNode resolveNode(JsonNode node) {
|
||||
if (node == null || node.isNull() || node.isMissingNode()) {
|
||||
return node;
|
||||
}
|
||||
if (node.isTextual() || node.isNumber() || node.isBoolean()) {
|
||||
return node;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
if (node.has("Ref") || node.has("Fn::Sub") || node.has("Fn::Join") ||
|
||||
node.has("Fn::Select") || node.has("Fn::If") || node.has("Fn::Base64") ||
|
||||
node.has("Fn::GetAtt") || node.has("Fn::ImportValue") || node.has("Fn::Split")) {
|
||||
return TextNode.valueOf(resolve(node));
|
||||
}
|
||||
// Plain object — resolve each field
|
||||
var resolved = objectMapper.createObjectNode();
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
|
||||
while (fields.hasNext()) {
|
||||
var entry = fields.next();
|
||||
resolved.set(entry.getKey(), resolveNode(entry.getValue()));
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
if (node.isArray()) {
|
||||
var arr = objectMapper.createArrayNode();
|
||||
for (JsonNode item : node) {
|
||||
arr.add(resolveNode(item));
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private String resolveRef(String name) {
|
||||
// Pseudo-parameters
|
||||
return switch (name) {
|
||||
case "AWS::AccountId" -> accountId;
|
||||
case "AWS::Region" -> region;
|
||||
case "AWS::StackName" -> stackName;
|
||||
case "AWS::StackId" -> stackId;
|
||||
case "AWS::Partition" -> "aws";
|
||||
case "AWS::URLSuffix" -> "amazonaws.com";
|
||||
case "AWS::NoValue" -> "";
|
||||
default -> {
|
||||
if (physicalIds.containsKey(name)) {
|
||||
yield physicalIds.get(name);
|
||||
}
|
||||
if (parameters.containsKey(name)) {
|
||||
yield parameters.get(name);
|
||||
}
|
||||
LOG.debugv("Unresolved Ref: {0}", name);
|
||||
yield name;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private String resolveSub(JsonNode sub) {
|
||||
String template;
|
||||
Map<String, String> vars = new HashMap<>();
|
||||
if (sub.isTextual()) {
|
||||
template = sub.textValue();
|
||||
} else if (sub.isArray() && sub.size() == 2) {
|
||||
template = sub.get(0).textValue();
|
||||
JsonNode varMap = sub.get(1);
|
||||
if (varMap.isObject()) {
|
||||
varMap.fields().forEachRemaining(e -> vars.put(e.getKey(), resolve(e.getValue())));
|
||||
}
|
||||
} else {
|
||||
return sub.asText();
|
||||
}
|
||||
|
||||
StringBuilder result = new StringBuilder();
|
||||
int i = 0;
|
||||
while (i < template.length()) {
|
||||
if (template.charAt(i) == '$' && i + 1 < template.length() && template.charAt(i + 1) == '{') {
|
||||
int end = template.indexOf('}', i + 2);
|
||||
if (end == -1) {
|
||||
result.append(template.substring(i));
|
||||
break;
|
||||
}
|
||||
String varName = template.substring(i + 2, end);
|
||||
if (vars.containsKey(varName)) {
|
||||
result.append(vars.get(varName));
|
||||
} else if (varName.contains("!")) {
|
||||
// Fn::GetAtt shorthand: ${LogicalId.Attr}
|
||||
String[] parts = varName.split("\\.", 2);
|
||||
result.append(resolveGetAttParts(parts[0], parts.length > 1 ? parts[1] : ""));
|
||||
} else {
|
||||
result.append(resolveRef(varName));
|
||||
}
|
||||
i = end + 1;
|
||||
} else {
|
||||
result.append(template.charAt(i));
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
private String resolveJoin(JsonNode join) {
|
||||
if (!join.isArray() || join.size() < 2) {
|
||||
return "";
|
||||
}
|
||||
String delimiter = join.get(0).asText("");
|
||||
JsonNode parts = join.get(1);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < parts.size(); i++) {
|
||||
if (i > 0) {
|
||||
sb.append(delimiter);
|
||||
}
|
||||
sb.append(resolve(parts.get(i)));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String resolveSelect(JsonNode select) {
|
||||
if (!select.isArray() || select.size() < 2) {
|
||||
return "";
|
||||
}
|
||||
int index = select.get(0).asInt(0);
|
||||
JsonNode list = select.get(1);
|
||||
if (list.isArray() && index < list.size()) {
|
||||
return resolve(list.get(index));
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private String resolveIf(JsonNode ifNode) {
|
||||
if (!ifNode.isArray() || ifNode.size() < 3) {
|
||||
return "";
|
||||
}
|
||||
String conditionName = ifNode.get(0).asText();
|
||||
boolean condValue = conditions.getOrDefault(conditionName, false);
|
||||
return resolve(condValue ? ifNode.get(1) : ifNode.get(2));
|
||||
}
|
||||
|
||||
private String resolveGetAtt(JsonNode getAtt) {
|
||||
if (getAtt.isArray() && getAtt.size() == 2) {
|
||||
return resolveGetAttParts(getAtt.get(0).asText(), getAtt.get(1).asText());
|
||||
}
|
||||
if (getAtt.isTextual()) {
|
||||
String[] parts = getAtt.textValue().split("\\.", 2);
|
||||
return resolveGetAttParts(parts[0], parts.length > 1 ? parts[1] : "");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private String resolveGetAttParts(String logicalId, String attrName) {
|
||||
Map<String, String> attrs = resourceAttributes.get(logicalId);
|
||||
if (attrs != null && attrs.containsKey(attrName)) {
|
||||
return attrs.get(attrName);
|
||||
}
|
||||
LOG.debugv("Unresolved GetAtt: {0}.{1}", logicalId, attrName);
|
||||
return logicalId + "." + attrName;
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.Construct;
|
||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||
import org.yaml.snakeyaml.nodes.MappingNode;
|
||||
import org.yaml.snakeyaml.nodes.Node;
|
||||
import org.yaml.snakeyaml.nodes.ScalarNode;
|
||||
import org.yaml.snakeyaml.nodes.SequenceNode;
|
||||
import org.yaml.snakeyaml.nodes.Tag;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Parses CloudFormation YAML templates, properly converting shorthand intrinsic
|
||||
* function tags (!Ref, !Sub, !GetAtt, !If, !Join, !Select, etc.) to their
|
||||
* long-form map equivalents ({"Ref": ...}, {"Fn::Sub": ...}, etc.).
|
||||
*/
|
||||
public class CloudFormationYamlParser {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
CloudFormationYamlParser(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public JsonNode parse(String yamlContent) throws Exception {
|
||||
LoaderOptions opts = new LoaderOptions();
|
||||
opts.setMaxAliasesForCollections(200);
|
||||
Yaml yaml = new Yaml(new CfnConstructor(opts));
|
||||
Object data = yaml.load(yamlContent);
|
||||
return objectMapper.convertValue(data, JsonNode.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* SnakeYAML constructor that maps CloudFormation YAML shorthand tags to
|
||||
* their long-form intrinsic function maps.
|
||||
*/
|
||||
private static class CfnConstructor extends SafeConstructor {
|
||||
|
||||
CfnConstructor(LoaderOptions opts) {
|
||||
super(opts);
|
||||
// Register all CloudFormation shorthand tags
|
||||
register("!Ref", n -> scalarMap("Ref", scalar(n)));
|
||||
register("!Sub", n -> fnMap("Fn::Sub", n));
|
||||
register("!GetAtt", this::fnGetAtt);
|
||||
register("!If", n -> fnMap("Fn::If", n));
|
||||
register("!Join", n -> fnMap("Fn::Join", n));
|
||||
register("!Select", n -> fnMap("Fn::Select", n));
|
||||
register("!Base64", n -> fnMap("Fn::Base64", n));
|
||||
register("!FindInMap", n -> fnMap("Fn::FindInMap", n));
|
||||
register("!Split", n -> fnMap("Fn::Split", n));
|
||||
register("!ImportValue",n -> fnMap("Fn::ImportValue", n));
|
||||
register("!Condition", n -> scalarMap("Condition", scalar(n)));
|
||||
register("!And", n -> fnMap("Fn::And", n));
|
||||
register("!Or", n -> fnMap("Fn::Or", n));
|
||||
register("!Not", n -> fnMap("Fn::Not", n));
|
||||
register("!Equals", n -> fnMap("Fn::Equals", n));
|
||||
register("!Contains", n -> fnMap("Fn::Contains", n));
|
||||
register("!Length", n -> fnMap("Fn::Length", n));
|
||||
register("!ToJsonString", n -> fnMap("Fn::ToJsonString", n));
|
||||
register("!Transform", n -> fnMap("Fn::Transform", n));
|
||||
}
|
||||
|
||||
private void register(String tag, NodeConverter converter) {
|
||||
yamlConstructors.put(new Tag(tag), new Construct() {
|
||||
@Override
|
||||
public Object construct(Node node) {
|
||||
return converter.convert(node);
|
||||
}
|
||||
@Override
|
||||
public void construct2ndStep(Node node, Object data) {}
|
||||
});
|
||||
}
|
||||
|
||||
private String scalar(Node n) {
|
||||
return (n instanceof ScalarNode s) ? s.getValue() : n.toString();
|
||||
}
|
||||
|
||||
private Map<String, Object> scalarMap(String key, String value) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put(key, value);
|
||||
return map;
|
||||
}
|
||||
|
||||
private Object fnMap(String fnName, Node n) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put(fnName, construct(n));
|
||||
return map;
|
||||
}
|
||||
|
||||
private Object fnGetAtt(Node n) {
|
||||
String raw = scalar(n);
|
||||
// !GetAtt Resource.Attribute
|
||||
int dot = raw.indexOf('.');
|
||||
List<String> parts = new ArrayList<>();
|
||||
if (dot > 0) {
|
||||
parts.add(raw.substring(0, dot));
|
||||
parts.add(raw.substring(dot + 1));
|
||||
} else {
|
||||
parts.add(raw);
|
||||
}
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("Fn::GetAtt", parts);
|
||||
return map;
|
||||
}
|
||||
|
||||
private Object construct(Node n) {
|
||||
if (n instanceof ScalarNode s) {
|
||||
return constructScalar(s);
|
||||
} else if (n instanceof SequenceNode seq) {
|
||||
return constructSequence(seq);
|
||||
} else if (n instanceof MappingNode m) {
|
||||
return constructMapping(m);
|
||||
}
|
||||
return constructObject(n);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface NodeConverter {
|
||||
Object convert(Node node);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class ChangeSet {
|
||||
private String changeSetId;
|
||||
private String changeSetName;
|
||||
private String stackName;
|
||||
private String stackId;
|
||||
private String status = "CREATE_COMPLETE";
|
||||
private String executionStatus = "AVAILABLE";
|
||||
private String statusReason;
|
||||
private String templateBody;
|
||||
private Map<String, String> parameters;
|
||||
private List<String> capabilities;
|
||||
private String changeSetType; // CREATE or UPDATE
|
||||
private Instant creationTime = Instant.now();
|
||||
|
||||
public String getChangeSetId() { return changeSetId; }
|
||||
public void setChangeSetId(String changeSetId) { this.changeSetId = changeSetId; }
|
||||
public String getChangeSetName() { return changeSetName; }
|
||||
public void setChangeSetName(String changeSetName) { this.changeSetName = changeSetName; }
|
||||
public String getStackName() { return stackName; }
|
||||
public void setStackName(String stackName) { this.stackName = stackName; }
|
||||
public String getStackId() { return stackId; }
|
||||
public void setStackId(String stackId) { this.stackId = stackId; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public String getExecutionStatus() { return executionStatus; }
|
||||
public void setExecutionStatus(String executionStatus) { this.executionStatus = executionStatus; }
|
||||
public String getStatusReason() { return statusReason; }
|
||||
public void setStatusReason(String statusReason) { this.statusReason = statusReason; }
|
||||
public String getTemplateBody() { return templateBody; }
|
||||
public void setTemplateBody(String templateBody) { this.templateBody = templateBody; }
|
||||
public Map<String, String> getParameters() { return parameters; }
|
||||
public void setParameters(Map<String, String> parameters) { this.parameters = parameters; }
|
||||
public List<String> getCapabilities() { return capabilities; }
|
||||
public void setCapabilities(List<String> capabilities) { this.capabilities = capabilities; }
|
||||
public String getChangeSetType() { return changeSetType; }
|
||||
public void setChangeSetType(String changeSetType) { this.changeSetType = changeSetType; }
|
||||
public Instant getCreationTime() { return creationTime; }
|
||||
public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
|
||||
public class Stack {
|
||||
private String stackId;
|
||||
private String stackName;
|
||||
private String region;
|
||||
private String status = "CREATE_IN_PROGRESS";
|
||||
private String statusReason;
|
||||
private Instant creationTime = Instant.now();
|
||||
private Instant lastUpdatedTime;
|
||||
private String templateBody;
|
||||
private List<String> capabilities = new ArrayList<>();
|
||||
private Map<String, String> parameters = new LinkedHashMap<>();
|
||||
private Map<String, String> outputs = new LinkedHashMap<>();
|
||||
private Map<String, StackResource> resources = new LinkedHashMap<>();
|
||||
private List<StackEvent> events = new ArrayList<>();
|
||||
private Map<String, ChangeSet> changeSets = new LinkedHashMap<>();
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public String getStackId() { return stackId; }
|
||||
public void setStackId(String stackId) { this.stackId = stackId; }
|
||||
public String getStackName() { return stackName; }
|
||||
public void setStackName(String stackName) { this.stackName = stackName; }
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public String getStatusReason() { return statusReason; }
|
||||
public void setStatusReason(String statusReason) { this.statusReason = statusReason; }
|
||||
public Instant getCreationTime() { return creationTime; }
|
||||
public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }
|
||||
public Instant getLastUpdatedTime() { return lastUpdatedTime; }
|
||||
public void setLastUpdatedTime(Instant lastUpdatedTime) { this.lastUpdatedTime = lastUpdatedTime; }
|
||||
public String getTemplateBody() { return templateBody; }
|
||||
public void setTemplateBody(String templateBody) { this.templateBody = templateBody; }
|
||||
public List<String> getCapabilities() { return capabilities; }
|
||||
public void setCapabilities(List<String> capabilities) { this.capabilities = capabilities; }
|
||||
public Map<String, String> getParameters() { return parameters; }
|
||||
public void setParameters(Map<String, String> parameters) { this.parameters = parameters; }
|
||||
public Map<String, String> getOutputs() { return outputs; }
|
||||
public void setOutputs(Map<String, String> outputs) { this.outputs = outputs; }
|
||||
public Map<String, StackResource> getResources() { return resources; }
|
||||
public void setResources(Map<String, StackResource> resources) { this.resources = resources; }
|
||||
public List<StackEvent> getEvents() { return events; }
|
||||
public void setEvents(List<StackEvent> events) { this.events = events; }
|
||||
public Map<String, ChangeSet> getChangeSets() { return changeSets; }
|
||||
public void setChangeSets(Map<String, ChangeSet> changeSets) { this.changeSets = changeSets; }
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public class StackEvent {
|
||||
private String eventId = UUID.randomUUID().toString();
|
||||
private String stackId;
|
||||
private String stackName;
|
||||
private String logicalResourceId;
|
||||
private String physicalResourceId;
|
||||
private String resourceType;
|
||||
private String resourceStatus;
|
||||
private String resourceStatusReason;
|
||||
private Instant timestamp = Instant.now();
|
||||
|
||||
public String getEventId() { return eventId; }
|
||||
public void setEventId(String eventId) { this.eventId = eventId; }
|
||||
public String getStackId() { return stackId; }
|
||||
public void setStackId(String stackId) { this.stackId = stackId; }
|
||||
public String getStackName() { return stackName; }
|
||||
public void setStackName(String stackName) { this.stackName = stackName; }
|
||||
public String getLogicalResourceId() { return logicalResourceId; }
|
||||
public void setLogicalResourceId(String logicalResourceId) { this.logicalResourceId = logicalResourceId; }
|
||||
public String getPhysicalResourceId() { return physicalResourceId; }
|
||||
public void setPhysicalResourceId(String physicalResourceId) { this.physicalResourceId = physicalResourceId; }
|
||||
public String getResourceType() { return resourceType; }
|
||||
public void setResourceType(String resourceType) { this.resourceType = resourceType; }
|
||||
public String getResourceStatus() { return resourceStatus; }
|
||||
public void setResourceStatus(String resourceStatus) { this.resourceStatus = resourceStatus; }
|
||||
public String getResourceStatusReason() { return resourceStatusReason; }
|
||||
public void setResourceStatusReason(String reason) { this.resourceStatusReason = reason; }
|
||||
public Instant getTimestamp() { return timestamp; }
|
||||
public void setTimestamp(Instant timestamp) { this.timestamp = timestamp; }
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class StackResource {
|
||||
private String logicalId;
|
||||
private String physicalId;
|
||||
private String resourceType;
|
||||
private String status = "CREATE_IN_PROGRESS";
|
||||
private String statusReason;
|
||||
private Instant timestamp = Instant.now();
|
||||
private Map<String, String> attributes = new HashMap<>();
|
||||
|
||||
public String getLogicalId() { return logicalId; }
|
||||
public void setLogicalId(String logicalId) { this.logicalId = logicalId; }
|
||||
public String getPhysicalId() { return physicalId; }
|
||||
public void setPhysicalId(String physicalId) { this.physicalId = physicalId; }
|
||||
public String getResourceType() { return resourceType; }
|
||||
public void setResourceType(String resourceType) { this.resourceType = resourceType; }
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
public String getStatusReason() { return statusReason; }
|
||||
public void setStatusReason(String statusReason) { this.statusReason = statusReason; }
|
||||
public Instant getTimestamp() { return timestamp; }
|
||||
public void setTimestamp(Instant timestamp) { this.timestamp = timestamp; }
|
||||
public Map<String, String> getAttributes() { return attributes; }
|
||||
public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; }
|
||||
}
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogStream;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CloudWatchLogsHandler {
|
||||
|
||||
private final CloudWatchLogsService logsService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public CloudWatchLogsHandler(CloudWatchLogsService logsService, ObjectMapper objectMapper) {
|
||||
this.logsService = logsService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
return switch (action) {
|
||||
case "CreateLogGroup" -> handleCreateLogGroup(request, region);
|
||||
case "DeleteLogGroup" -> handleDeleteLogGroup(request, region);
|
||||
case "DescribeLogGroups" -> handleDescribeLogGroups(request, region);
|
||||
case "CreateLogStream" -> handleCreateLogStream(request, region);
|
||||
case "DeleteLogStream" -> handleDeleteLogStream(request, region);
|
||||
case "DescribeLogStreams" -> handleDescribeLogStreams(request, region);
|
||||
case "PutLogEvents" -> handlePutLogEvents(request, region);
|
||||
case "GetLogEvents" -> handleGetLogEvents(request, region);
|
||||
case "FilterLogEvents" -> handleFilterLogEvents(request, region);
|
||||
case "PutRetentionPolicy" -> handlePutRetentionPolicy(request, region);
|
||||
case "DeleteRetentionPolicy" -> handleDeleteRetentionPolicy(request, region);
|
||||
case "TagLogGroup" -> handleTagLogGroup(request, region);
|
||||
case "UntagLogGroup" -> handleUntagLogGroup(request, region);
|
||||
case "ListTagsLogGroup" -> handleListTagsLogGroup(request, region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
|
||||
.build();
|
||||
};
|
||||
}
|
||||
|
||||
private Response handleCreateLogGroup(JsonNode request, String region) {
|
||||
String name = request.path("logGroupName").asText();
|
||||
Integer retentionInDays = request.has("retentionInDays")
|
||||
? request.path("retentionInDays").asInt() : null;
|
||||
Map<String, String> tags = extractTags(request.path("tags"));
|
||||
logsService.createLogGroup(name, retentionInDays, tags, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteLogGroup(JsonNode request, String region) {
|
||||
String name = request.path("logGroupName").asText();
|
||||
logsService.deleteLogGroup(name, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeLogGroups(JsonNode request, String region) {
|
||||
String prefix = request.path("logGroupNamePrefix").asText(null);
|
||||
List<LogGroup> groups = logsService.describeLogGroups(prefix, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode groupsArray = objectMapper.createArrayNode();
|
||||
for (LogGroup g : groups) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("logGroupName", g.getLogGroupName());
|
||||
node.put("createdTime", g.getCreatedTime());
|
||||
node.put("arn", logsService.buildArn(g.getLogGroupName(), region));
|
||||
if (g.getRetentionInDays() != null) {
|
||||
node.put("retentionInDays", g.getRetentionInDays());
|
||||
}
|
||||
node.put("storedBytes", 0);
|
||||
node.put("metricFilterCount", 0);
|
||||
groupsArray.add(node);
|
||||
}
|
||||
response.set("logGroups", groupsArray);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleCreateLogStream(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
String streamName = request.path("logStreamName").asText();
|
||||
logsService.createLogStream(groupName, streamName, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteLogStream(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
String streamName = request.path("logStreamName").asText();
|
||||
logsService.deleteLogStream(groupName, streamName, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeLogStreams(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
String prefix = request.path("logStreamNamePrefix").asText(null);
|
||||
List<LogStream> streams = logsService.describeLogStreams(groupName, prefix, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode streamsArray = objectMapper.createArrayNode();
|
||||
for (LogStream s : streams) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("logStreamName", s.getLogStreamName());
|
||||
node.put("createdTime", s.getCreatedTime());
|
||||
node.put("lastIngestionTime", s.getLastIngestionTime());
|
||||
node.put("uploadSequenceToken", s.getUploadSequenceToken());
|
||||
node.put("storedBytes", s.getStoredBytes());
|
||||
if (s.getFirstEventTimestamp() != null) {
|
||||
node.put("firstEventTimestamp", s.getFirstEventTimestamp());
|
||||
}
|
||||
if (s.getLastEventTimestamp() != null) {
|
||||
node.put("lastEventTimestamp", s.getLastEventTimestamp());
|
||||
}
|
||||
streamsArray.add(node);
|
||||
}
|
||||
response.set("logStreams", streamsArray);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handlePutLogEvents(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
String streamName = request.path("logStreamName").asText();
|
||||
|
||||
List<Map<String, Object>> events = new ArrayList<>();
|
||||
request.path("logEvents").forEach(evt -> {
|
||||
Map<String, Object> event = new HashMap<>();
|
||||
event.put("timestamp", evt.path("timestamp").asLong());
|
||||
event.put("message", evt.path("message").asText());
|
||||
events.add(event);
|
||||
});
|
||||
|
||||
String nextToken = logsService.putLogEvents(groupName, streamName, events, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("nextSequenceToken", nextToken);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGetLogEvents(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
String streamName = request.path("logStreamName").asText();
|
||||
Long startTime = request.has("startTime") ? request.path("startTime").asLong() : null;
|
||||
Long endTime = request.has("endTime") ? request.path("endTime").asLong() : null;
|
||||
int limit = request.path("limit").asInt(0);
|
||||
boolean startFromHead = request.path("startFromHead").asBoolean(false);
|
||||
|
||||
CloudWatchLogsService.LogEventsResult result =
|
||||
logsService.getLogEvents(groupName, streamName, startTime, endTime, limit, startFromHead, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("events", buildEventsArray(result.events()));
|
||||
response.put("nextForwardToken", result.nextForwardToken());
|
||||
response.put("nextBackwardToken", result.nextBackwardToken());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleFilterLogEvents(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
Long startTime = request.has("startTime") ? request.path("startTime").asLong() : null;
|
||||
Long endTime = request.has("endTime") ? request.path("endTime").asLong() : null;
|
||||
String filterPattern = request.path("filterPattern").asText(null);
|
||||
int limit = request.path("limit").asInt(0);
|
||||
|
||||
List<String> streamNames = new ArrayList<>();
|
||||
request.path("logStreamNames").forEach(n -> streamNames.add(n.asText()));
|
||||
|
||||
CloudWatchLogsService.FilteredLogEventsResult result =
|
||||
logsService.filterLogEvents(groupName, streamNames, startTime, endTime, filterPattern, limit, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("events", buildEventsArray(result.events()));
|
||||
if (result.nextToken() != null) {
|
||||
response.put("nextToken", result.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handlePutRetentionPolicy(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
int days = request.path("retentionInDays").asInt();
|
||||
logsService.putRetentionPolicy(groupName, days, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteRetentionPolicy(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
logsService.deleteRetentionPolicy(groupName, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleTagLogGroup(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
Map<String, String> tags = extractTags(request.path("tags"));
|
||||
logsService.tagLogGroup(groupName, tags, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleUntagLogGroup(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
List<String> tagKeys = new ArrayList<>();
|
||||
request.path("tags").forEach(k -> tagKeys.add(k.asText()));
|
||||
logsService.untagLogGroup(groupName, tagKeys, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleListTagsLogGroup(JsonNode request, String region) {
|
||||
String groupName = request.path("logGroupName").asText();
|
||||
Map<String, String> tags = logsService.listTagsLogGroup(groupName, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ObjectNode tagsNode = objectMapper.createObjectNode();
|
||||
tags.forEach(tagsNode::put);
|
||||
response.set("tags", tagsNode);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Helpers ────────────────────────────
|
||||
|
||||
private ArrayNode buildEventsArray(List<LogEvent> events) {
|
||||
ArrayNode array = objectMapper.createArrayNode();
|
||||
for (LogEvent e : events) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("eventId", e.getEventId());
|
||||
node.put("timestamp", e.getTimestamp());
|
||||
node.put("message", e.getMessage());
|
||||
node.put("ingestionTime", e.getIngestionTime());
|
||||
array.add(node);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
private Map<String, String> extractTags(JsonNode tagsNode) {
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
if (tagsNode != null && tagsNode.isObject()) {
|
||||
tagsNode.fields().forEachRemaining(entry -> tags.put(entry.getKey(), entry.getValue().asText()));
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
}
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogStream;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CloudWatchLogsService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchLogsService.class);
|
||||
|
||||
private final StorageBackend<String, LogGroup> groupStore;
|
||||
private final StorageBackend<String, LogStream> streamStore;
|
||||
private final StorageBackend<String, LogEvent> eventStore;
|
||||
private final RegionResolver regionResolver;
|
||||
private final int maxEventsPerQuery;
|
||||
|
||||
@Inject
|
||||
public CloudWatchLogsService(StorageFactory storageFactory,
|
||||
EmulatorConfig config,
|
||||
RegionResolver regionResolver) {
|
||||
this(
|
||||
storageFactory.create("cloudwatchlogs", "cwlogs-groups.json",
|
||||
new TypeReference<>() {}),
|
||||
storageFactory.create("cloudwatchlogs", "cwlogs-streams.json",
|
||||
new TypeReference<>() {}),
|
||||
storageFactory.create("cloudwatchlogs", "cwlogs-events.json",
|
||||
new TypeReference<>() {}),
|
||||
config.services().cloudwatchlogs().maxEventsPerQuery(),
|
||||
regionResolver
|
||||
);
|
||||
}
|
||||
|
||||
CloudWatchLogsService(StorageBackend<String, LogGroup> groupStore,
|
||||
StorageBackend<String, LogStream> streamStore,
|
||||
StorageBackend<String, LogEvent> eventStore,
|
||||
int maxEventsPerQuery,
|
||||
RegionResolver regionResolver) {
|
||||
this.groupStore = groupStore;
|
||||
this.streamStore = streamStore;
|
||||
this.eventStore = eventStore;
|
||||
this.maxEventsPerQuery = maxEventsPerQuery;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Log Groups ────────────────────────────
|
||||
|
||||
public void createLogGroup(String name, Integer retentionInDays, Map<String, String> tags, String region) {
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException", "logGroupName is required.", 400);
|
||||
}
|
||||
String key = groupKey(region, name);
|
||||
if (groupStore.get(key).isPresent()) {
|
||||
throw new AwsException("ResourceAlreadyExistsException",
|
||||
"The specified log group already exists: " + name, 400);
|
||||
}
|
||||
LogGroup group = new LogGroup();
|
||||
group.setLogGroupName(name);
|
||||
group.setCreatedTime(System.currentTimeMillis());
|
||||
group.setRetentionInDays(retentionInDays);
|
||||
if (tags != null) {
|
||||
group.setTags(new HashMap<>(tags));
|
||||
}
|
||||
groupStore.put(key, group);
|
||||
LOG.infov("Created log group: {0} in region {1}", name, region);
|
||||
}
|
||||
|
||||
public void deleteLogGroup(String name, String region) {
|
||||
String key = groupKey(region, name);
|
||||
groupStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + name, 400));
|
||||
|
||||
// Cascade: delete all streams and events for this group
|
||||
String streamPrefix = streamKeyPrefix(region, name);
|
||||
List<String> streamKeys = streamStore.keys().stream()
|
||||
.filter(k -> k.startsWith(streamPrefix))
|
||||
.toList();
|
||||
for (String sk : streamKeys) {
|
||||
LogStream stream = streamStore.get(sk).orElse(null);
|
||||
if (stream != null) {
|
||||
deleteEventsForStream(region, name, stream.getLogStreamName());
|
||||
streamStore.delete(sk);
|
||||
}
|
||||
}
|
||||
groupStore.delete(key);
|
||||
LOG.infov("Deleted log group: {0}", name);
|
||||
}
|
||||
|
||||
public List<LogGroup> describeLogGroups(String prefix, String region) {
|
||||
String storagePrefix = groupKeyPrefix(region);
|
||||
List<LogGroup> result = groupStore.scan(k -> {
|
||||
if (!k.startsWith(storagePrefix)) {
|
||||
return false;
|
||||
}
|
||||
if (prefix == null || prefix.isBlank()) {
|
||||
return true;
|
||||
}
|
||||
String groupName = k.substring(storagePrefix.length());
|
||||
return groupName.startsWith(prefix);
|
||||
});
|
||||
result.sort(Comparator.comparing(LogGroup::getLogGroupName));
|
||||
return result;
|
||||
}
|
||||
|
||||
public void putRetentionPolicy(String groupName, int days, String region) {
|
||||
String key = groupKey(region, groupName);
|
||||
LogGroup group = groupStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + groupName, 400));
|
||||
group.setRetentionInDays(days);
|
||||
groupStore.put(key, group);
|
||||
}
|
||||
|
||||
public void deleteRetentionPolicy(String groupName, String region) {
|
||||
String key = groupKey(region, groupName);
|
||||
LogGroup group = groupStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + groupName, 400));
|
||||
group.setRetentionInDays(null);
|
||||
groupStore.put(key, group);
|
||||
}
|
||||
|
||||
public void tagLogGroup(String groupName, Map<String, String> tags, String region) {
|
||||
String key = groupKey(region, groupName);
|
||||
LogGroup group = groupStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + groupName, 400));
|
||||
group.getTags().putAll(tags);
|
||||
groupStore.put(key, group);
|
||||
}
|
||||
|
||||
public void untagLogGroup(String groupName, List<String> tagKeys, String region) {
|
||||
String key = groupKey(region, groupName);
|
||||
LogGroup group = groupStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + groupName, 400));
|
||||
tagKeys.forEach(group.getTags()::remove);
|
||||
groupStore.put(key, group);
|
||||
}
|
||||
|
||||
public Map<String, String> listTagsLogGroup(String groupName, String region) {
|
||||
String key = groupKey(region, groupName);
|
||||
LogGroup group = groupStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + groupName, 400));
|
||||
return group.getTags();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Log Streams ────────────────────────────
|
||||
|
||||
public void createLogStream(String groupName, String streamName, String region) {
|
||||
String groupKey = groupKey(region, groupName);
|
||||
groupStore.get(groupKey)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + groupName, 400));
|
||||
|
||||
String streamKey = streamKey(region, groupName, streamName);
|
||||
if (streamStore.get(streamKey).isPresent()) {
|
||||
throw new AwsException("ResourceAlreadyExistsException",
|
||||
"The specified log stream already exists: " + streamName, 400);
|
||||
}
|
||||
|
||||
LogStream stream = new LogStream();
|
||||
stream.setLogGroupName(groupName);
|
||||
stream.setLogStreamName(streamName);
|
||||
stream.setCreatedTime(System.currentTimeMillis());
|
||||
stream.setUploadSequenceToken(UUID.randomUUID().toString());
|
||||
streamStore.put(streamKey, stream);
|
||||
LOG.infov("Created log stream: {0}/{1}", groupName, streamName);
|
||||
}
|
||||
|
||||
public void deleteLogStream(String groupName, String streamName, String region) {
|
||||
String streamKey = streamKey(region, groupName, streamName);
|
||||
streamStore.get(streamKey)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log stream does not exist: " + streamName, 400));
|
||||
|
||||
deleteEventsForStream(region, groupName, streamName);
|
||||
streamStore.delete(streamKey);
|
||||
LOG.infov("Deleted log stream: {0}/{1}", groupName, streamName);
|
||||
}
|
||||
|
||||
public List<LogStream> describeLogStreams(String groupName, String prefix, String region) {
|
||||
// Verify group exists
|
||||
groupStore.get(groupKey(region, groupName))
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log group does not exist: " + groupName, 400));
|
||||
|
||||
String storagePrefix = streamKeyPrefix(region, groupName);
|
||||
List<LogStream> result = streamStore.scan(k -> {
|
||||
if (!k.startsWith(storagePrefix)) {
|
||||
return false;
|
||||
}
|
||||
if (prefix == null || prefix.isBlank()) {
|
||||
return true;
|
||||
}
|
||||
String streamName = k.substring(storagePrefix.length());
|
||||
return streamName.startsWith(prefix);
|
||||
});
|
||||
result.sort(Comparator.comparing(LogStream::getLogStreamName));
|
||||
return result;
|
||||
}
|
||||
|
||||
// ──────────────────────────── Log Events ────────────────────────────
|
||||
|
||||
public String putLogEvents(String groupName, String streamName,
|
||||
List<Map<String, Object>> events, String region) {
|
||||
String streamKey = streamKey(region, groupName, streamName);
|
||||
LogStream stream = streamStore.get(streamKey)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The specified log stream does not exist: " + streamName, 400));
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
long totalBytes = 0;
|
||||
Long minTs = null;
|
||||
Long maxTs = null;
|
||||
|
||||
for (Map<String, Object> evt : events) {
|
||||
long ts = toLong(evt.get("timestamp"), now);
|
||||
String msg = (String) evt.getOrDefault("message", "");
|
||||
|
||||
LogEvent logEvent = new LogEvent();
|
||||
logEvent.setEventId(UUID.randomUUID().toString());
|
||||
logEvent.setTimestamp(ts);
|
||||
logEvent.setMessage(msg);
|
||||
logEvent.setIngestionTime(now);
|
||||
|
||||
String eventKey = eventKey(region, groupName, streamName, ts, logEvent.getEventId());
|
||||
eventStore.put(eventKey, logEvent);
|
||||
|
||||
totalBytes += msg.getBytes().length + 26; // approx overhead
|
||||
if (minTs == null || ts < minTs) { minTs = ts; }
|
||||
if (maxTs == null || ts > maxTs) { maxTs = ts; }
|
||||
}
|
||||
|
||||
// Update stream metadata
|
||||
if (minTs != null) {
|
||||
if (stream.getFirstEventTimestamp() == null || minTs < stream.getFirstEventTimestamp()) {
|
||||
stream.setFirstEventTimestamp(minTs);
|
||||
}
|
||||
}
|
||||
if (maxTs != null) {
|
||||
stream.setLastEventTimestamp(maxTs);
|
||||
}
|
||||
stream.setLastIngestionTime(now);
|
||||
stream.setStoredBytes(stream.getStoredBytes() + totalBytes);
|
||||
String nextToken = UUID.randomUUID().toString();
|
||||
stream.setUploadSequenceToken(nextToken);
|
||||
streamStore.put(streamKey, stream);
|
||||
|
||||
return nextToken;
|
||||
}
|
||||
|
||||
public record LogEventsResult(List<LogEvent> events, String nextForwardToken, String nextBackwardToken) {}
|
||||
|
||||
public LogEventsResult getLogEvents(String groupName, String streamName,
|
||||
Long startTime, Long endTime,
|
||||
int limit, boolean startFromHead, String region) {
|
||||
int maxEvents = Math.min(limit > 0 ? limit : Integer.MAX_VALUE,
|
||||
maxEventsPerQuery);
|
||||
|
||||
String eventPrefix = eventKeyPrefix(region, groupName, streamName);
|
||||
List<LogEvent> all = eventStore.scan(k -> k.startsWith(eventPrefix));
|
||||
all.sort(Comparator.comparingLong(LogEvent::getTimestamp));
|
||||
|
||||
List<LogEvent> filtered = all.stream()
|
||||
.filter(e -> (startTime == null || e.getTimestamp() >= startTime)
|
||||
&& (endTime == null || e.getTimestamp() <= endTime))
|
||||
.toList();
|
||||
|
||||
List<LogEvent> page;
|
||||
if (!startFromHead && filtered.size() > maxEvents) {
|
||||
page = filtered.subList(filtered.size() - maxEvents, filtered.size());
|
||||
} else {
|
||||
page = filtered.size() > maxEvents ? filtered.subList(0, maxEvents) : filtered;
|
||||
}
|
||||
|
||||
String forwardToken = "f/" + UUID.randomUUID();
|
||||
String backwardToken = "b/" + UUID.randomUUID();
|
||||
return new LogEventsResult(page, forwardToken, backwardToken);
|
||||
}
|
||||
|
||||
public record FilteredLogEventsResult(List<LogEvent> events, String nextToken) {}
|
||||
|
||||
public FilteredLogEventsResult filterLogEvents(String groupName, List<String> streamNames,
|
||||
Long startTime, Long endTime,
|
||||
String filterPattern, int limit,
|
||||
String region) {
|
||||
int maxEvents = Math.min(limit > 0 ? limit : Integer.MAX_VALUE,
|
||||
maxEventsPerQuery);
|
||||
|
||||
String groupPrefix = groupKeyPrefix(region) + groupName + "::";
|
||||
List<LogEvent> all = new ArrayList<>();
|
||||
|
||||
if (streamNames != null && !streamNames.isEmpty()) {
|
||||
for (String sn : streamNames) {
|
||||
String eventPrefix = eventKeyPrefix(region, groupName, sn);
|
||||
all.addAll(eventStore.scan(k -> k.startsWith(eventPrefix)));
|
||||
}
|
||||
} else {
|
||||
// All streams in group
|
||||
all.addAll(eventStore.scan(k -> k.startsWith(groupPrefix)));
|
||||
}
|
||||
|
||||
all.sort(Comparator.comparingLong(LogEvent::getTimestamp));
|
||||
|
||||
List<LogEvent> result = all.stream()
|
||||
.filter(e -> (startTime == null || e.getTimestamp() >= startTime)
|
||||
&& (endTime == null || e.getTimestamp() <= endTime))
|
||||
.filter(e -> filterPattern == null || filterPattern.isBlank()
|
||||
|| e.getMessage().contains(filterPattern))
|
||||
.limit(maxEvents)
|
||||
.toList();
|
||||
|
||||
String nextToken = result.size() >= maxEvents ? UUID.randomUUID().toString() : null;
|
||||
return new FilteredLogEventsResult(result, nextToken);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Helpers ────────────────────────────
|
||||
|
||||
private void deleteEventsForStream(String region, String groupName, String streamName) {
|
||||
String eventPrefix = eventKeyPrefix(region, groupName, streamName);
|
||||
List<String> keys = eventStore.keys().stream()
|
||||
.filter(k -> k.startsWith(eventPrefix))
|
||||
.toList();
|
||||
keys.forEach(eventStore::delete);
|
||||
}
|
||||
|
||||
public String buildArn(String groupName, String region) {
|
||||
return regionResolver.buildArn("logs", region, "log-group:" + groupName);
|
||||
}
|
||||
|
||||
private static String groupKeyPrefix(String region) {
|
||||
return region + "::";
|
||||
}
|
||||
|
||||
private static String groupKey(String region, String groupName) {
|
||||
return region + "::" + groupName;
|
||||
}
|
||||
|
||||
private static String streamKeyPrefix(String region, String groupName) {
|
||||
return region + "::" + groupName + "::";
|
||||
}
|
||||
|
||||
private static String streamKey(String region, String groupName, String streamName) {
|
||||
return region + "::" + groupName + "::" + streamName;
|
||||
}
|
||||
|
||||
private static String eventKeyPrefix(String region, String groupName, String streamName) {
|
||||
return region + "::" + groupName + "::" + streamName + "::";
|
||||
}
|
||||
|
||||
private static String eventKey(String region, String groupName, String streamName,
|
||||
long timestamp, String uuid) {
|
||||
return region + "::" + groupName + "::" + streamName + "::"
|
||||
+ String.format("%015d", timestamp) + "::" + uuid;
|
||||
}
|
||||
|
||||
private static long toLong(Object value, long defaultValue) {
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (value instanceof Number n) {
|
||||
return n.longValue();
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(value.toString());
|
||||
} catch (NumberFormatException e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class LogEvent {
|
||||
|
||||
private String eventId;
|
||||
private long timestamp;
|
||||
private String message;
|
||||
private long ingestionTime;
|
||||
|
||||
public LogEvent() {}
|
||||
|
||||
public String getEventId() { return eventId; }
|
||||
public void setEventId(String eventId) { this.eventId = eventId; }
|
||||
|
||||
public long getTimestamp() { return timestamp; }
|
||||
public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
|
||||
|
||||
public String getMessage() { return message; }
|
||||
public void setMessage(String message) { this.message = message; }
|
||||
|
||||
public long getIngestionTime() { return ingestionTime; }
|
||||
public void setIngestionTime(long ingestionTime) { this.ingestionTime = ingestionTime; }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class LogGroup {
|
||||
|
||||
private String logGroupName;
|
||||
private long createdTime;
|
||||
private Integer retentionInDays;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
|
||||
public LogGroup() {}
|
||||
|
||||
public String getLogGroupName() { return logGroupName; }
|
||||
public void setLogGroupName(String logGroupName) { this.logGroupName = logGroupName; }
|
||||
|
||||
public long getCreatedTime() { return createdTime; }
|
||||
public void setCreatedTime(long createdTime) { this.createdTime = createdTime; }
|
||||
|
||||
public Integer getRetentionInDays() { return retentionInDays; }
|
||||
public void setRetentionInDays(Integer retentionInDays) { this.retentionInDays = retentionInDays; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.logs.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class LogStream {
|
||||
|
||||
private String logGroupName;
|
||||
private String logStreamName;
|
||||
private long createdTime;
|
||||
private Long firstEventTimestamp;
|
||||
private Long lastEventTimestamp;
|
||||
private long lastIngestionTime;
|
||||
private String uploadSequenceToken;
|
||||
private long storedBytes;
|
||||
|
||||
public LogStream() {}
|
||||
|
||||
public String getLogGroupName() { return logGroupName; }
|
||||
public void setLogGroupName(String logGroupName) { this.logGroupName = logGroupName; }
|
||||
|
||||
public String getLogStreamName() { return logStreamName; }
|
||||
public void setLogStreamName(String logStreamName) { this.logStreamName = logStreamName; }
|
||||
|
||||
public long getCreatedTime() { return createdTime; }
|
||||
public void setCreatedTime(long createdTime) { this.createdTime = createdTime; }
|
||||
|
||||
public Long getFirstEventTimestamp() { return firstEventTimestamp; }
|
||||
public void setFirstEventTimestamp(Long firstEventTimestamp) { this.firstEventTimestamp = firstEventTimestamp; }
|
||||
|
||||
public Long getLastEventTimestamp() { return lastEventTimestamp; }
|
||||
public void setLastEventTimestamp(Long lastEventTimestamp) { this.lastEventTimestamp = lastEventTimestamp; }
|
||||
|
||||
public long getLastIngestionTime() { return lastIngestionTime; }
|
||||
public void setLastIngestionTime(long lastIngestionTime) { this.lastIngestionTime = lastIngestionTime; }
|
||||
|
||||
public String getUploadSequenceToken() { return uploadSequenceToken; }
|
||||
public void setUploadSequenceToken(String uploadSequenceToken) { this.uploadSequenceToken = uploadSequenceToken; }
|
||||
|
||||
public long getStoredBytes() { return storedBytes; }
|
||||
public void setStoredBytes(long storedBytes) { this.storedBytes = storedBytes; }
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Handles CloudWatch Metrics requests via the JSON 1.0 protocol.
|
||||
* AWS SDK v3 for CloudWatch uses X-Amz-Target: GraniteServiceVersion20100801.*
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CloudWatchMetricsJsonHandler {
|
||||
|
||||
private final CloudWatchMetricsService metricsService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public CloudWatchMetricsJsonHandler(CloudWatchMetricsService metricsService, ObjectMapper objectMapper) {
|
||||
this.metricsService = metricsService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
return switch (action) {
|
||||
case "PutMetricData" -> handlePutMetricData(request, region);
|
||||
case "ListMetrics" -> handleListMetrics(request, region);
|
||||
case "GetMetricStatistics" -> handleGetMetricStatistics(request, region);
|
||||
case "PutMetricAlarm" -> handlePutMetricAlarm(request, region);
|
||||
case "DescribeAlarms" -> handleDescribeAlarms(request, region);
|
||||
case "DeleteAlarms" -> handleDeleteAlarms(request, region);
|
||||
case "SetAlarmState" -> handleSetAlarmState(request, region);
|
||||
case "GetMetricData" -> Response.ok(objectMapper.createObjectNode().putArray("MetricDataResults")).build();
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
|
||||
.build();
|
||||
};
|
||||
}
|
||||
|
||||
private Response handlePutMetricData(JsonNode request, String region) {
|
||||
String namespace = request.path("Namespace").asText();
|
||||
List<MetricDatum> datums = parseMetricDataJson(request.path("MetricData"));
|
||||
metricsService.putMetricData(namespace, datums, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleListMetrics(JsonNode request, String region) {
|
||||
String namespace = request.has("Namespace") ? request.path("Namespace").asText() : null;
|
||||
String metricName = request.has("MetricName") ? request.path("MetricName").asText() : null;
|
||||
List<Dimension> dimensions = parseDimensionsJson(request.path("Dimensions"));
|
||||
|
||||
List<CloudWatchMetricsService.MetricIdentity> metrics =
|
||||
metricsService.listMetrics(namespace, metricName, dimensions, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode metricsArray = response.putArray("Metrics");
|
||||
for (var m : metrics) {
|
||||
ObjectNode mNode = metricsArray.addObject();
|
||||
mNode.put("Namespace", m.namespace());
|
||||
mNode.put("MetricName", m.metricName());
|
||||
ArrayNode dims = mNode.putArray("Dimensions");
|
||||
if (m.dimensions() != null) {
|
||||
for (Dimension d : m.dimensions()) {
|
||||
dims.addObject().put("Name", d.name()).put("Value", d.value());
|
||||
}
|
||||
}
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGetMetricStatistics(JsonNode request, String region) {
|
||||
String namespace = request.path("Namespace").asText();
|
||||
String metricName = request.path("MetricName").asText();
|
||||
List<Dimension> dimensions = parseDimensionsJson(request.path("Dimensions"));
|
||||
int period = request.path("Period").asInt(60);
|
||||
Instant startTime = parseInstant(request.path("StartTime").asText(null));
|
||||
Instant endTime = parseInstant(request.path("EndTime").asText(null));
|
||||
|
||||
List<String> statistics = new ArrayList<>();
|
||||
JsonNode statsNode = request.path("Statistics");
|
||||
if (statsNode.isArray()) {
|
||||
statsNode.forEach(s -> statistics.add(s.asText()));
|
||||
}
|
||||
|
||||
List<CloudWatchMetricsService.Datapoint> datapoints =
|
||||
metricsService.getMetricStatistics(namespace, metricName, dimensions,
|
||||
startTime, endTime, period, statistics, null, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Label", metricName);
|
||||
ArrayNode dps = response.putArray("Datapoints");
|
||||
for (var dp : datapoints) {
|
||||
ObjectNode dpNode = dps.addObject();
|
||||
dpNode.put("Timestamp", dp.timestamp().getEpochSecond());
|
||||
if (statistics.contains("Average")) dpNode.put("Average", dp.average());
|
||||
if (statistics.contains("Sum")) dpNode.put("Sum", dp.sum());
|
||||
if (statistics.contains("Minimum")) dpNode.put("Minimum", dp.minimum());
|
||||
if (statistics.contains("Maximum")) dpNode.put("Maximum", dp.maximum());
|
||||
if (statistics.contains("SampleCount")) dpNode.put("SampleCount", dp.sampleCount());
|
||||
dpNode.put("Unit", dp.unit());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handlePutMetricAlarm(JsonNode request, String region) {
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setAlarmName(request.path("AlarmName").asText());
|
||||
alarm.setAlarmDescription(request.path("AlarmDescription").asText(null));
|
||||
alarm.setMetricName(request.path("MetricName").asText(null));
|
||||
alarm.setNamespace(request.path("Namespace").asText(null));
|
||||
alarm.setStatistic(request.path("Statistic").asText(null));
|
||||
alarm.setPeriod(request.path("Period").asInt(60));
|
||||
alarm.setUnit(request.path("Unit").asText(null));
|
||||
alarm.setEvaluationPeriods(request.path("EvaluationPeriods").asInt(1));
|
||||
alarm.setDatapointsToAlarm(request.path("DatapointsToAlarm").asInt(alarm.getEvaluationPeriods()));
|
||||
alarm.setThreshold(request.path("Threshold").asDouble(0));
|
||||
alarm.setComparisonOperator(request.path("ComparisonOperator").asText(null));
|
||||
alarm.setTreatMissingData(request.path("TreatMissingData").asText(null));
|
||||
alarm.setActionsEnabled(request.path("ActionsEnabled").asBoolean(true));
|
||||
alarm.setDimensions(parseDimensionsJson(request.path("Dimensions")));
|
||||
|
||||
JsonNode alarmActions = request.path("AlarmActions");
|
||||
if (alarmActions.isArray()) {
|
||||
alarmActions.forEach(a -> alarm.getAlarmActions().add(a.asText()));
|
||||
}
|
||||
JsonNode okActions = request.path("OKActions");
|
||||
if (okActions.isArray()) {
|
||||
okActions.forEach(a -> alarm.getOkActions().add(a.asText()));
|
||||
}
|
||||
|
||||
metricsService.putMetricAlarm(alarm, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeAlarms(JsonNode request, String region) {
|
||||
List<String> alarmNames = new ArrayList<>();
|
||||
JsonNode namesNode = request.path("AlarmNames");
|
||||
if (namesNode.isArray()) {
|
||||
namesNode.forEach(n -> alarmNames.add(n.asText()));
|
||||
}
|
||||
String prefix = request.has("AlarmNamePrefix") ? request.path("AlarmNamePrefix").asText() : null;
|
||||
|
||||
List<MetricAlarm> alarms = metricsService.describeAlarms(alarmNames, prefix, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode arr = response.putArray("MetricAlarms");
|
||||
for (MetricAlarm a : alarms) {
|
||||
ObjectNode node = arr.addObject();
|
||||
node.put("AlarmName", a.getAlarmName());
|
||||
if (a.getAlarmArn() != null) node.put("AlarmArn", a.getAlarmArn());
|
||||
if (a.getAlarmDescription() != null) node.put("AlarmDescription", a.getAlarmDescription());
|
||||
if (a.getMetricName() != null) node.put("MetricName", a.getMetricName());
|
||||
if (a.getNamespace() != null) node.put("Namespace", a.getNamespace());
|
||||
if (a.getStatistic() != null) node.put("Statistic", a.getStatistic());
|
||||
node.put("Period", a.getPeriod());
|
||||
node.put("EvaluationPeriods", a.getEvaluationPeriods());
|
||||
node.put("Threshold", a.getThreshold());
|
||||
if (a.getComparisonOperator() != null) node.put("ComparisonOperator", a.getComparisonOperator());
|
||||
node.put("ActionsEnabled", a.isActionsEnabled());
|
||||
if (a.getStateValue() != null) node.put("StateValue", a.getStateValue());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteAlarms(JsonNode request, String region) {
|
||||
List<String> alarmNames = new ArrayList<>();
|
||||
JsonNode namesNode = request.path("AlarmNames");
|
||||
if (namesNode.isArray()) {
|
||||
namesNode.forEach(n -> alarmNames.add(n.asText()));
|
||||
}
|
||||
metricsService.deleteAlarms(alarmNames, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleSetAlarmState(JsonNode request, String region) {
|
||||
String name = request.path("AlarmName").asText();
|
||||
String state = request.path("StateValue").asText();
|
||||
String reason = request.path("StateReason").asText(null);
|
||||
String reasonData = request.path("StateReasonData").asText(null);
|
||||
metricsService.setAlarmState(name, state, reason, reasonData, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private List<MetricDatum> parseMetricDataJson(JsonNode node) {
|
||||
List<MetricDatum> datums = new ArrayList<>();
|
||||
if (!node.isArray()) return datums;
|
||||
for (JsonNode item : node) {
|
||||
MetricDatum datum = new MetricDatum();
|
||||
datum.setMetricName(item.path("MetricName").asText());
|
||||
datum.setValue(item.path("Value").asDouble(0));
|
||||
datum.setUnit(item.path("Unit").asText(null));
|
||||
JsonNode ts = item.path("Timestamp");
|
||||
if (!ts.isMissingNode()) {
|
||||
Instant parsed = parseInstant(ts.asText(null));
|
||||
if (parsed != null) datum.setTimestamp(parsed.getEpochSecond());
|
||||
}
|
||||
datum.setDimensions(parseDimensionsJson(item.path("Dimensions")));
|
||||
datums.add(datum);
|
||||
}
|
||||
return datums;
|
||||
}
|
||||
|
||||
private List<Dimension> parseDimensionsJson(JsonNode node) {
|
||||
List<Dimension> dims = new ArrayList<>();
|
||||
if (!node.isArray()) return dims;
|
||||
for (JsonNode d : node) {
|
||||
dims.add(new Dimension(d.path("Name").asText(), d.path("Value").asText()));
|
||||
}
|
||||
return dims;
|
||||
}
|
||||
|
||||
private Instant parseInstant(String value) {
|
||||
if (value == null || value.isBlank()) return null;
|
||||
try {
|
||||
return Instant.parse(value);
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
return Instant.ofEpochSecond(Long.parseLong(value));
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+375
@@ -0,0 +1,375 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CloudWatchMetricsQueryHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchMetricsQueryHandler.class);
|
||||
|
||||
private CloudWatchMetricsService metricsService;
|
||||
|
||||
@Inject
|
||||
public CloudWatchMetricsQueryHandler(CloudWatchMetricsService metricsService) {
|
||||
this.metricsService = metricsService;
|
||||
}
|
||||
|
||||
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
|
||||
LOG.debugv("CloudWatch Metrics action: {0}", action);
|
||||
return switch (action) {
|
||||
case "PutMetricData" -> handlePutMetricData(params, region);
|
||||
case "ListMetrics" -> handleListMetrics(params, region);
|
||||
case "GetMetricStatistics" -> handleGetMetricStatistics(params, region);
|
||||
case "GetMetricData" -> handleGetMetricDataStub(params);
|
||||
case "PutMetricAlarm" -> handlePutMetricAlarm(params, region);
|
||||
case "DescribeAlarms" -> handleDescribeAlarms(params, region);
|
||||
case "DeleteAlarms" -> handleDeleteAlarms(params, region);
|
||||
case "SetAlarmState" -> handleSetAlarmState(params, region);
|
||||
default -> AwsQueryResponse.error("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported by CloudWatch.", AwsNamespaces.CW, 400);
|
||||
};
|
||||
}
|
||||
|
||||
private Response handlePutMetricData(MultivaluedMap<String, String> params, String region) {
|
||||
String namespace = params.getFirst("Namespace");
|
||||
List<MetricDatum> datums = parseMetricData(params);
|
||||
metricsService.putMetricData(namespace, datums, region);
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("PutMetricData", null)).build();
|
||||
}
|
||||
|
||||
private Response handleListMetrics(MultivaluedMap<String, String> params, String region) {
|
||||
String namespace = params.getFirst("Namespace");
|
||||
String metricName = params.getFirst("MetricName");
|
||||
List<Dimension> dimensions = parseDimensionFilters(params);
|
||||
|
||||
List<CloudWatchMetricsService.MetricIdentity> metrics =
|
||||
metricsService.listMetrics(namespace, metricName, dimensions, region);
|
||||
|
||||
var xml = new XmlBuilder().start("Metrics");
|
||||
for (var m : metrics) {
|
||||
var member = xml.start("member")
|
||||
.elem("Namespace", m.namespace())
|
||||
.elem("MetricName", m.metricName())
|
||||
.start("Dimensions");
|
||||
for (Dimension d : m.dimensions()) {
|
||||
xml.start("member")
|
||||
.elem("Name", d.name())
|
||||
.elem("Value", d.value())
|
||||
.end("member");
|
||||
}
|
||||
xml.end("Dimensions").end("member");
|
||||
}
|
||||
xml.end("Metrics");
|
||||
return Response.ok(AwsQueryResponse.envelope("ListMetrics", null, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleGetMetricStatistics(MultivaluedMap<String, String> params, String region) {
|
||||
String namespace = params.getFirst("Namespace");
|
||||
String metricName = params.getFirst("MetricName");
|
||||
List<Dimension> dimensions = parseDimensionFilters(params);
|
||||
int period = parseIntParam(params, "Period", 60);
|
||||
String unit = params.getFirst("Unit");
|
||||
|
||||
Instant startTime = parseInstant(params.getFirst("StartTime"));
|
||||
Instant endTime = parseInstant(params.getFirst("EndTime"));
|
||||
|
||||
List<String> statistics = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String stat = params.getFirst("Statistics.member." + i);
|
||||
if (stat == null) {
|
||||
break;
|
||||
}
|
||||
statistics.add(stat);
|
||||
}
|
||||
|
||||
List<CloudWatchMetricsService.Datapoint> datapoints =
|
||||
metricsService.getMetricStatistics(namespace, metricName, dimensions,
|
||||
startTime, endTime, period, statistics, unit, region);
|
||||
|
||||
DateTimeFormatter fmt = DateTimeFormatter.ISO_INSTANT;
|
||||
var xml = new XmlBuilder()
|
||||
.elem("Label", metricName)
|
||||
.start("Datapoints");
|
||||
for (var dp : datapoints) {
|
||||
xml.start("member").elem("Timestamp", fmt.format(dp.timestamp()));
|
||||
if (statistics.contains("Average")) {
|
||||
xml.elem("Average", String.valueOf(dp.average()));
|
||||
}
|
||||
if (statistics.contains("Sum")) {
|
||||
xml.elem("Sum", String.valueOf(dp.sum()));
|
||||
}
|
||||
if (statistics.contains("Minimum")) {
|
||||
xml.elem("Minimum", String.valueOf(dp.minimum()));
|
||||
}
|
||||
if (statistics.contains("Maximum")) {
|
||||
xml.elem("Maximum", String.valueOf(dp.maximum()));
|
||||
}
|
||||
if (statistics.contains("SampleCount")) {
|
||||
xml.elem("SampleCount", String.valueOf(dp.sampleCount()));
|
||||
}
|
||||
xml.elem("Unit", dp.unit()).end("member");
|
||||
}
|
||||
xml.end("Datapoints");
|
||||
return Response.ok(AwsQueryResponse.envelope("GetMetricStatistics", null, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleGetMetricDataStub(MultivaluedMap<String, String> params) {
|
||||
String result = new XmlBuilder().start("MetricDataResults").end("MetricDataResults").build();
|
||||
return Response.ok(AwsQueryResponse.envelope("GetMetricData", null, result)).build();
|
||||
}
|
||||
|
||||
private Response handlePutMetricAlarm(MultivaluedMap<String, String> params, String region) {
|
||||
MetricAlarm alarm = parseAlarm(params);
|
||||
metricsService.putMetricAlarm(alarm, region);
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("PutMetricAlarm", null)).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeAlarms(MultivaluedMap<String, String> params, String region) {
|
||||
List<String> alarmNames = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String name = params.getFirst("AlarmNames.member." + i);
|
||||
if (name == null) break;
|
||||
alarmNames.add(name);
|
||||
}
|
||||
String prefix = params.getFirst("AlarmNamePrefix");
|
||||
|
||||
List<MetricAlarm> alarms = metricsService.describeAlarms(alarmNames, prefix, region);
|
||||
|
||||
var xml = new XmlBuilder().start("MetricAlarms");
|
||||
for (MetricAlarm a : alarms) {
|
||||
toAlarmXml(xml, a);
|
||||
}
|
||||
xml.end("MetricAlarms");
|
||||
return Response.ok(AwsQueryResponse.envelope("DescribeAlarms", null, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteAlarms(MultivaluedMap<String, String> params, String region) {
|
||||
List<String> alarmNames = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String name = params.getFirst("AlarmNames.member." + i);
|
||||
if (name == null) break;
|
||||
alarmNames.add(name);
|
||||
}
|
||||
metricsService.deleteAlarms(alarmNames, region);
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteAlarms", null)).build();
|
||||
}
|
||||
|
||||
private Response handleSetAlarmState(MultivaluedMap<String, String> params, String region) {
|
||||
String name = params.getFirst("AlarmName");
|
||||
String state = params.getFirst("StateValue");
|
||||
String reason = params.getFirst("StateReason");
|
||||
String reasonData = params.getFirst("StateReasonData");
|
||||
metricsService.setAlarmState(name, state, reason, reasonData, region);
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("SetAlarmState", null)).build();
|
||||
}
|
||||
|
||||
// ──────────────────────────── Parsing Helpers ────────────────────────────
|
||||
|
||||
private List<MetricDatum> parseMetricData(MultivaluedMap<String, String> params) {
|
||||
List<MetricDatum> datums = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String metricName = params.getFirst("MetricData.member." + i + ".MetricName");
|
||||
if (metricName == null) {
|
||||
break;
|
||||
}
|
||||
MetricDatum datum = new MetricDatum();
|
||||
datum.setMetricName(metricName);
|
||||
datum.setUnit(params.getFirst("MetricData.member." + i + ".Unit"));
|
||||
|
||||
String valueStr = params.getFirst("MetricData.member." + i + ".Value");
|
||||
if (valueStr != null) {
|
||||
datum.setValue(parseDouble(valueStr, 0));
|
||||
}
|
||||
|
||||
String tsStr = params.getFirst("MetricData.member." + i + ".Timestamp");
|
||||
if (tsStr != null) {
|
||||
Instant ts = parseInstant(tsStr);
|
||||
datum.setTimestamp(ts != null ? ts.getEpochSecond() : 0);
|
||||
}
|
||||
|
||||
// StatisticValues
|
||||
String sc = params.getFirst("MetricData.member." + i + ".StatisticValues.SampleCount");
|
||||
if (sc != null) {
|
||||
datum.setSampleCount(parseDouble(sc, 0));
|
||||
datum.setSum(parseDouble(params.getFirst("MetricData.member." + i + ".StatisticValues.Sum"), 0));
|
||||
datum.setMinimum(parseDouble(params.getFirst("MetricData.member." + i + ".StatisticValues.Minimum"), 0));
|
||||
datum.setMaximum(parseDouble(params.getFirst("MetricData.member." + i + ".StatisticValues.Maximum"), 0));
|
||||
}
|
||||
|
||||
// Dimensions
|
||||
List<Dimension> dims = new ArrayList<>();
|
||||
for (int j = 1; ; j++) {
|
||||
String dimName = params.getFirst("MetricData.member." + i + ".Dimensions.member." + j + ".Name");
|
||||
String dimValue = params.getFirst("MetricData.member." + i + ".Dimensions.member." + j + ".Value");
|
||||
if (dimName == null) {
|
||||
break;
|
||||
}
|
||||
dims.add(new Dimension(dimName, dimValue));
|
||||
}
|
||||
datum.setDimensions(dims);
|
||||
|
||||
datums.add(datum);
|
||||
}
|
||||
return datums;
|
||||
}
|
||||
|
||||
private List<Dimension> parseDimensionFilters(MultivaluedMap<String, String> params) {
|
||||
List<Dimension> dims = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String name = params.getFirst("Dimensions.member." + i + ".Name");
|
||||
String value = params.getFirst("Dimensions.member." + i + ".Value");
|
||||
if (name == null) {
|
||||
break;
|
||||
}
|
||||
dims.add(new Dimension(name, value));
|
||||
}
|
||||
return dims;
|
||||
}
|
||||
|
||||
private MetricAlarm parseAlarm(MultivaluedMap<String, String> params) {
|
||||
MetricAlarm a = new MetricAlarm();
|
||||
a.setAlarmName(params.getFirst("AlarmName"));
|
||||
a.setAlarmDescription(params.getFirst("AlarmDescription"));
|
||||
a.setActionsEnabled(Boolean.parseBoolean(params.getFirst("ActionsEnabled")));
|
||||
a.setMetricName(params.getFirst("MetricName"));
|
||||
a.setNamespace(params.getFirst("Namespace"));
|
||||
a.setStatistic(params.getFirst("Statistic"));
|
||||
a.setPeriod(parseIntParam(params, "Period", 60));
|
||||
a.setUnit(params.getFirst("Unit"));
|
||||
a.setEvaluationPeriods(parseIntParam(params, "EvaluationPeriods", 1));
|
||||
a.setDatapointsToAlarm(parseIntParam(params, "DatapointsToAlarm", a.getEvaluationPeriods()));
|
||||
a.setThreshold(parseDouble(params.getFirst("Threshold"), 0));
|
||||
a.setComparisonOperator(params.getFirst("ComparisonOperator"));
|
||||
a.setTreatMissingData(params.getFirst("TreatMissingData"));
|
||||
|
||||
// Dimensions
|
||||
List<Dimension> dims = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String name = params.getFirst("Dimensions.member." + i + ".Name");
|
||||
String value = params.getFirst("Dimensions.member." + i + ".Value");
|
||||
if (name == null) break;
|
||||
dims.add(new Dimension(name, value));
|
||||
}
|
||||
a.setDimensions(dims);
|
||||
|
||||
// Actions
|
||||
for (int i = 1; ; i++) {
|
||||
String act = params.getFirst("OKActions.member." + i);
|
||||
if (act == null) break;
|
||||
a.getOkActions().add(act);
|
||||
}
|
||||
for (int i = 1; ; i++) {
|
||||
String act = params.getFirst("AlarmActions.member." + i);
|
||||
if (act == null) break;
|
||||
a.getAlarmActions().add(act);
|
||||
}
|
||||
for (int i = 1; ; i++) {
|
||||
String act = params.getFirst("InsufficientDataActions.member." + i);
|
||||
if (act == null) break;
|
||||
a.getInsufficientDataActions().add(act);
|
||||
}
|
||||
|
||||
return a;
|
||||
}
|
||||
|
||||
private void toAlarmXml(XmlBuilder xml, MetricAlarm a) {
|
||||
xml.start("member")
|
||||
.elem("AlarmName", a.getAlarmName())
|
||||
.elem("AlarmArn", a.getAlarmArn())
|
||||
.elem("AlarmDescription", a.getAlarmDescription())
|
||||
.elem("AlarmConfigurationUpdatedTimestamp", Instant.ofEpochSecond(a.getAlarmConfigurationUpdatedTimestamp()).toString())
|
||||
.elem("ActionsEnabled", String.valueOf(a.isActionsEnabled()))
|
||||
.elem("StateValue", a.getStateValue())
|
||||
.elem("StateReason", a.getStateReason())
|
||||
.elem("StateReasonData", a.getStateReasonData())
|
||||
.elem("StateUpdatedTimestamp", Instant.ofEpochSecond(a.getStateUpdatedTimestamp()).toString())
|
||||
.elem("MetricName", a.getMetricName())
|
||||
.elem("Namespace", a.getNamespace())
|
||||
.elem("Statistic", a.getStatistic())
|
||||
.elem("Period", String.valueOf(a.getPeriod()))
|
||||
.elem("Unit", a.getUnit())
|
||||
.elem("EvaluationPeriods", String.valueOf(a.getEvaluationPeriods()))
|
||||
.elem("DatapointsToAlarm", String.valueOf(a.getDatapointsToAlarm()))
|
||||
.elem("Threshold", String.valueOf(a.getThreshold()))
|
||||
.elem("ComparisonOperator", a.getComparisonOperator())
|
||||
.elem("TreatMissingData", a.getTreatMissingData());
|
||||
|
||||
if (!a.getOkActions().isEmpty()) {
|
||||
xml.start("OKActions");
|
||||
a.getOkActions().forEach(act -> xml.elem("member", act));
|
||||
xml.end("OKActions");
|
||||
}
|
||||
if (!a.getAlarmActions().isEmpty()) {
|
||||
xml.start("AlarmActions");
|
||||
a.getAlarmActions().forEach(act -> xml.elem("member", act));
|
||||
xml.end("AlarmActions");
|
||||
}
|
||||
if (!a.getInsufficientDataActions().isEmpty()) {
|
||||
xml.start("InsufficientDataActions");
|
||||
a.getInsufficientDataActions().forEach(act -> xml.elem("member", act));
|
||||
xml.end("InsufficientDataActions");
|
||||
}
|
||||
|
||||
if (!a.getDimensions().isEmpty()) {
|
||||
xml.start("Dimensions");
|
||||
for (Dimension d : a.getDimensions()) {
|
||||
xml.start("member").elem("Name", d.name()).elem("Value", d.value()).end("member");
|
||||
}
|
||||
xml.end("Dimensions");
|
||||
}
|
||||
xml.end("member");
|
||||
}
|
||||
|
||||
private Instant parseInstant(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Instant.parse(value);
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
return Instant.ofEpochSecond(Long.parseLong(value));
|
||||
} catch (Exception ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int parseIntParam(MultivaluedMap<String, String> params, String name, int defaultValue) {
|
||||
String value = params.getFirst(name);
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(value);
|
||||
} catch (NumberFormatException e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
private double parseDouble(String value, double defaultValue) {
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
try {
|
||||
return Double.parseDouble(value);
|
||||
} catch (NumberFormatException e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CloudWatchMetricsService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchMetricsService.class);
|
||||
|
||||
private final StorageBackend<String, MetricDatum> metricStore;
|
||||
private final StorageBackend<String, MetricAlarm> alarmStore;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public CloudWatchMetricsService(StorageFactory storageFactory, RegionResolver regionResolver) {
|
||||
this.metricStore = storageFactory.create("cloudwatchmetrics", "cwmetrics.json",
|
||||
new TypeReference<Map<String, MetricDatum>>() {});
|
||||
this.alarmStore = storageFactory.create("cloudwatchmetrics", "cwalarms.json",
|
||||
new TypeReference<Map<String, MetricAlarm>>() {});
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
CloudWatchMetricsService(StorageBackend<String, MetricDatum> metricStore,
|
||||
StorageBackend<String, MetricAlarm> alarmStore,
|
||||
RegionResolver regionResolver) {
|
||||
this.metricStore = metricStore;
|
||||
this.alarmStore = alarmStore;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
public void putMetricData(String namespace, List<MetricDatum> datums, String region) {
|
||||
long nowSeconds = Instant.now().getEpochSecond();
|
||||
for (MetricDatum datum : datums) {
|
||||
datum.setNamespace(namespace);
|
||||
if (datum.getTimestamp() == 0) {
|
||||
datum.setTimestamp(nowSeconds);
|
||||
}
|
||||
// Synthesize StatisticValues if only a scalar value was provided
|
||||
if (datum.getSampleCount() == 0 && datum.getSum() == 0) {
|
||||
datum.setSampleCount(1);
|
||||
datum.setSum(datum.getValue());
|
||||
datum.setMinimum(datum.getValue());
|
||||
datum.setMaximum(datum.getValue());
|
||||
}
|
||||
|
||||
String dimKey = buildDimKey(datum.getDimensions());
|
||||
String key = region + "::" + namespace + "::" + datum.getMetricName()
|
||||
+ "::" + dimKey + "::"
|
||||
+ String.format("%013d", datum.getTimestamp()) + "::" + UUID.randomUUID();
|
||||
metricStore.put(key, datum);
|
||||
}
|
||||
LOG.debugv("PutMetricData: {0} datums for namespace {1}", datums.size(), namespace);
|
||||
}
|
||||
|
||||
public record MetricIdentity(String namespace, String metricName, List<Dimension> dimensions) {}
|
||||
|
||||
public List<MetricIdentity> listMetrics(String namespace, String metricName,
|
||||
List<Dimension> dimensions, String region) {
|
||||
String prefix = region + "::";
|
||||
if (namespace != null && !namespace.isBlank()) {
|
||||
prefix += namespace + "::";
|
||||
}
|
||||
|
||||
final String finalPrefix = prefix;
|
||||
List<MetricDatum> all = metricStore.scan(k -> k.startsWith(finalPrefix));
|
||||
|
||||
// De-duplicate by (namespace, metricName, dimKey)
|
||||
Map<String, MetricIdentity> deduped = new LinkedHashMap<>();
|
||||
for (MetricDatum d : all) {
|
||||
if (metricName != null && !metricName.isBlank() && !metricName.equals(d.getMetricName())) {
|
||||
continue;
|
||||
}
|
||||
if (dimensions != null && !dimensions.isEmpty() && !matchesDimensions(d.getDimensions(), dimensions)) {
|
||||
continue;
|
||||
}
|
||||
String identity = d.getNamespace() + "::" + d.getMetricName() + "::" + buildDimKey(d.getDimensions());
|
||||
deduped.putIfAbsent(identity, new MetricIdentity(d.getNamespace(), d.getMetricName(), d.getDimensions()));
|
||||
}
|
||||
return new ArrayList<>(deduped.values());
|
||||
}
|
||||
|
||||
public record Datapoint(Instant timestamp, double sampleCount, double sum,
|
||||
double average, double minimum, double maximum, String unit) {}
|
||||
|
||||
public List<Datapoint> getMetricStatistics(String namespace, String metricName,
|
||||
List<Dimension> dimensions,
|
||||
Instant startTime, Instant endTime,
|
||||
int periodSeconds,
|
||||
List<String> statistics,
|
||||
String unit, String region) {
|
||||
String dimKey = dimensions != null ? buildDimKey(dimensions) : "";
|
||||
String prefix = region + "::" + namespace + "::" + metricName + "::" + dimKey + "::";
|
||||
|
||||
long startEpoch = startTime != null ? startTime.getEpochSecond() : 0;
|
||||
long endEpoch = endTime != null ? endTime.getEpochSecond() : Long.MAX_VALUE;
|
||||
|
||||
List<MetricDatum> matching = metricStore.scan(k -> {
|
||||
if (!k.startsWith(prefix)) return false;
|
||||
// Extract timestamp from key segment
|
||||
String[] parts = k.split("::");
|
||||
if (parts.length < 6) return false;
|
||||
try {
|
||||
long ts = Long.parseLong(parts[parts.length - 2]);
|
||||
return ts >= startEpoch && ts <= endEpoch;
|
||||
} catch (NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
if (unit != null && !unit.isBlank() && !"None".equals(unit)) {
|
||||
matching = matching.stream()
|
||||
.filter(d -> unit.equals(d.getUnit()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
// Group by period bucket
|
||||
Map<Long, List<MetricDatum>> buckets = new LinkedHashMap<>();
|
||||
for (MetricDatum d : matching) {
|
||||
long bucket = (d.getTimestamp() / periodSeconds) * periodSeconds;
|
||||
buckets.computeIfAbsent(bucket, k -> new ArrayList<>()).add(d);
|
||||
}
|
||||
|
||||
List<Datapoint> result = new ArrayList<>();
|
||||
for (Map.Entry<Long, List<MetricDatum>> entry : buckets.entrySet()) {
|
||||
List<MetricDatum> group = entry.getValue();
|
||||
double sc = group.stream().mapToDouble(MetricDatum::getSampleCount).sum();
|
||||
double sum = group.stream().mapToDouble(MetricDatum::getSum).sum();
|
||||
double min = group.stream().mapToDouble(MetricDatum::getMinimum).min().orElse(0);
|
||||
double max = group.stream().mapToDouble(MetricDatum::getMaximum).max().orElse(0);
|
||||
double avg = sc > 0 ? sum / sc : 0;
|
||||
String resolvedUnit = group.stream()
|
||||
.map(MetricDatum::getUnit)
|
||||
.filter(u -> u != null && !u.isBlank())
|
||||
.findFirst().orElse("None");
|
||||
result.add(new Datapoint(
|
||||
Instant.ofEpochSecond(entry.getKey()),
|
||||
sc, sum, avg, min, max, resolvedUnit
|
||||
));
|
||||
}
|
||||
result.sort(Comparator.comparing(Datapoint::timestamp));
|
||||
return result;
|
||||
}
|
||||
|
||||
public void putMetricAlarm(MetricAlarm alarm, String region) {
|
||||
if (alarm.getAlarmArn() == null) {
|
||||
alarm.setAlarmArn(regionResolver.buildArn("cloudwatch", region, "alarm:" + alarm.getAlarmName()));
|
||||
}
|
||||
alarm.setAlarmConfigurationUpdatedTimestamp(Instant.now().getEpochSecond());
|
||||
alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);
|
||||
LOG.infov("PutMetricAlarm: {0} in {1}", alarm.getAlarmName(), region);
|
||||
}
|
||||
|
||||
public List<MetricAlarm> describeAlarms(List<String> alarmNames, String alarmNamePrefix, String region) {
|
||||
String prefix = region + "::";
|
||||
List<MetricAlarm> all = alarmStore.scan(k -> k.startsWith(prefix));
|
||||
|
||||
if (alarmNames != null && !alarmNames.isEmpty()) {
|
||||
return all.stream().filter(a -> alarmNames.contains(a.getAlarmName())).toList();
|
||||
}
|
||||
if (alarmNamePrefix != null && !alarmNamePrefix.isBlank()) {
|
||||
return all.stream().filter(a -> a.getAlarmName().startsWith(alarmNamePrefix)).toList();
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
public void deleteAlarms(List<String> alarmNames, String region) {
|
||||
for (String name : alarmNames) {
|
||||
alarmStore.delete(region + "::" + name);
|
||||
}
|
||||
LOG.infov("Deleted alarms: {0} in {1}", alarmNames, region);
|
||||
}
|
||||
|
||||
public void setAlarmState(String alarmName, String stateValue, String stateReason, String stateReasonData, String region) {
|
||||
String key = region + "::" + alarmName;
|
||||
MetricAlarm alarm = alarmStore.get(key)
|
||||
.orElseThrow(() -> new RuntimeException("Alarm not found: " + alarmName));
|
||||
|
||||
alarm.setStateValue(stateValue);
|
||||
alarm.setStateReason(stateReason);
|
||||
alarm.setStateReasonData(stateReasonData);
|
||||
alarm.setStateUpdatedTimestamp(Instant.now().getEpochSecond());
|
||||
|
||||
alarmStore.put(key, alarm);
|
||||
LOG.infov("SetAlarmState: {0} -> {1}", alarmName, stateValue);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Helpers ────────────────────────────
|
||||
|
||||
static String buildDimKey(List<Dimension> dimensions) {
|
||||
if (dimensions == null || dimensions.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
return dimensions.stream()
|
||||
.sorted(Comparator.comparing(Dimension::name))
|
||||
.map(d -> d.name() + "=" + d.value())
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
private boolean matchesDimensions(List<Dimension> actual, List<Dimension> required) {
|
||||
String requiredKey = buildDimKey(required);
|
||||
String actualKey = buildDimKey(actual);
|
||||
return actualKey.contains(requiredKey);
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record Dimension(String name, String value) {}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class MetricAlarm {
|
||||
private String alarmName;
|
||||
private String alarmArn;
|
||||
private String alarmDescription;
|
||||
private long alarmConfigurationUpdatedTimestamp;
|
||||
private boolean actionsEnabled;
|
||||
private List<String> okActions = new ArrayList<>();
|
||||
private List<String> alarmActions = new ArrayList<>();
|
||||
private List<String> insufficientDataActions = new ArrayList<>();
|
||||
private String stateValue = "INSUFFICIENT_DATA";
|
||||
private String stateReason = "Unchecked";
|
||||
private String stateReasonData;
|
||||
private long stateUpdatedTimestamp;
|
||||
private String metricName;
|
||||
private String namespace;
|
||||
private String statistic;
|
||||
private List<Dimension> dimensions = new ArrayList<>();
|
||||
private int period;
|
||||
private String unit;
|
||||
private int evaluationPeriods;
|
||||
private int datapointsToAlarm;
|
||||
private double threshold;
|
||||
private String comparisonOperator;
|
||||
private String treatMissingData = "missing";
|
||||
private String evaluateLowSampleCountPercentile;
|
||||
|
||||
public MetricAlarm() {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
this.alarmConfigurationUpdatedTimestamp = now;
|
||||
this.stateUpdatedTimestamp = now;
|
||||
}
|
||||
|
||||
public String getAlarmName() { return alarmName; }
|
||||
public void setAlarmName(String alarmName) { this.alarmName = alarmName; }
|
||||
|
||||
public String getAlarmArn() { return alarmArn; }
|
||||
public void setAlarmArn(String alarmArn) { this.alarmArn = alarmArn; }
|
||||
|
||||
public String getAlarmDescription() { return alarmDescription; }
|
||||
public void setAlarmDescription(String alarmDescription) { this.alarmDescription = alarmDescription; }
|
||||
|
||||
public long getAlarmConfigurationUpdatedTimestamp() { return alarmConfigurationUpdatedTimestamp; }
|
||||
public void setAlarmConfigurationUpdatedTimestamp(long timestamp) { this.alarmConfigurationUpdatedTimestamp = timestamp; }
|
||||
|
||||
public boolean isActionsEnabled() { return actionsEnabled; }
|
||||
public void setActionsEnabled(boolean actionsEnabled) { this.actionsEnabled = actionsEnabled; }
|
||||
|
||||
public List<String> getOkActions() { return okActions; }
|
||||
public void setOkActions(List<String> okActions) { this.okActions = okActions; }
|
||||
|
||||
public List<String> getAlarmActions() { return alarmActions; }
|
||||
public void setAlarmActions(List<String> alarmActions) { this.alarmActions = alarmActions; }
|
||||
|
||||
public List<String> getInsufficientDataActions() { return insufficientDataActions; }
|
||||
public void setInsufficientDataActions(List<String> insufficientDataActions) { this.insufficientDataActions = insufficientDataActions; }
|
||||
|
||||
public String getStateValue() { return stateValue; }
|
||||
public void setStateValue(String stateValue) { this.stateValue = stateValue; }
|
||||
|
||||
public String getStateReason() { return stateReason; }
|
||||
public void setStateReason(String stateReason) { this.stateReason = stateReason; }
|
||||
|
||||
public String getStateReasonData() { return stateReasonData; }
|
||||
public void setStateReasonData(String stateReasonData) { this.stateReasonData = stateReasonData; }
|
||||
|
||||
public long getStateUpdatedTimestamp() { return stateUpdatedTimestamp; }
|
||||
public void setStateUpdatedTimestamp(long stateUpdatedTimestamp) { this.stateUpdatedTimestamp = stateUpdatedTimestamp; }
|
||||
|
||||
public String getMetricName() { return metricName; }
|
||||
public void setMetricName(String metricName) { this.metricName = metricName; }
|
||||
|
||||
public String getNamespace() { return namespace; }
|
||||
public void setNamespace(String namespace) { this.namespace = namespace; }
|
||||
|
||||
public String getStatistic() { return statistic; }
|
||||
public void setStatistic(String statistic) { this.statistic = statistic; }
|
||||
|
||||
public List<Dimension> getDimensions() { return dimensions; }
|
||||
public void setDimensions(List<Dimension> dimensions) { this.dimensions = dimensions; }
|
||||
|
||||
public int getPeriod() { return period; }
|
||||
public void setPeriod(int period) { this.period = period; }
|
||||
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String unit) { this.unit = unit; }
|
||||
|
||||
public int getEvaluationPeriods() { return evaluationPeriods; }
|
||||
public void setEvaluationPeriods(int evaluationPeriods) { this.evaluationPeriods = evaluationPeriods; }
|
||||
|
||||
public int getDatapointsToAlarm() { return datapointsToAlarm; }
|
||||
public void setDatapointsToAlarm(int datapointsToAlarm) { this.datapointsToAlarm = datapointsToAlarm; }
|
||||
|
||||
public double getThreshold() { return threshold; }
|
||||
public void setThreshold(double threshold) { this.threshold = threshold; }
|
||||
|
||||
public String getComparisonOperator() { return comparisonOperator; }
|
||||
public void setComparisonOperator(String comparisonOperator) { this.comparisonOperator = comparisonOperator; }
|
||||
|
||||
public String getTreatMissingData() { return treatMissingData; }
|
||||
public void setTreatMissingData(String treatMissingData) { this.treatMissingData = treatMissingData; }
|
||||
|
||||
public String getEvaluateLowSampleCountPercentile() { return evaluateLowSampleCountPercentile; }
|
||||
public void setEvaluateLowSampleCountPercentile(String percentile) { this.evaluateLowSampleCountPercentile = percentile; }
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class MetricDatum {
|
||||
|
||||
private String namespace;
|
||||
private String metricName;
|
||||
private List<Dimension> dimensions = new ArrayList<>();
|
||||
private long timestamp;
|
||||
private double value;
|
||||
private double sampleCount;
|
||||
private double sum;
|
||||
private double minimum;
|
||||
private double maximum;
|
||||
private String unit;
|
||||
|
||||
public MetricDatum() {}
|
||||
|
||||
public String getNamespace() { return namespace; }
|
||||
public void setNamespace(String namespace) { this.namespace = namespace; }
|
||||
|
||||
public String getMetricName() { return metricName; }
|
||||
public void setMetricName(String metricName) { this.metricName = metricName; }
|
||||
|
||||
public List<Dimension> getDimensions() { return dimensions; }
|
||||
public void setDimensions(List<Dimension> dimensions) { this.dimensions = dimensions; }
|
||||
|
||||
public long getTimestamp() { return timestamp; }
|
||||
public void setTimestamp(long timestamp) { this.timestamp = timestamp; }
|
||||
|
||||
public double getValue() { return value; }
|
||||
public void setValue(double value) { this.value = value; }
|
||||
|
||||
public double getSampleCount() { return sampleCount; }
|
||||
public void setSampleCount(double sampleCount) { this.sampleCount = sampleCount; }
|
||||
|
||||
public double getSum() { return sum; }
|
||||
public void setSum(double sum) { this.sum = sum; }
|
||||
|
||||
public double getMinimum() { return minimum; }
|
||||
public void setMinimum(double minimum) { this.minimum = minimum; }
|
||||
|
||||
public double getMaximum() { return maximum; }
|
||||
public void setMaximum(double maximum) { this.maximum = maximum; }
|
||||
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String unit) { this.unit = unit; }
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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.services.cognito.model.CognitoUser;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPool;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CognitoJsonHandler {
|
||||
|
||||
private final CognitoService service;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public CognitoJsonHandler(CognitoService service, ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
return switch (action) {
|
||||
case "CreateUserPool" -> handleCreateUserPool(request, region);
|
||||
case "DescribeUserPool" -> handleDescribeUserPool(request);
|
||||
case "ListUserPools" -> handleListUserPools(request);
|
||||
case "DeleteUserPool" -> handleDeleteUserPool(request);
|
||||
case "CreateUserPoolClient" -> handleCreateUserPoolClient(request);
|
||||
case "DescribeUserPoolClient" -> handleDescribeUserPoolClient(request);
|
||||
case "ListUserPoolClients" -> handleListUserPoolClients(request);
|
||||
case "DeleteUserPoolClient" -> handleDeleteUserPoolClient(request);
|
||||
case "AdminCreateUser" -> handleAdminCreateUser(request);
|
||||
case "AdminGetUser" -> handleAdminGetUser(request);
|
||||
case "AdminDeleteUser" -> handleAdminDeleteUser(request);
|
||||
case "AdminSetUserPassword" -> handleAdminSetUserPassword(request);
|
||||
case "AdminUpdateUserAttributes" -> handleAdminUpdateUserAttributes(request);
|
||||
case "ListUsers" -> handleListUsers(request);
|
||||
case "InitiateAuth" -> handleInitiateAuth(request);
|
||||
case "AdminInitiateAuth" -> handleAdminInitiateAuth(request);
|
||||
case "RespondToAuthChallenge" -> handleRespondToAuthChallenge(request);
|
||||
case "SignUp" -> handleSignUp(request);
|
||||
case "ConfirmSignUp" -> handleConfirmSignUp(request);
|
||||
case "ChangePassword" -> handleChangePassword(request);
|
||||
case "ForgotPassword" -> handleForgotPassword(request);
|
||||
case "ConfirmForgotPassword" -> handleConfirmForgotPassword(request);
|
||||
case "GetUser" -> handleGetUser(request);
|
||||
case "UpdateUserAttributes" -> handleUpdateUserAttributes(request);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnsupportedOperation", "Operation " + action + " is not supported."))
|
||||
.build();
|
||||
};
|
||||
}
|
||||
|
||||
private Response handleCreateUserPool(JsonNode request, String region) {
|
||||
String poolName = request.path("PoolName").asText();
|
||||
UserPool pool = service.createUserPool(poolName, region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("UserPool", userPoolToNode(pool));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeUserPool(JsonNode request) {
|
||||
UserPool pool = service.describeUserPool(request.path("UserPoolId").asText());
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("UserPool", userPoolToNode(pool));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleListUserPools(JsonNode request) {
|
||||
List<UserPool> pools = service.listUserPools();
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode items = response.putArray("UserPools");
|
||||
pools.forEach(p -> items.add(userPoolToNode(p)));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteUserPool(JsonNode request) {
|
||||
service.deleteUserPool(request.path("UserPoolId").asText());
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleCreateUserPoolClient(JsonNode request) {
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
request.path("UserPoolId").asText(),
|
||||
request.path("ClientName").asText()
|
||||
);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("UserPoolClient", clientToNode(client));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeUserPoolClient(JsonNode request) {
|
||||
UserPoolClient client = service.describeUserPoolClient(
|
||||
request.path("UserPoolId").asText(),
|
||||
request.path("ClientId").asText()
|
||||
);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("UserPoolClient", clientToNode(client));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleListUserPoolClients(JsonNode request) {
|
||||
List<UserPoolClient> clients = service.listUserPoolClients(request.path("UserPoolId").asText());
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode items = response.putArray("UserPoolClients");
|
||||
clients.forEach(c -> items.add(clientToNode(c)));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteUserPoolClient(JsonNode request) {
|
||||
service.deleteUserPoolClient(
|
||||
request.path("UserPoolId").asText(),
|
||||
request.path("ClientId").asText()
|
||||
);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleAdminCreateUser(JsonNode request) {
|
||||
Map<String, String> attrs = new HashMap<>();
|
||||
request.path("UserAttributes").forEach(a -> attrs.put(a.path("Name").asText(), a.path("Value").asText()));
|
||||
String tempPassword = request.path("TemporaryPassword").isMissingNode() ? null
|
||||
: request.path("TemporaryPassword").asText(null);
|
||||
|
||||
CognitoUser user = service.adminCreateUser(
|
||||
request.path("UserPoolId").asText(),
|
||||
request.path("Username").asText(),
|
||||
attrs,
|
||||
tempPassword
|
||||
);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("User", userToNode(user));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleAdminGetUser(JsonNode request) {
|
||||
CognitoUser user = service.adminGetUser(
|
||||
request.path("UserPoolId").asText(),
|
||||
request.path("Username").asText()
|
||||
);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Username", user.getUsername());
|
||||
response.put("UserStatus", user.getUserStatus());
|
||||
response.put("Enabled", user.isEnabled());
|
||||
response.put("UserCreateDate", user.getCreationDate());
|
||||
response.put("UserLastModifiedDate", user.getLastModifiedDate());
|
||||
ArrayNode attrs = response.putArray("UserAttributes");
|
||||
user.getAttributes().forEach((k, v) -> {
|
||||
ObjectNode attr = attrs.addObject();
|
||||
attr.put("Name", k);
|
||||
attr.put("Value", v);
|
||||
});
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleAdminDeleteUser(JsonNode request) {
|
||||
service.adminDeleteUser(request.path("UserPoolId").asText(), request.path("Username").asText());
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleAdminSetUserPassword(JsonNode request) {
|
||||
service.adminSetUserPassword(
|
||||
request.path("UserPoolId").asText(),
|
||||
request.path("Username").asText(),
|
||||
request.path("Password").asText(),
|
||||
request.path("Permanent").asBoolean(true)
|
||||
);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleAdminUpdateUserAttributes(JsonNode request) {
|
||||
Map<String, String> attrs = new HashMap<>();
|
||||
request.path("UserAttributes").forEach(a -> attrs.put(a.path("Name").asText(), a.path("Value").asText()));
|
||||
service.adminUpdateUserAttributes(
|
||||
request.path("UserPoolId").asText(),
|
||||
request.path("Username").asText(),
|
||||
attrs
|
||||
);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleListUsers(JsonNode request) {
|
||||
List<CognitoUser> users = service.listUsers(request.path("UserPoolId").asText());
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode items = response.putArray("Users");
|
||||
users.forEach(u -> items.add(userToNode(u)));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleInitiateAuth(JsonNode request) {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
request.path("AuthParameters").fields().forEachRemaining(e -> params.put(e.getKey(), e.getValue().asText()));
|
||||
|
||||
Map<String, Object> result = service.initiateAuth(
|
||||
request.path("ClientId").asText(),
|
||||
request.path("AuthFlow").asText(),
|
||||
params
|
||||
);
|
||||
return Response.ok(objectMapper.valueToTree(result)).build();
|
||||
}
|
||||
|
||||
private Response handleAdminInitiateAuth(JsonNode request) {
|
||||
Map<String, String> params = new HashMap<>();
|
||||
request.path("AuthParameters").fields().forEachRemaining(e -> params.put(e.getKey(), e.getValue().asText()));
|
||||
|
||||
Map<String, Object> result = service.adminInitiateAuth(
|
||||
request.path("UserPoolId").asText(),
|
||||
request.path("ClientId").asText(),
|
||||
request.path("AuthFlow").asText(),
|
||||
params
|
||||
);
|
||||
return Response.ok(objectMapper.valueToTree(result)).build();
|
||||
}
|
||||
|
||||
private Response handleRespondToAuthChallenge(JsonNode request) {
|
||||
Map<String, String> responses = new HashMap<>();
|
||||
request.path("ChallengeResponses").fields().forEachRemaining(e -> responses.put(e.getKey(), e.getValue().asText()));
|
||||
|
||||
Map<String, Object> result = service.respondToAuthChallenge(
|
||||
request.path("ClientId").asText(),
|
||||
request.path("ChallengeName").asText(),
|
||||
request.path("Session").asText(null),
|
||||
responses
|
||||
);
|
||||
return Response.ok(objectMapper.valueToTree(result)).build();
|
||||
}
|
||||
|
||||
private Response handleSignUp(JsonNode request) {
|
||||
Map<String, String> attrs = new HashMap<>();
|
||||
request.path("UserAttributes").forEach(a -> attrs.put(a.path("Name").asText(), a.path("Value").asText()));
|
||||
|
||||
CognitoUser user = service.signUp(
|
||||
request.path("ClientId").asText(),
|
||||
request.path("Username").asText(),
|
||||
request.path("Password").asText(),
|
||||
attrs
|
||||
);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("UserConfirmed", "CONFIRMED".equals(user.getUserStatus()));
|
||||
response.put("UserSub", user.getUsername());
|
||||
ObjectNode delivery = response.putObject("CodeDeliveryDetails");
|
||||
delivery.put("AttributeName", "email");
|
||||
delivery.put("DeliveryMedium", "EMAIL");
|
||||
delivery.put("Destination", user.getAttributes().getOrDefault("email", "****"));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleConfirmSignUp(JsonNode request) {
|
||||
service.confirmSignUp(
|
||||
request.path("ClientId").asText(),
|
||||
request.path("Username").asText()
|
||||
);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleChangePassword(JsonNode request) {
|
||||
service.changePassword(
|
||||
request.path("AccessToken").asText(),
|
||||
request.path("PreviousPassword").asText(),
|
||||
request.path("ProposedPassword").asText()
|
||||
);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleForgotPassword(JsonNode request) {
|
||||
service.forgotPassword(
|
||||
request.path("ClientId").asText(),
|
||||
request.path("Username").asText()
|
||||
);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ObjectNode delivery = response.putObject("CodeDeliveryDetails");
|
||||
delivery.put("AttributeName", "email");
|
||||
delivery.put("DeliveryMedium", "EMAIL");
|
||||
delivery.put("Destination", "****");
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleConfirmForgotPassword(JsonNode request) {
|
||||
service.confirmForgotPassword(
|
||||
request.path("ClientId").asText(),
|
||||
request.path("Username").asText(),
|
||||
request.path("ConfirmationCode").asText(),
|
||||
request.path("Password").asText()
|
||||
);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleGetUser(JsonNode request) {
|
||||
Map<String, Object> result = service.getUser(request.path("AccessToken").asText());
|
||||
return Response.ok(objectMapper.valueToTree(result)).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateUserAttributes(JsonNode request) {
|
||||
Map<String, String> attrs = new HashMap<>();
|
||||
request.path("UserAttributes").forEach(a -> attrs.put(a.path("Name").asText(), a.path("Value").asText()));
|
||||
service.updateUserAttributes(request.path("AccessToken").asText(), attrs);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.putArray("CodeDeliveryDetailsList");
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private ObjectNode userPoolToNode(UserPool p) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("Id", p.getId());
|
||||
node.put("Name", p.getName());
|
||||
node.put("CreationDate", p.getCreationDate());
|
||||
node.put("LastModifiedDate", p.getLastModifiedDate());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode clientToNode(UserPoolClient c) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("ClientId", c.getClientId());
|
||||
node.put("UserPoolId", c.getUserPoolId());
|
||||
node.put("ClientName", c.getClientName());
|
||||
node.put("CreationDate", c.getCreationDate());
|
||||
node.put("LastModifiedDate", c.getLastModifiedDate());
|
||||
return node;
|
||||
}
|
||||
|
||||
private ObjectNode userToNode(CognitoUser u) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("Username", u.getUsername());
|
||||
node.put("UserStatus", u.getUserStatus());
|
||||
node.put("Enabled", u.isEnabled());
|
||||
node.put("UserCreateDate", u.getCreationDate());
|
||||
node.put("UserLastModifiedDate", u.getLastModifiedDate());
|
||||
ArrayNode attrs = node.putArray("Attributes");
|
||||
u.getAttributes().forEach((k, v) -> {
|
||||
ObjectNode attr = attrs.addObject();
|
||||
attr.put("Name", k);
|
||||
attr.put("Value", v);
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPool;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CognitoService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CognitoService.class);
|
||||
|
||||
private final StorageBackend<String, UserPool> poolStore;
|
||||
private final StorageBackend<String, UserPoolClient> clientStore;
|
||||
private final StorageBackend<String, CognitoUser> userStore;
|
||||
|
||||
@Inject
|
||||
public CognitoService(StorageFactory storageFactory) {
|
||||
this.poolStore = storageFactory.create("cognito", "cognito-pools.json",
|
||||
new TypeReference<Map<String, UserPool>>() {});
|
||||
this.clientStore = storageFactory.create("cognito", "cognito-clients.json",
|
||||
new TypeReference<Map<String, UserPoolClient>>() {});
|
||||
this.userStore = storageFactory.create("cognito", "cognito-users.json",
|
||||
new TypeReference<Map<String, CognitoUser>>() {});
|
||||
}
|
||||
|
||||
// ──────────────────────────── User Pools ────────────────────────────
|
||||
|
||||
public UserPool createUserPool(String name, String region) {
|
||||
String id = region + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 9);
|
||||
UserPool pool = new UserPool();
|
||||
pool.setId(id);
|
||||
pool.setName(name);
|
||||
poolStore.put(id, pool);
|
||||
LOG.infov("Created User Pool: {0}", id);
|
||||
return pool;
|
||||
}
|
||||
|
||||
public UserPool describeUserPool(String id) {
|
||||
return poolStore.get(id)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool not found", 404));
|
||||
}
|
||||
|
||||
public List<UserPool> listUserPools() {
|
||||
return poolStore.scan(k -> true);
|
||||
}
|
||||
|
||||
public void deleteUserPool(String id) {
|
||||
poolStore.delete(id);
|
||||
}
|
||||
|
||||
// ──────────────────────────── User Pool Clients ────────────────────────────
|
||||
|
||||
public UserPoolClient createUserPoolClient(String userPoolId, String clientName) {
|
||||
describeUserPool(userPoolId);
|
||||
String clientId = UUID.randomUUID().toString().replace("-", "").substring(0, 26);
|
||||
UserPoolClient client = new UserPoolClient();
|
||||
client.setClientId(clientId);
|
||||
client.setUserPoolId(userPoolId);
|
||||
client.setClientName(clientName);
|
||||
clientStore.put(clientId, client);
|
||||
LOG.infov("Created User Pool Client: {0} for pool {1}", clientId, userPoolId);
|
||||
return client;
|
||||
}
|
||||
|
||||
public UserPoolClient describeUserPoolClient(String userPoolId, String clientId) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 404));
|
||||
if (!client.getUserPoolId().equals(userPoolId)) {
|
||||
throw new AwsException("ResourceNotFoundException", "User pool client not found", 404);
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
public List<UserPoolClient> listUserPoolClients(String userPoolId) {
|
||||
return clientStore.scan(k -> clientStore.get(k).map(c -> c.getUserPoolId().equals(userPoolId)).orElse(false));
|
||||
}
|
||||
|
||||
public void deleteUserPoolClient(String userPoolId, String clientId) {
|
||||
describeUserPoolClient(userPoolId, clientId);
|
||||
clientStore.delete(clientId);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Users ────────────────────────────
|
||||
|
||||
public CognitoUser adminCreateUser(String userPoolId, String username, Map<String, String> attributes,
|
||||
String temporaryPassword) {
|
||||
describeUserPool(userPoolId);
|
||||
String key = userKey(userPoolId, username);
|
||||
if (userStore.get(key).isPresent()) {
|
||||
throw new AwsException("UsernameExistsException", "User already exists", 400);
|
||||
}
|
||||
|
||||
CognitoUser user = new CognitoUser();
|
||||
user.setUsername(username);
|
||||
user.setUserPoolId(userPoolId);
|
||||
if (attributes != null) {
|
||||
user.getAttributes().putAll(attributes);
|
||||
}
|
||||
|
||||
if (temporaryPassword != null && !temporaryPassword.isEmpty()) {
|
||||
user.setPasswordHash(hashPassword(temporaryPassword));
|
||||
user.setTemporaryPassword(true);
|
||||
user.setUserStatus("FORCE_CHANGE_PASSWORD");
|
||||
}
|
||||
|
||||
userStore.put(key, user);
|
||||
LOG.infov("Created user {0} in pool {1}", username, userPoolId);
|
||||
return user;
|
||||
}
|
||||
|
||||
public CognitoUser adminGetUser(String userPoolId, String username) {
|
||||
return userStore.get(userKey(userPoolId, username))
|
||||
.orElseThrow(() -> new AwsException("UserNotFoundException", "User not found", 404));
|
||||
}
|
||||
|
||||
public void adminDeleteUser(String userPoolId, String username) {
|
||||
userStore.delete(userKey(userPoolId, username));
|
||||
}
|
||||
|
||||
public void adminSetUserPassword(String userPoolId, String username, String password, boolean permanent) {
|
||||
CognitoUser user = adminGetUser(userPoolId, username);
|
||||
user.setPasswordHash(hashPassword(password));
|
||||
user.setTemporaryPassword(!permanent);
|
||||
user.setUserStatus(permanent ? "CONFIRMED" : "FORCE_CHANGE_PASSWORD");
|
||||
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(userPoolId, username), user);
|
||||
LOG.infov("Set password for user {0} in pool {1} (permanent={2})", username, userPoolId, permanent);
|
||||
}
|
||||
|
||||
public void adminUpdateUserAttributes(String userPoolId, String username, Map<String, String> attributes) {
|
||||
CognitoUser user = adminGetUser(userPoolId, username);
|
||||
user.getAttributes().putAll(attributes);
|
||||
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(userPoolId, username), user);
|
||||
}
|
||||
|
||||
public List<CognitoUser> listUsers(String userPoolId) {
|
||||
String prefix = userPoolId + "::";
|
||||
return userStore.scan(k -> k.startsWith(prefix));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Self-Service Registration ────────────────────────────
|
||||
|
||||
public CognitoUser signUp(String clientId, String username, String password, Map<String, String> attributes) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
|
||||
String userPoolId = client.getUserPoolId();
|
||||
describeUserPool(userPoolId);
|
||||
|
||||
String key = userKey(userPoolId, username);
|
||||
if (userStore.get(key).isPresent()) {
|
||||
throw new AwsException("UsernameExistsException", "User already exists", 400);
|
||||
}
|
||||
|
||||
CognitoUser user = new CognitoUser();
|
||||
user.setUsername(username);
|
||||
user.setUserPoolId(userPoolId);
|
||||
user.setPasswordHash(hashPassword(password));
|
||||
user.setUserStatus("UNCONFIRMED");
|
||||
if (attributes != null) {
|
||||
user.getAttributes().putAll(attributes);
|
||||
}
|
||||
|
||||
userStore.put(key, user);
|
||||
LOG.infov("Signed up user {0} in pool {1}", username, userPoolId);
|
||||
return user;
|
||||
}
|
||||
|
||||
public void confirmSignUp(String clientId, String username) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
|
||||
CognitoUser user = adminGetUser(client.getUserPoolId(), username);
|
||||
user.setUserStatus("CONFIRMED");
|
||||
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(client.getUserPoolId(), username), user);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Auth ────────────────────────────
|
||||
|
||||
public Map<String, Object> initiateAuth(String clientId, String authFlow, Map<String, String> authParameters) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
|
||||
UserPool pool = describeUserPool(client.getUserPoolId());
|
||||
|
||||
return switch (authFlow) {
|
||||
case "USER_PASSWORD_AUTH" -> authenticateWithPassword(pool, authParameters, clientId);
|
||||
case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> handleRefreshToken(pool, authParameters);
|
||||
default -> {
|
||||
// For other flows (USER_SRP_AUTH, etc.), if user exists return tokens
|
||||
String username = authParameters.get("USERNAME");
|
||||
if (username == null) {
|
||||
throw new AwsException("InvalidParameterException", "USERNAME is required", 400);
|
||||
}
|
||||
CognitoUser user = adminGetUser(pool.getId(), username);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("AuthenticationResult", generateAuthResult(user, pool));
|
||||
yield result;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public Map<String, Object> adminInitiateAuth(String userPoolId, String clientId, String authFlow,
|
||||
Map<String, String> authParameters) {
|
||||
describeUserPoolClient(userPoolId, clientId);
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
|
||||
return switch (authFlow) {
|
||||
case "ADMIN_USER_PASSWORD_AUTH", "USER_PASSWORD_AUTH" ->
|
||||
authenticateWithPassword(pool, authParameters, clientId);
|
||||
case "REFRESH_TOKEN_AUTH", "REFRESH_TOKEN" -> handleRefreshToken(pool, authParameters);
|
||||
default -> {
|
||||
String username = authParameters.get("USERNAME");
|
||||
CognitoUser user = adminGetUser(userPoolId, username);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("AuthenticationResult", generateAuthResult(user, pool));
|
||||
yield result;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public Map<String, Object> respondToAuthChallenge(String clientId, String challengeName,
|
||||
String session, Map<String, String> responses) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
|
||||
UserPool pool = describeUserPool(client.getUserPoolId());
|
||||
|
||||
if ("NEW_PASSWORD_REQUIRED".equals(challengeName)) {
|
||||
String username = responses.get("USERNAME");
|
||||
String newPassword = responses.get("NEW_PASSWORD");
|
||||
if (username == null || newPassword == null) {
|
||||
throw new AwsException("InvalidParameterException", "USERNAME and NEW_PASSWORD are required", 400);
|
||||
}
|
||||
adminSetUserPassword(pool.getId(), username, newPassword, true);
|
||||
CognitoUser user = adminGetUser(pool.getId(), username);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("AuthenticationResult", generateAuthResult(user, pool));
|
||||
return result;
|
||||
}
|
||||
|
||||
throw new AwsException("InvalidParameterException", "Unsupported challenge: " + challengeName, 400);
|
||||
}
|
||||
|
||||
public void changePassword(String accessToken, String previousPassword, String proposedPassword) {
|
||||
String username = extractUsernameFromToken(accessToken);
|
||||
String poolId = extractPoolIdFromToken(accessToken);
|
||||
if (username == null || poolId == null) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid access token", 400);
|
||||
}
|
||||
|
||||
CognitoUser user = adminGetUser(poolId, username);
|
||||
if (user.getPasswordHash() != null && !user.getPasswordHash().equals(hashPassword(previousPassword))) {
|
||||
throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400);
|
||||
}
|
||||
|
||||
user.setPasswordHash(hashPassword(proposedPassword));
|
||||
user.setTemporaryPassword(false);
|
||||
user.setUserStatus("CONFIRMED");
|
||||
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(poolId, username), user);
|
||||
}
|
||||
|
||||
public void forgotPassword(String clientId, String username) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
|
||||
// Verify user exists; real AWS would send email/SMS
|
||||
adminGetUser(client.getUserPoolId(), username);
|
||||
LOG.infov("ForgotPassword stub: user {0} requested password reset", username);
|
||||
}
|
||||
|
||||
public void confirmForgotPassword(String clientId, String username, String confirmationCode, String newPassword) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
|
||||
// Accept any confirmation code in the emulator
|
||||
adminSetUserPassword(client.getUserPoolId(), username, newPassword, true);
|
||||
}
|
||||
|
||||
public Map<String, Object> getUser(String accessToken) {
|
||||
String username = extractUsernameFromToken(accessToken);
|
||||
String poolId = extractPoolIdFromToken(accessToken);
|
||||
if (username == null || poolId == null) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid access token", 400);
|
||||
}
|
||||
CognitoUser user = adminGetUser(poolId, username);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("Username", user.getUsername());
|
||||
List<Map<String, String>> attrs = new ArrayList<>();
|
||||
user.getAttributes().forEach((k, v) -> attrs.add(Map.of("Name", k, "Value", v)));
|
||||
result.put("UserAttributes", attrs);
|
||||
return result;
|
||||
}
|
||||
|
||||
public void updateUserAttributes(String accessToken, Map<String, String> attributes) {
|
||||
String username = extractUsernameFromToken(accessToken);
|
||||
String poolId = extractPoolIdFromToken(accessToken);
|
||||
if (username == null || poolId == null) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid access token", 400);
|
||||
}
|
||||
adminUpdateUserAttributes(poolId, username, attributes);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Private helpers ────────────────────────────
|
||||
|
||||
private Map<String, Object> authenticateWithPassword(UserPool pool, Map<String, String> params, String clientId) {
|
||||
String username = params.get("USERNAME");
|
||||
String password = params.get("PASSWORD");
|
||||
if (username == null) {
|
||||
throw new AwsException("InvalidParameterException", "USERNAME is required", 400);
|
||||
}
|
||||
if (password == null) {
|
||||
throw new AwsException("InvalidParameterException", "PASSWORD is required", 400);
|
||||
}
|
||||
|
||||
CognitoUser user = adminGetUser(pool.getId(), username);
|
||||
|
||||
if (!user.isEnabled()) {
|
||||
throw new AwsException("UserNotConfirmedException", "User is disabled", 400);
|
||||
}
|
||||
|
||||
if ("UNCONFIRMED".equals(user.getUserStatus())) {
|
||||
throw new AwsException("UserNotConfirmedException", "User is not confirmed", 400);
|
||||
}
|
||||
|
||||
if (user.getPasswordHash() != null && !user.getPasswordHash().equals(hashPassword(password))) {
|
||||
throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400);
|
||||
}
|
||||
|
||||
if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) {
|
||||
// Return a challenge instead of auth tokens
|
||||
String session = buildSessionToken(pool.getId(), username, clientId);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("ChallengeName", "NEW_PASSWORD_REQUIRED");
|
||||
result.put("Session", session);
|
||||
result.put("ChallengeParameters", Map.of(
|
||||
"USER_ID_FOR_SRP", username,
|
||||
"requiredAttributes", "[]",
|
||||
"userAttributes", "{}"
|
||||
));
|
||||
return result;
|
||||
}
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("AuthenticationResult", generateAuthResult(user, pool));
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<String, Object> handleRefreshToken(UserPool pool, Map<String, String> params) {
|
||||
// In the emulator, accept any refresh token and return new tokens
|
||||
// A real implementation would validate the refresh token
|
||||
String refreshToken = params.get("REFRESH_TOKEN");
|
||||
if (refreshToken == null) {
|
||||
throw new AwsException("InvalidParameterException", "REFRESH_TOKEN is required", 400);
|
||||
}
|
||||
// We can't look up the user from a stub refresh token, so return a minimal result
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", generateTokenString("access", "unknown", pool));
|
||||
auth.put("IdToken", generateTokenString("id", "unknown", pool));
|
||||
auth.put("ExpiresIn", 3600);
|
||||
auth.put("TokenType", "Bearer");
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("AuthenticationResult", auth);
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool) {
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", generateSignedJwt(user, pool, "access"));
|
||||
auth.put("IdToken", generateSignedJwt(user, pool, "id"));
|
||||
auth.put("RefreshToken", UUID.randomUUID().toString());
|
||||
auth.put("ExpiresIn", 3600);
|
||||
auth.put("TokenType", "Bearer");
|
||||
return auth;
|
||||
}
|
||||
|
||||
private String generateSignedJwt(CognitoUser user, UserPool pool, String type) {
|
||||
String headerJson = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
|
||||
String header = Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
String email = user.getAttributes().getOrDefault("email", user.getUsername());
|
||||
String payloadJson = String.format(
|
||||
"{\"sub\":\"%s\",\"event_id\":\"%s\",\"token_use\":\"%s\",\"auth_time\":%d," +
|
||||
"\"iss\":\"https://cognito-idp.local/%s\",\"exp\":%d,\"iat\":%d," +
|
||||
"\"username\":\"%s\",\"email\":\"%s\",\"cognito:username\":\"%s\"}",
|
||||
UUID.randomUUID(), UUID.randomUUID(), type, now,
|
||||
pool.getId(), now + 3600, now,
|
||||
user.getUsername(), email, user.getUsername()
|
||||
);
|
||||
String payload = Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
String signingInput = header + "." + payload;
|
||||
String signature = hmacSha256(signingInput, pool.getSigningSecret());
|
||||
return signingInput + "." + signature;
|
||||
}
|
||||
|
||||
private String generateTokenString(String type, String username, UserPool pool) {
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
String headerJson = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}";
|
||||
String header = Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
|
||||
String payloadJson = String.format(
|
||||
"{\"sub\":\"%s\",\"token_use\":\"%s\",\"iss\":\"https://cognito-idp.local/%s\"," +
|
||||
"\"exp\":%d,\"iat\":%d,\"username\":\"%s\"}",
|
||||
UUID.randomUUID(), type, pool.getId(), now + 3600, now, username
|
||||
);
|
||||
String payload = Base64.getUrlEncoder().withoutPadding()
|
||||
.encodeToString(payloadJson.getBytes(StandardCharsets.UTF_8));
|
||||
String signingInput = header + "." + payload;
|
||||
String signature = hmacSha256(signingInput, pool.getSigningSecret());
|
||||
return signingInput + "." + signature;
|
||||
}
|
||||
|
||||
private String hmacSha256(String data, String key) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
byte[] sig = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(sig);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("JWT signing failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
String hashPassword(String password) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (byte b : hash) {
|
||||
hex.append(String.format("%02x", b));
|
||||
}
|
||||
return hex.toString();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Password hashing failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String buildSessionToken(String poolId, String username, String clientId) {
|
||||
String raw = poolId + "|" + username + "|" + clientId + "|" + UUID.randomUUID();
|
||||
return Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private String extractUsernameFromToken(String token) {
|
||||
try {
|
||||
String[] parts = token.split("\\.");
|
||||
if (parts.length < 2) return null;
|
||||
String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
|
||||
// Simple extraction without full JSON parsing
|
||||
return extractJsonField(payloadJson, "username");
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String extractPoolIdFromToken(String token) {
|
||||
try {
|
||||
String[] parts = token.split("\\.");
|
||||
if (parts.length < 2) return null;
|
||||
String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
|
||||
String iss = extractJsonField(payloadJson, "iss");
|
||||
if (iss == null) return null;
|
||||
// iss = "https://cognito-idp.local/POOL_ID"
|
||||
int lastSlash = iss.lastIndexOf('/');
|
||||
return lastSlash >= 0 ? iss.substring(lastSlash + 1) : null;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String extractJsonField(String json, String field) {
|
||||
String search = "\"" + field + "\":\"";
|
||||
int start = json.indexOf(search);
|
||||
if (start < 0) return null;
|
||||
start += search.length();
|
||||
int end = json.indexOf('"', start);
|
||||
if (end < 0) return null;
|
||||
return json.substring(start, end);
|
||||
}
|
||||
|
||||
private String userKey(String poolId, String username) {
|
||||
return poolId + "::" + username;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPool;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* Exposes Cognito well-known endpoints.
|
||||
* The JWKS endpoint allows downstream services to verify JWTs issued by Floci Cognito pools.
|
||||
* Path mirrors real AWS: /{userPoolId}/.well-known/jwks.json
|
||||
*/
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public class CognitoWellKnownController {
|
||||
|
||||
private final CognitoService cognitoService;
|
||||
|
||||
@Inject
|
||||
public CognitoWellKnownController(CognitoService cognitoService) {
|
||||
this.cognitoService = cognitoService;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{poolId}/.well-known/jwks.json")
|
||||
public Response getJwks(@PathParam("poolId") String poolId) {
|
||||
UserPool pool = cognitoService.describeUserPool(poolId);
|
||||
String kid = pool.getId();
|
||||
// Encode signing secret bytes as Base64URL (no padding) for the JWK "k" parameter
|
||||
byte[] secretBytes = pool.getSigningSecret().getBytes(StandardCharsets.UTF_8);
|
||||
String k = Base64.getUrlEncoder().withoutPadding().encodeToString(secretBytes);
|
||||
|
||||
String body = """
|
||||
{"keys":[{"kty":"oct","kid":"%s","alg":"HS256","k":"%s","use":"sig"}]}
|
||||
""".formatted(kid, k).strip();
|
||||
return Response.ok(body).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package io.github.hectorvent.floci.services.cognito.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class CognitoUser {
|
||||
private String username;
|
||||
private String userPoolId;
|
||||
private String userStatus; // UNCONFIRMED, CONFIRMED, ARCHIVED, COMPROMISED, UNKNOWN, RESET_REQUIRED, FORCE_CHANGE_PASSWORD
|
||||
private boolean enabled;
|
||||
private Map<String, String> attributes = new HashMap<>();
|
||||
private long creationDate;
|
||||
private long lastModifiedDate;
|
||||
private String passwordHash;
|
||||
private boolean temporaryPassword;
|
||||
|
||||
public CognitoUser() {
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
this.creationDate = now;
|
||||
this.lastModifiedDate = now;
|
||||
this.userStatus = "CONFIRMED";
|
||||
this.enabled = true;
|
||||
}
|
||||
|
||||
public String getUsername() { return username; }
|
||||
public void setUsername(String username) { this.username = username; }
|
||||
|
||||
public String getUserPoolId() { return userPoolId; }
|
||||
public void setUserPoolId(String userPoolId) { this.userPoolId = userPoolId; }
|
||||
|
||||
public String getUserStatus() { return userStatus; }
|
||||
public void setUserStatus(String userStatus) { this.userStatus = userStatus; }
|
||||
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public void setEnabled(boolean enabled) { this.enabled = enabled; }
|
||||
|
||||
public Map<String, String> getAttributes() { return attributes; }
|
||||
public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; }
|
||||
|
||||
public long getCreationDate() { return creationDate; }
|
||||
public void setCreationDate(long creationDate) { this.creationDate = creationDate; }
|
||||
|
||||
public long getLastModifiedDate() { return lastModifiedDate; }
|
||||
public void setLastModifiedDate(long lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; }
|
||||
|
||||
public String getPasswordHash() { return passwordHash; }
|
||||
public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; }
|
||||
|
||||
public boolean isTemporaryPassword() { return temporaryPassword; }
|
||||
public void setTemporaryPassword(boolean temporaryPassword) { this.temporaryPassword = temporaryPassword; }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package io.github.hectorvent.floci.services.cognito.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class UserPool {
|
||||
private String id;
|
||||
private String name;
|
||||
private String signingSecret;
|
||||
private long creationDate;
|
||||
private long lastModifiedDate;
|
||||
|
||||
public UserPool() {
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
this.creationDate = now;
|
||||
this.lastModifiedDate = now;
|
||||
this.signingSecret = java.util.UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
|
||||
public String getId() { return id; }
|
||||
public void setId(String id) { this.id = id; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getSigningSecret() { return signingSecret; }
|
||||
public void setSigningSecret(String signingSecret) { this.signingSecret = signingSecret; }
|
||||
|
||||
public long getCreationDate() { return creationDate; }
|
||||
public void setCreationDate(long creationDate) { this.creationDate = creationDate; }
|
||||
|
||||
public long getLastModifiedDate() { return lastModifiedDate; }
|
||||
public void setLastModifiedDate(long lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package io.github.hectorvent.floci.services.cognito.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class UserPoolClient {
|
||||
private String clientId;
|
||||
private String userPoolId;
|
||||
private String clientName;
|
||||
private long creationDate;
|
||||
private long lastModifiedDate;
|
||||
|
||||
public UserPoolClient() {
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
this.creationDate = now;
|
||||
this.lastModifiedDate = now;
|
||||
}
|
||||
|
||||
public String getClientId() { return clientId; }
|
||||
public void setClientId(String clientId) { this.clientId = clientId; }
|
||||
|
||||
public String getUserPoolId() { return userPoolId; }
|
||||
public void setUserPoolId(String userPoolId) { this.userPoolId = userPoolId; }
|
||||
|
||||
public String getClientName() { return clientName; }
|
||||
public void setClientName(String clientName) { this.clientName = clientName; }
|
||||
|
||||
public long getCreationDate() { return creationDate; }
|
||||
public void setCreationDate(long creationDate) { this.creationDate = creationDate; }
|
||||
|
||||
public long getLastModifiedDate() { return lastModifiedDate; }
|
||||
public void setLastModifiedDate(long lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; }
|
||||
}
|
||||
@@ -0,0 +1,625 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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.core.common.AwsJsonController;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.*;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* DynamoDB JSON protocol handler.
|
||||
* Called by {@link AwsJsonController} for DynamoDB-targeted requests.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class DynamoDbJsonHandler {
|
||||
|
||||
private final DynamoDbService dynamoDbService;
|
||||
private final DynamoDbStreamService dynamoDbStreamService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public DynamoDbJsonHandler(DynamoDbService dynamoDbService, DynamoDbStreamService dynamoDbStreamService,
|
||||
ObjectMapper objectMapper) {
|
||||
this.dynamoDbService = dynamoDbService;
|
||||
this.dynamoDbStreamService = dynamoDbStreamService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) throws Exception {
|
||||
return switch (action) {
|
||||
case "CreateTable" -> handleCreateTable(request, region);
|
||||
case "DeleteTable" -> handleDeleteTable(request, region);
|
||||
case "DescribeTable" -> handleDescribeTable(request, region);
|
||||
case "ListTables" -> handleListTables(request, region);
|
||||
case "PutItem" -> handlePutItem(request, region);
|
||||
case "GetItem" -> handleGetItem(request, region);
|
||||
case "DeleteItem" -> handleDeleteItem(request, region);
|
||||
case "UpdateItem" -> handleUpdateItem(request, region);
|
||||
case "Query" -> handleQuery(request, region);
|
||||
case "Scan" -> handleScan(request, region);
|
||||
case "BatchWriteItem" -> handleBatchWriteItem(request, region);
|
||||
case "BatchGetItem" -> handleBatchGetItem(request, region);
|
||||
case "UpdateTable" -> handleUpdateTable(request, region);
|
||||
case "DescribeTimeToLive" -> handleDescribeTimeToLive(request, region);
|
||||
case "UpdateTimeToLive" -> handleUpdateTimeToLive(request, region);
|
||||
case "TransactWriteItems" -> handleTransactWriteItems(request, region);
|
||||
case "TransactGetItems" -> handleTransactGetItems(request, region);
|
||||
case "TagResource" -> handleTagResource(request, region);
|
||||
case "UntagResource" -> handleUntagResource(request, region);
|
||||
case "ListTagsOfResource" -> handleListTagsOfResource(request, region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnknownOperationException", "Operation " + action + " is not supported."))
|
||||
.build();
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
private Response handleCreateTable(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
|
||||
List<KeySchemaElement> keySchema = new ArrayList<>();
|
||||
request.path("KeySchema").forEach(ks ->
|
||||
keySchema.add(new KeySchemaElement(
|
||||
ks.path("AttributeName").asText(),
|
||||
ks.path("KeyType").asText())));
|
||||
|
||||
List<AttributeDefinition> attrDefs = new ArrayList<>();
|
||||
request.path("AttributeDefinitions").forEach(ad ->
|
||||
attrDefs.add(new AttributeDefinition(
|
||||
ad.path("AttributeName").asText(),
|
||||
ad.path("AttributeType").asText())));
|
||||
|
||||
Long readCapacity = null;
|
||||
Long writeCapacity = null;
|
||||
JsonNode pt = request.path("ProvisionedThroughput");
|
||||
if (!pt.isMissingNode()) {
|
||||
readCapacity = pt.path("ReadCapacityUnits").asLong(5);
|
||||
writeCapacity = pt.path("WriteCapacityUnits").asLong(5);
|
||||
}
|
||||
|
||||
List<GlobalSecondaryIndex> gsis = new ArrayList<>();
|
||||
JsonNode gsiArray = request.path("GlobalSecondaryIndexes");
|
||||
if (!gsiArray.isMissingNode() && gsiArray.isArray()) {
|
||||
for (JsonNode gsiNode : gsiArray) {
|
||||
String indexName = gsiNode.path("IndexName").asText();
|
||||
List<KeySchemaElement> gsiKeySchema = new ArrayList<>();
|
||||
gsiNode.path("KeySchema").forEach(ks ->
|
||||
gsiKeySchema.add(new KeySchemaElement(
|
||||
ks.path("AttributeName").asText(),
|
||||
ks.path("KeyType").asText())));
|
||||
String projectionType = gsiNode.path("Projection").path("ProjectionType").asText("ALL");
|
||||
gsis.add(new GlobalSecondaryIndex(indexName, gsiKeySchema, null, projectionType));
|
||||
}
|
||||
}
|
||||
|
||||
List<LocalSecondaryIndex> lsis = new ArrayList<>();
|
||||
JsonNode lsiArray = request.path("LocalSecondaryIndexes");
|
||||
if (!lsiArray.isMissingNode() && lsiArray.isArray()) {
|
||||
for (JsonNode lsiNode : lsiArray) {
|
||||
String indexName = lsiNode.path("IndexName").asText();
|
||||
List<KeySchemaElement> lsiKeySchema = new ArrayList<>();
|
||||
lsiNode.path("KeySchema").forEach(ks ->
|
||||
lsiKeySchema.add(new KeySchemaElement(
|
||||
ks.path("AttributeName").asText(),
|
||||
ks.path("KeyType").asText())));
|
||||
String projectionType = lsiNode.path("Projection").path("ProjectionType").asText("ALL");
|
||||
lsis.add(new LocalSecondaryIndex(indexName, lsiKeySchema, null, projectionType));
|
||||
}
|
||||
}
|
||||
|
||||
TableDefinition table = dynamoDbService.createTable(tableName, keySchema, attrDefs,
|
||||
readCapacity, writeCapacity, gsis, lsis, region);
|
||||
|
||||
JsonNode streamSpec = request.path("StreamSpecification");
|
||||
if (!streamSpec.isMissingNode() && streamSpec.path("StreamEnabled").asBoolean(false)) {
|
||||
String viewType = streamSpec.path("StreamViewType").asText("NEW_AND_OLD_IMAGES");
|
||||
StreamDescription sd = dynamoDbStreamService.enableStream(
|
||||
tableName, table.getTableArn(), viewType, region);
|
||||
table.setStreamEnabled(true);
|
||||
table.setStreamArn(sd.getStreamArn());
|
||||
table.setStreamViewType(viewType);
|
||||
}
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("TableDescription", tableToNode(table));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteTable(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
TableDefinition table = dynamoDbService.describeTable(tableName, region);
|
||||
dynamoDbService.deleteTable(tableName, region);
|
||||
|
||||
table.setTableStatus("DELETING");
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("TableDescription", tableToNode(table));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeTable(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
TableDefinition table = dynamoDbService.describeTable(tableName, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("Table", tableToNode(table));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleListTables(JsonNode request, String region) {
|
||||
List<String> tables = dynamoDbService.listTables(region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode tableNames = objectMapper.createArrayNode();
|
||||
tables.forEach(tableNames::add);
|
||||
response.set("TableNames", tableNames);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handlePutItem(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
JsonNode item = request.path("Item");
|
||||
String returnValues = request.path("ReturnValues").asText("NONE");
|
||||
String conditionExpression = request.has("ConditionExpression")
|
||||
? request.get("ConditionExpression").asText() : null;
|
||||
JsonNode exprAttrNames = request.has("ExpressionAttributeNames")
|
||||
? request.get("ExpressionAttributeNames") : null;
|
||||
JsonNode exprAttrValues = request.has("ExpressionAttributeValues")
|
||||
? request.get("ExpressionAttributeValues") : null;
|
||||
|
||||
JsonNode oldItem = null;
|
||||
if ("ALL_OLD" .equals(returnValues)) {
|
||||
dynamoDbService.describeTable(tableName, region);
|
||||
oldItem = dynamoDbService.getItem(tableName, item, region);
|
||||
}
|
||||
|
||||
dynamoDbService.putItem(tableName, item, conditionExpression, exprAttrNames, exprAttrValues, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
if ("ALL_OLD" .equals(returnValues) && oldItem != null) {
|
||||
response.set("Attributes", oldItem);
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGetItem(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
JsonNode key = request.path("Key");
|
||||
|
||||
JsonNode item = dynamoDbService.getItem(tableName, key, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
if (item != null) {
|
||||
response.set("Item", item);
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteItem(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
JsonNode key = request.path("Key");
|
||||
String returnValues = request.path("ReturnValues").asText("NONE");
|
||||
String conditionExpression = request.has("ConditionExpression")
|
||||
? request.get("ConditionExpression").asText() : null;
|
||||
JsonNode exprAttrNames = request.has("ExpressionAttributeNames")
|
||||
? request.get("ExpressionAttributeNames") : null;
|
||||
JsonNode exprAttrValues = request.has("ExpressionAttributeValues")
|
||||
? request.get("ExpressionAttributeValues") : null;
|
||||
|
||||
JsonNode oldItem = dynamoDbService.deleteItem(tableName, key, conditionExpression,
|
||||
exprAttrNames, exprAttrValues, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
if ("ALL_OLD" .equals(returnValues) && oldItem != null) {
|
||||
response.set("Attributes", oldItem);
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateItem(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
JsonNode key = request.path("Key");
|
||||
JsonNode attributeUpdates = request.path("AttributeUpdates");
|
||||
JsonNode exprAttrNames = request.has("ExpressionAttributeNames")
|
||||
? request.get("ExpressionAttributeNames") : null;
|
||||
JsonNode exprAttrValues = request.has("ExpressionAttributeValues")
|
||||
? request.get("ExpressionAttributeValues") : null;
|
||||
String updateExpression = request.has("UpdateExpression")
|
||||
? request.get("UpdateExpression").asText() : null;
|
||||
String conditionExpression = request.has("ConditionExpression")
|
||||
? request.get("ConditionExpression").asText() : null;
|
||||
String returnValues = request.path("ReturnValues").asText("NONE");
|
||||
|
||||
JsonNode updateData = attributeUpdates.isMissingNode() ? null : attributeUpdates;
|
||||
|
||||
DynamoDbService.UpdateResult result = dynamoDbService.updateItem(
|
||||
tableName, key, updateData, updateExpression, exprAttrNames, exprAttrValues,
|
||||
returnValues, conditionExpression, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
if ("ALL_NEW" .equals(returnValues) && result.newItem() != null) {
|
||||
response.set("Attributes", result.newItem());
|
||||
} else if ("ALL_OLD" .equals(returnValues) && result.oldItem() != null) {
|
||||
response.set("Attributes", result.oldItem());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleQuery(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
JsonNode keyConditions = request.has("KeyConditions") ? request.get("KeyConditions") : null;
|
||||
JsonNode exprAttrValues = request.has("ExpressionAttributeValues")
|
||||
? request.get("ExpressionAttributeValues") : null;
|
||||
JsonNode exprAttrNames = request.has("ExpressionAttributeNames")
|
||||
? request.get("ExpressionAttributeNames") : null;
|
||||
String keyConditionExpr = request.has("KeyConditionExpression")
|
||||
? request.get("KeyConditionExpression").asText() : null;
|
||||
String filterExpr = request.has("FilterExpression")
|
||||
? request.get("FilterExpression").asText() : null;
|
||||
Integer limit = request.has("Limit") ? request.get("Limit").asInt() : null;
|
||||
String indexName = request.has("IndexName") ? request.get("IndexName").asText() : null;
|
||||
JsonNode exclusiveStartKey = request.has("ExclusiveStartKey")
|
||||
? request.get("ExclusiveStartKey") : null;
|
||||
|
||||
DynamoDbService.QueryResult result = dynamoDbService.query(tableName, keyConditions,
|
||||
exprAttrValues, keyConditionExpr, filterExpr, limit, indexName,
|
||||
exclusiveStartKey, exprAttrNames, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode itemsArray = objectMapper.createArrayNode();
|
||||
result.items().forEach(itemsArray::add);
|
||||
response.set("Items", itemsArray);
|
||||
response.put("Count", result.items().size());
|
||||
response.put("ScannedCount", result.scannedCount());
|
||||
if (result.lastEvaluatedKey() != null) {
|
||||
response.set("LastEvaluatedKey", result.lastEvaluatedKey());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleScan(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
String filterExpr = request.has("FilterExpression")
|
||||
? request.get("FilterExpression").asText() : null;
|
||||
JsonNode exprAttrNames = request.has("ExpressionAttributeNames")
|
||||
? request.get("ExpressionAttributeNames") : null;
|
||||
JsonNode exprAttrValues = request.has("ExpressionAttributeValues")
|
||||
? request.get("ExpressionAttributeValues") : null;
|
||||
Integer limit = request.has("Limit") ? request.get("Limit").asInt() : null;
|
||||
JsonNode exclusiveStartKey = request.has("ExclusiveStartKey")
|
||||
? request.get("ExclusiveStartKey") : null;
|
||||
|
||||
DynamoDbService.ScanResult result = dynamoDbService.scan(
|
||||
tableName, filterExpr, exprAttrNames, exprAttrValues, limit, exclusiveStartKey, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode itemsArray = objectMapper.createArrayNode();
|
||||
result.items().forEach(itemsArray::add);
|
||||
response.set("Items", itemsArray);
|
||||
response.put("Count", result.items().size());
|
||||
response.put("ScannedCount", result.scannedCount());
|
||||
if (result.lastEvaluatedKey() != null) {
|
||||
response.set("LastEvaluatedKey", result.lastEvaluatedKey());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleBatchWriteItem(JsonNode request, String region) {
|
||||
JsonNode requestItems = request.get("RequestItems");
|
||||
if (requestItems == null || requestItems.isNull() || requestItems.isMissingNode()) {
|
||||
return Response.ok(objectMapper.createObjectNode()
|
||||
.set("UnprocessedItems", objectMapper.createObjectNode())).build();
|
||||
}
|
||||
Map<String, List<JsonNode>> items = new HashMap<>();
|
||||
Iterator<Map.Entry<String, JsonNode>> tables = requestItems.fields();
|
||||
while (tables.hasNext()) {
|
||||
var entry = tables.next();
|
||||
List<JsonNode> writes = new ArrayList<>();
|
||||
for (JsonNode writeReq : entry.getValue()) {
|
||||
writes.add(writeReq);
|
||||
}
|
||||
items.put(entry.getKey(), writes);
|
||||
}
|
||||
|
||||
dynamoDbService.batchWriteItem(items, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("UnprocessedItems", objectMapper.createObjectNode());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleBatchGetItem(JsonNode request, String region) {
|
||||
JsonNode requestItems = request.get("RequestItems");
|
||||
if (requestItems == null || requestItems.isNull() || requestItems.isMissingNode()) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("Responses", objectMapper.createObjectNode());
|
||||
response.set("UnprocessedKeys", objectMapper.createObjectNode());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
Map<String, JsonNode> items = new HashMap<>();
|
||||
Iterator<Map.Entry<String, JsonNode>> tables = requestItems.fields();
|
||||
while (tables.hasNext()) {
|
||||
var entry = tables.next();
|
||||
items.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
DynamoDbService.BatchGetResult result = dynamoDbService.batchGetItem(items, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ObjectNode responses = objectMapper.createObjectNode();
|
||||
for (Map.Entry<String, List<JsonNode>> entry : result.responses().entrySet()) {
|
||||
ArrayNode tableItems = objectMapper.createArrayNode();
|
||||
entry.getValue().forEach(tableItems::add);
|
||||
responses.set(entry.getKey(), tableItems);
|
||||
}
|
||||
response.set("Responses", responses);
|
||||
response.set("UnprocessedKeys", objectMapper.createObjectNode());
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateTable(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
Long readCapacity = null;
|
||||
Long writeCapacity = null;
|
||||
JsonNode pt = request.path("ProvisionedThroughput");
|
||||
if (!pt.isMissingNode()) {
|
||||
readCapacity = pt.has("ReadCapacityUnits") ? pt.get("ReadCapacityUnits").asLong() : null;
|
||||
writeCapacity = pt.has("WriteCapacityUnits") ? pt.get("WriteCapacityUnits").asLong() : null;
|
||||
}
|
||||
|
||||
TableDefinition table = dynamoDbService.updateTable(tableName, readCapacity, writeCapacity, region);
|
||||
|
||||
JsonNode streamSpec = request.path("StreamSpecification");
|
||||
if (!streamSpec.isMissingNode()) {
|
||||
boolean streamEnabled = streamSpec.path("StreamEnabled").asBoolean(false);
|
||||
if (streamEnabled) {
|
||||
String viewType = streamSpec.path("StreamViewType").asText("NEW_AND_OLD_IMAGES");
|
||||
StreamDescription sd = dynamoDbStreamService.enableStream(
|
||||
tableName, table.getTableArn(), viewType, region);
|
||||
table.setStreamEnabled(true);
|
||||
table.setStreamArn(sd.getStreamArn());
|
||||
table.setStreamViewType(viewType);
|
||||
} else {
|
||||
dynamoDbStreamService.disableStream(tableName, region);
|
||||
table.setStreamEnabled(false);
|
||||
}
|
||||
}
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("TableDescription", tableToNode(table));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeTimeToLive(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
TableDefinition table = dynamoDbService.describeTable(tableName, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ObjectNode ttlDesc = objectMapper.createObjectNode();
|
||||
if (table.isTtlEnabled() && table.getTtlAttributeName() != null) {
|
||||
ttlDesc.put("TimeToLiveStatus", "ENABLED");
|
||||
ttlDesc.put("AttributeName", table.getTtlAttributeName());
|
||||
} else {
|
||||
ttlDesc.put("TimeToLiveStatus", "DISABLED");
|
||||
}
|
||||
response.set("TimeToLiveDescription", ttlDesc);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateTimeToLive(JsonNode request, String region) {
|
||||
String tableName = request.path("TableName").asText();
|
||||
JsonNode spec = request.path("TimeToLiveSpecification");
|
||||
String ttlAttributeName = spec.path("AttributeName").asText();
|
||||
boolean enabled = spec.path("Enabled").asBoolean(false);
|
||||
|
||||
dynamoDbService.updateTimeToLive(tableName, ttlAttributeName, enabled, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ObjectNode ttlSpec = objectMapper.createObjectNode();
|
||||
ttlSpec.put("AttributeName", ttlAttributeName);
|
||||
ttlSpec.put("Enabled", enabled);
|
||||
response.set("TimeToLiveSpecification", ttlSpec);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleTransactWriteItems(JsonNode request, String region) {
|
||||
JsonNode transactItemsNode = request.path("TransactItems");
|
||||
List<JsonNode> transactItems = new ArrayList<>();
|
||||
if (transactItemsNode.isArray()) {
|
||||
transactItemsNode.forEach(transactItems::add);
|
||||
}
|
||||
|
||||
try {
|
||||
dynamoDbService.transactWriteItems(transactItems, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
} catch (TransactionCanceledException e) {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("__type", "TransactionCanceledException");
|
||||
body.put("message", e.getMessage());
|
||||
ArrayNode reasons = body.putArray("CancellationReasons");
|
||||
for (String reason : e.getCancellationReasons()) {
|
||||
ObjectNode r = objectMapper.createObjectNode();
|
||||
r.put("Code", reason.isEmpty() ? "None" : "ConditionalCheckFailed");
|
||||
r.put("Message", reason);
|
||||
reasons.add(r);
|
||||
}
|
||||
return Response.status(400).entity(body).build();
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleTransactGetItems(JsonNode request, String region) {
|
||||
JsonNode transactItemsNode = request.path("TransactItems");
|
||||
List<JsonNode> transactItems = new ArrayList<>();
|
||||
if (transactItemsNode.isArray()) {
|
||||
transactItemsNode.forEach(transactItems::add);
|
||||
}
|
||||
|
||||
List<JsonNode> results = dynamoDbService.transactGetItems(transactItems, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode responsesArray = objectMapper.createArrayNode();
|
||||
for (JsonNode item : results) {
|
||||
ObjectNode entry = objectMapper.createObjectNode();
|
||||
if (item != null) {
|
||||
entry.set("Item", item);
|
||||
}
|
||||
responsesArray.add(entry);
|
||||
}
|
||||
response.set("Responses", responsesArray);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleTagResource(JsonNode request, String region) {
|
||||
String resourceArn = request.path("ResourceArn").asText();
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
JsonNode tagsNode = request.path("Tags");
|
||||
if (tagsNode.isArray()) {
|
||||
for (JsonNode tag : tagsNode) {
|
||||
tags.put(tag.path("Key").asText(), tag.path("Value").asText());
|
||||
}
|
||||
}
|
||||
dynamoDbService.tagResource(resourceArn, tags, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleUntagResource(JsonNode request, String region) {
|
||||
String resourceArn = request.path("ResourceArn").asText();
|
||||
List<String> tagKeys = new ArrayList<>();
|
||||
JsonNode keysNode = request.path("TagKeys");
|
||||
if (keysNode.isArray()) {
|
||||
for (JsonNode key : keysNode) {
|
||||
tagKeys.add(key.asText());
|
||||
}
|
||||
}
|
||||
dynamoDbService.untagResource(resourceArn, tagKeys, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleListTagsOfResource(JsonNode request, String region) {
|
||||
String resourceArn = request.path("ResourceArn").asText();
|
||||
Map<String, String> tags = dynamoDbService.listTagsOfResource(resourceArn, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode tagsArray = objectMapper.createArrayNode();
|
||||
for (Map.Entry<String, String> entry : tags.entrySet()) {
|
||||
ObjectNode tagNode = objectMapper.createObjectNode();
|
||||
tagNode.put("Key", entry.getKey());
|
||||
tagNode.put("Value", entry.getValue());
|
||||
tagsArray.add(tagNode);
|
||||
}
|
||||
response.set("Tags", tagsArray);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private ObjectNode tableToNode(TableDefinition table) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("TableName", table.getTableName());
|
||||
node.put("TableStatus", table.getTableStatus());
|
||||
node.put("TableArn", table.getTableArn());
|
||||
node.put("CreationDateTime", table.getCreationDateTime().getEpochSecond());
|
||||
node.put("ItemCount", table.getItemCount());
|
||||
node.put("TableSizeBytes", table.getTableSizeBytes());
|
||||
|
||||
ArrayNode keySchemaArray = objectMapper.createArrayNode();
|
||||
for (var ks : table.getKeySchema()) {
|
||||
ObjectNode ksNode = objectMapper.createObjectNode();
|
||||
ksNode.put("AttributeName", ks.getAttributeName());
|
||||
ksNode.put("KeyType", ks.getKeyType());
|
||||
keySchemaArray.add(ksNode);
|
||||
}
|
||||
node.set("KeySchema", keySchemaArray);
|
||||
|
||||
ArrayNode attrDefsArray = objectMapper.createArrayNode();
|
||||
for (var ad : table.getAttributeDefinitions()) {
|
||||
ObjectNode adNode = objectMapper.createObjectNode();
|
||||
adNode.put("AttributeName", ad.getAttributeName());
|
||||
adNode.put("AttributeType", ad.getAttributeType());
|
||||
attrDefsArray.add(adNode);
|
||||
}
|
||||
node.set("AttributeDefinitions", attrDefsArray);
|
||||
|
||||
ObjectNode ptNode = objectMapper.createObjectNode();
|
||||
ptNode.put("ReadCapacityUnits", table.getProvisionedThroughput().getReadCapacityUnits());
|
||||
ptNode.put("WriteCapacityUnits", table.getProvisionedThroughput().getWriteCapacityUnits());
|
||||
ptNode.put("NumberOfDecreasesToday", table.getProvisionedThroughput().getNumberOfDecreasesToday());
|
||||
node.set("ProvisionedThroughput", ptNode);
|
||||
|
||||
List<GlobalSecondaryIndex> gsis = table.getGlobalSecondaryIndexes();
|
||||
if (gsis != null && !gsis.isEmpty()) {
|
||||
ArrayNode gsiArray = objectMapper.createArrayNode();
|
||||
for (GlobalSecondaryIndex gsi : gsis) {
|
||||
ObjectNode gsiNode = objectMapper.createObjectNode();
|
||||
gsiNode.put("IndexName", gsi.getIndexName());
|
||||
gsiNode.put("IndexArn", gsi.getIndexArn());
|
||||
gsiNode.put("IndexStatus", "ACTIVE");
|
||||
|
||||
ArrayNode gsiKeySchema = objectMapper.createArrayNode();
|
||||
for (var ks : gsi.getKeySchema()) {
|
||||
ObjectNode ksNode = objectMapper.createObjectNode();
|
||||
ksNode.put("AttributeName", ks.getAttributeName());
|
||||
ksNode.put("KeyType", ks.getKeyType());
|
||||
gsiKeySchema.add(ksNode);
|
||||
}
|
||||
gsiNode.set("KeySchema", gsiKeySchema);
|
||||
|
||||
ObjectNode projection = objectMapper.createObjectNode();
|
||||
projection.put("ProjectionType",
|
||||
gsi.getProjectionType() != null ? gsi.getProjectionType() : "ALL");
|
||||
gsiNode.set("Projection", projection);
|
||||
|
||||
gsiArray.add(gsiNode);
|
||||
}
|
||||
node.set("GlobalSecondaryIndexes", gsiArray);
|
||||
}
|
||||
|
||||
List<LocalSecondaryIndex> lsis = table.getLocalSecondaryIndexes();
|
||||
if (lsis != null && !lsis.isEmpty()) {
|
||||
ArrayNode lsiArray = objectMapper.createArrayNode();
|
||||
for (LocalSecondaryIndex lsi : lsis) {
|
||||
ObjectNode lsiNode = objectMapper.createObjectNode();
|
||||
lsiNode.put("IndexName", lsi.getIndexName());
|
||||
lsiNode.put("IndexArn", lsi.getIndexArn());
|
||||
|
||||
ArrayNode lsiKeySchema = objectMapper.createArrayNode();
|
||||
for (var ks : lsi.getKeySchema()) {
|
||||
ObjectNode ksNode = objectMapper.createObjectNode();
|
||||
ksNode.put("AttributeName", ks.getAttributeName());
|
||||
ksNode.put("KeyType", ks.getKeyType());
|
||||
lsiKeySchema.add(ksNode);
|
||||
}
|
||||
lsiNode.set("KeySchema", lsiKeySchema);
|
||||
|
||||
ObjectNode projection = objectMapper.createObjectNode();
|
||||
projection.put("ProjectionType",
|
||||
lsi.getProjectionType() != null ? lsi.getProjectionType() : "ALL");
|
||||
lsiNode.set("Projection", projection);
|
||||
|
||||
lsiNode.put("IndexSizeBytes", lsi.getIndexSizeBytes());
|
||||
lsiNode.put("ItemCount", lsi.getItemCount());
|
||||
|
||||
lsiArray.add(lsiNode);
|
||||
}
|
||||
node.set("LocalSecondaryIndexes", lsiArray);
|
||||
}
|
||||
|
||||
if (table.getStreamArn() != null) {
|
||||
ObjectNode streamSpecNode = objectMapper.createObjectNode();
|
||||
streamSpecNode.put("StreamEnabled", table.isStreamEnabled());
|
||||
streamSpecNode.put("StreamViewType", table.getStreamViewType());
|
||||
node.set("StreamSpecification", streamSpecNode);
|
||||
node.put("LatestStreamArn", table.getStreamArn());
|
||||
String label = table.getStreamArn().contains("/stream/")
|
||||
? table.getStreamArn().substring(table.getStreamArn().lastIndexOf("/stream/") + 8)
|
||||
: "";
|
||||
node.put("LatestStreamLabel", label);
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+258
@@ -0,0 +1,258 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@ApplicationScoped
|
||||
public class DynamoDbStreamService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(DynamoDbStreamService.class);
|
||||
|
||||
public static final String SHARD_ID = "shardId-0000000001-00000000001";
|
||||
static final int MAX_RECORDS = 1000;
|
||||
|
||||
private static final DateTimeFormatter STREAM_LABEL_FORMAT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS").withZone(ZoneOffset.UTC);
|
||||
|
||||
private final ConcurrentHashMap<String, StreamDescription> streams = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, ConcurrentLinkedDeque<DynamoDbStreamRecord>> records =
|
||||
new ConcurrentHashMap<>();
|
||||
private final AtomicLong sequenceCounter = new AtomicLong(0);
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public DynamoDbStreamService(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public StreamDescription enableStream(String tableName, String tableArn, String viewType, String region) {
|
||||
String key = streamKey(region, tableName);
|
||||
StreamDescription existing = streams.get(key);
|
||||
if (existing != null && "ENABLED".equals(existing.getStreamStatus())) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
Instant now = Instant.now();
|
||||
String label = STREAM_LABEL_FORMAT.format(now);
|
||||
String streamArn = tableArn + "/stream/" + label;
|
||||
|
||||
StreamDescription sd = new StreamDescription();
|
||||
sd.setStreamArn(streamArn);
|
||||
sd.setStreamLabel(label);
|
||||
sd.setStreamStatus("ENABLED");
|
||||
sd.setStreamViewType(viewType);
|
||||
sd.setTableName(tableName);
|
||||
sd.setCreationDateTime(now);
|
||||
sd.setStartingSequenceNumber(String.format("%021d", 1));
|
||||
|
||||
streams.put(key, sd);
|
||||
records.put(streamArn, new ConcurrentLinkedDeque<>());
|
||||
LOG.infov("Enabled stream for table {0} in region {1}: {2}", tableName, region, streamArn);
|
||||
return sd;
|
||||
}
|
||||
|
||||
public void disableStream(String tableName, String region) {
|
||||
String key = streamKey(region, tableName);
|
||||
StreamDescription sd = streams.get(key);
|
||||
if (sd != null) {
|
||||
sd.setStreamStatus("DISABLED");
|
||||
LOG.infov("Disabled stream for table {0} in region {1}", tableName, region);
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteStream(String tableName, String region) {
|
||||
String key = streamKey(region, tableName);
|
||||
StreamDescription sd = streams.remove(key);
|
||||
if (sd != null) {
|
||||
records.remove(sd.getStreamArn());
|
||||
LOG.infov("Deleted stream for table {0} in region {1}", tableName, region);
|
||||
}
|
||||
}
|
||||
|
||||
public void captureEvent(String tableName, String eventName,
|
||||
JsonNode oldItem, JsonNode newItem,
|
||||
TableDefinition table, String region) {
|
||||
String key = streamKey(region, tableName);
|
||||
StreamDescription sd = streams.get(key);
|
||||
if (sd == null || !"ENABLED".equals(sd.getStreamStatus())) {
|
||||
return;
|
||||
}
|
||||
|
||||
long seq = sequenceCounter.incrementAndGet();
|
||||
String sequenceNumber = String.format("%021d", seq);
|
||||
|
||||
JsonNode sourceItem = newItem != null ? newItem : oldItem;
|
||||
ObjectNode keys = buildKeys(sourceItem, table);
|
||||
|
||||
String viewType = sd.getStreamViewType();
|
||||
JsonNode newImage = buildImage(newItem, viewType, true);
|
||||
JsonNode oldImage = buildImage(oldItem, viewType, false);
|
||||
|
||||
DynamoDbStreamRecord record = new DynamoDbStreamRecord();
|
||||
record.setEventId(UUID.randomUUID().toString());
|
||||
record.setEventVersion("1.1");
|
||||
record.setEventName(eventName);
|
||||
record.setEventSource("aws:dynamodb");
|
||||
record.setAwsRegion(region);
|
||||
record.setSequenceNumber(sequenceNumber);
|
||||
record.setApproximateCreationDateTime(Instant.now().getEpochSecond());
|
||||
record.setKeys(keys);
|
||||
record.setNewImage(newImage);
|
||||
record.setOldImage(oldImage);
|
||||
record.setStreamViewType(viewType);
|
||||
|
||||
ConcurrentLinkedDeque<DynamoDbStreamRecord> deque = records.get(sd.getStreamArn());
|
||||
if (deque != null) {
|
||||
deque.addLast(record);
|
||||
while (deque.size() > MAX_RECORDS) {
|
||||
deque.pollFirst();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode buildKeys(JsonNode item, TableDefinition table) {
|
||||
ObjectNode keys = objectMapper.createObjectNode();
|
||||
if (item == null) {
|
||||
return keys;
|
||||
}
|
||||
for (KeySchemaElement ks : table.getKeySchema()) {
|
||||
String attrName = ks.getAttributeName();
|
||||
if (item.has(attrName)) {
|
||||
keys.set(attrName, item.get(attrName));
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
private JsonNode buildImage(JsonNode item, String viewType, boolean isNewImage) {
|
||||
if (item == null) {
|
||||
return null;
|
||||
}
|
||||
return switch (viewType) {
|
||||
case "KEYS_ONLY" -> null;
|
||||
case "NEW_IMAGE" -> isNewImage ? item : null;
|
||||
case "OLD_IMAGE" -> !isNewImage ? item : null;
|
||||
case "NEW_AND_OLD_IMAGES" -> item;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
public List<StreamDescription> listStreams(String tableNameFilter, String region) {
|
||||
List<StreamDescription> result = new ArrayList<>();
|
||||
for (StreamDescription sd : streams.values()) {
|
||||
if (tableNameFilter != null && !tableNameFilter.equals(sd.getTableName())) {
|
||||
continue;
|
||||
}
|
||||
if (region != null && !sd.getStreamArn().contains(":" + region + ":")) {
|
||||
continue;
|
||||
}
|
||||
result.add(sd);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public StreamDescription describeStream(String streamArn) {
|
||||
for (StreamDescription sd : streams.values()) {
|
||||
if (streamArn.equals(sd.getStreamArn())) {
|
||||
return sd;
|
||||
}
|
||||
}
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Stream not found: " + streamArn, 400);
|
||||
}
|
||||
|
||||
public String getShardIterator(String streamArn, String shardId,
|
||||
String iteratorType, String sequenceNumber) {
|
||||
StreamDescription sd = describeStream(streamArn);
|
||||
if (!"ENABLED".equals(sd.getStreamStatus()) && !"DISABLED".equals(sd.getStreamStatus())) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Stream not found: " + streamArn, 400);
|
||||
}
|
||||
|
||||
ConcurrentLinkedDeque<DynamoDbStreamRecord> deque = records.get(streamArn);
|
||||
List<DynamoDbStreamRecord> snapshot = deque != null ? new ArrayList<>(deque) : List.of();
|
||||
|
||||
int position = switch (iteratorType) {
|
||||
case "TRIM_HORIZON" -> 0;
|
||||
case "LATEST" -> snapshot.size();
|
||||
case "AT_SEQUENCE_NUMBER" -> findSequencePosition(snapshot, sequenceNumber, false);
|
||||
case "AFTER_SEQUENCE_NUMBER" -> findSequencePosition(snapshot, sequenceNumber, true);
|
||||
default -> throw new AwsException("ValidationException",
|
||||
"Unknown iterator type: " + iteratorType, 400);
|
||||
};
|
||||
|
||||
return encodeIterator(streamArn, position);
|
||||
}
|
||||
|
||||
private int findSequencePosition(List<DynamoDbStreamRecord> records, String targetSeq, boolean after) {
|
||||
for (int i = 0; i < records.size(); i++) {
|
||||
String seq = records.get(i).getSequenceNumber();
|
||||
int cmp = seq.compareTo(targetSeq);
|
||||
if (after ? cmp > 0 : cmp >= 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return records.size();
|
||||
}
|
||||
|
||||
public record GetRecordsResult(List<DynamoDbStreamRecord> records, String nextShardIterator) {}
|
||||
|
||||
public GetRecordsResult getRecords(String shardIterator, Integer limit) {
|
||||
String[] parts = decodeIterator(shardIterator);
|
||||
String streamArn = parts[0];
|
||||
int position = Integer.parseInt(parts[1]);
|
||||
|
||||
ConcurrentLinkedDeque<DynamoDbStreamRecord> deque = records.get(streamArn);
|
||||
List<DynamoDbStreamRecord> snapshot = deque != null ? new ArrayList<>(deque) : List.of();
|
||||
|
||||
int effectiveLimit = limit != null ? limit : 100;
|
||||
int end = Math.min(position + effectiveLimit, snapshot.size());
|
||||
List<DynamoDbStreamRecord> page = snapshot.subList(position, end);
|
||||
|
||||
String nextIterator = encodeIterator(streamArn, end);
|
||||
return new GetRecordsResult(new ArrayList<>(page), nextIterator);
|
||||
}
|
||||
|
||||
private String encodeIterator(String streamArn, int position) {
|
||||
String raw = streamArn + "|" + position;
|
||||
return Base64.getEncoder().encodeToString(raw.getBytes());
|
||||
}
|
||||
|
||||
private String[] decodeIterator(String iterator) {
|
||||
try {
|
||||
String raw = new String(Base64.getDecoder().decode(iterator));
|
||||
int lastPipe = raw.lastIndexOf('|');
|
||||
if (lastPipe < 0) {
|
||||
throw new AwsException("ValidationException", "Invalid shard iterator", 400);
|
||||
}
|
||||
return new String[]{raw.substring(0, lastPipe), raw.substring(lastPipe + 1)};
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("ValidationException", "Invalid shard iterator", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private String streamKey(String region, String tableName) {
|
||||
return region + "::" + tableName;
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.DynamoDbStreamRecord;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
|
||||
import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* DynamoDB Streams JSON protocol handler.
|
||||
* Handles requests with X-Amz-Target prefix {@code DynamoDBStreams_20120810.}.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class DynamoDbStreamsJsonHandler {
|
||||
|
||||
private static final org.jboss.logging.Logger LOG = org.jboss.logging.Logger.getLogger(DynamoDbStreamsJsonHandler.class);
|
||||
|
||||
private final DynamoDbStreamService streamService;
|
||||
private final DynamoDbService dynamoDbService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public DynamoDbStreamsJsonHandler(DynamoDbStreamService streamService, DynamoDbService dynamoDbService,
|
||||
ObjectMapper objectMapper) {
|
||||
this.streamService = streamService;
|
||||
this.dynamoDbService = dynamoDbService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
return switch (action) {
|
||||
case "ListStreams" -> handleListStreams(request, region);
|
||||
case "DescribeStream" -> handleDescribeStream(request, region);
|
||||
case "GetShardIterator" -> handleGetShardIterator(request, region);
|
||||
case "GetRecords" -> handleGetRecords(request, region);
|
||||
default -> {
|
||||
yield Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnknownOperationException", "Operation " + action + " is not supported."))
|
||||
.build();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private Response handleListStreams(JsonNode request, String region) {
|
||||
String tableNameFilter = request.has("TableName") ? request.get("TableName").asText() : null;
|
||||
|
||||
List<StreamDescription> streams = streamService.listStreams(tableNameFilter, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode streamList = objectMapper.createArrayNode();
|
||||
for (StreamDescription sd : streams) {
|
||||
ObjectNode entry = objectMapper.createObjectNode();
|
||||
entry.put("StreamArn", sd.getStreamArn());
|
||||
entry.put("StreamLabel", sd.getStreamLabel());
|
||||
entry.put("TableName", sd.getTableName());
|
||||
streamList.add(entry);
|
||||
}
|
||||
response.set("Streams", streamList);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeStream(JsonNode request, String region) {
|
||||
String streamArn = request.path("StreamArn").asText();
|
||||
StreamDescription sd = streamService.describeStream(streamArn);
|
||||
|
||||
// Fetch key schema from the table
|
||||
List<KeySchemaElement> keySchema = List.of();
|
||||
try {
|
||||
var table = dynamoDbService.describeTable(sd.getTableName(), region);
|
||||
keySchema = table.getKeySchema();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("StreamDescription", describeStreamToNode(sd, keySchema));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private ObjectNode describeStreamToNode(StreamDescription sd, List<KeySchemaElement> keySchema) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("StreamArn", sd.getStreamArn());
|
||||
node.put("StreamLabel", sd.getStreamLabel());
|
||||
node.put("StreamStatus", sd.getStreamStatus());
|
||||
node.put("StreamViewType", sd.getStreamViewType());
|
||||
node.put("TableName", sd.getTableName());
|
||||
node.put("CreationRequestDateTime", sd.getCreationDateTime().getEpochSecond());
|
||||
|
||||
ArrayNode keySchemaArray = objectMapper.createArrayNode();
|
||||
for (KeySchemaElement ks : keySchema) {
|
||||
ObjectNode ksNode = objectMapper.createObjectNode();
|
||||
ksNode.put("AttributeName", ks.getAttributeName());
|
||||
ksNode.put("KeyType", ks.getKeyType());
|
||||
keySchemaArray.add(ksNode);
|
||||
}
|
||||
node.set("KeySchema", keySchemaArray);
|
||||
|
||||
ArrayNode shards = objectMapper.createArrayNode();
|
||||
ObjectNode shard = objectMapper.createObjectNode();
|
||||
shard.put("ShardId", DynamoDbStreamService.SHARD_ID);
|
||||
ObjectNode seqRange = objectMapper.createObjectNode();
|
||||
seqRange.put("StartingSequenceNumber", sd.getStartingSequenceNumber());
|
||||
shard.set("SequenceNumberRange", seqRange);
|
||||
shards.add(shard);
|
||||
node.set("Shards", shards);
|
||||
|
||||
node.putNull("LastEvaluatedShardId");
|
||||
return node;
|
||||
}
|
||||
|
||||
private Response handleGetShardIterator(JsonNode request, String region) {
|
||||
String streamArn = request.path("StreamArn").asText();
|
||||
String shardId = request.path("ShardId").asText();
|
||||
String iteratorType = request.path("ShardIteratorType").asText();
|
||||
String sequenceNumber = request.has("SequenceNumber")
|
||||
? request.get("SequenceNumber").asText() : null;
|
||||
|
||||
String iterator = streamService.getShardIterator(streamArn, shardId, iteratorType, sequenceNumber);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("ShardIterator", iterator);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGetRecords(JsonNode request, String region) {
|
||||
String shardIterator = request.path("ShardIterator").asText();
|
||||
Integer limit = request.has("Limit") ? request.get("Limit").asInt() : null;
|
||||
|
||||
DynamoDbStreamService.GetRecordsResult result = streamService.getRecords(shardIterator, limit);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode recordsArray = objectMapper.createArrayNode();
|
||||
for (DynamoDbStreamRecord record : result.records()) {
|
||||
recordsArray.add(recordToNode(record));
|
||||
}
|
||||
response.set("Records", recordsArray);
|
||||
response.put("NextShardIterator", result.nextShardIterator());
|
||||
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private ObjectNode recordToNode(DynamoDbStreamRecord record) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("eventID", record.getEventId());
|
||||
node.put("eventName", record.getEventName());
|
||||
node.put("eventVersion", record.getEventVersion());
|
||||
node.put("eventSource", record.getEventSource());
|
||||
node.put("awsRegion", record.getAwsRegion());
|
||||
|
||||
ObjectNode dynamodb = objectMapper.createObjectNode();
|
||||
dynamodb.put("ApproximateCreationDateTime", record.getApproximateCreationDateTime());
|
||||
if (record.getKeys() != null) {
|
||||
dynamodb.set("Keys", record.getKeys());
|
||||
}
|
||||
if (record.getNewImage() != null) {
|
||||
dynamodb.set("NewImage", record.getNewImage());
|
||||
}
|
||||
if (record.getOldImage() != null) {
|
||||
dynamodb.set("OldImage", record.getOldImage());
|
||||
}
|
||||
dynamodb.put("SequenceNumber", record.getSequenceNumber());
|
||||
dynamodb.put("SizeBytes", 100);
|
||||
dynamodb.put("StreamViewType", record.getStreamViewType());
|
||||
node.set("dynamodb", dynamodb);
|
||||
|
||||
return node;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ApplicationScoped
|
||||
public class DynamoDbTtlService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(DynamoDbTtlService.class);
|
||||
|
||||
private final DynamoDbService dynamoDbService;
|
||||
private final ScheduledExecutorService scheduler;
|
||||
|
||||
@Inject
|
||||
public DynamoDbTtlService(DynamoDbService dynamoDbService) {
|
||||
this.dynamoDbService = dynamoDbService;
|
||||
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "dynamodb-ttl-sweeper");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void init() {
|
||||
scheduler.scheduleAtFixedRate(dynamoDbService::deleteExpiredItems, 60, 60, TimeUnit.SECONDS);
|
||||
LOG.infov("DynamoDB TTL sweeper scheduled (60s interval)");
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
scheduler.shutdownNow();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Thrown when a TransactWriteItems condition check fails.
|
||||
* Carries per-item cancellation reasons for the AWS response.
|
||||
*/
|
||||
public class TransactionCanceledException extends AwsException {
|
||||
|
||||
private final List<String> cancellationReasons;
|
||||
|
||||
public TransactionCanceledException(List<String> cancellationReasons) {
|
||||
super("TransactionCanceledException",
|
||||
"Transaction cancelled, please refer cancellation reasons for specific reasons [" +
|
||||
String.join(", ", cancellationReasons) + "]",
|
||||
400);
|
||||
this.cancellationReasons = cancellationReasons;
|
||||
}
|
||||
|
||||
public List<String> getCancellationReasons() {
|
||||
return cancellationReasons;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class AttributeDefinition {
|
||||
|
||||
private String attributeName;
|
||||
private String attributeType; // S, N, B
|
||||
|
||||
public AttributeDefinition() {}
|
||||
|
||||
public AttributeDefinition(String attributeName, String attributeType) {
|
||||
this.attributeName = attributeName;
|
||||
this.attributeType = attributeType;
|
||||
}
|
||||
|
||||
public String getAttributeName() { return attributeName; }
|
||||
public void setAttributeName(String attributeName) { this.attributeName = attributeName; }
|
||||
|
||||
public String getAttributeType() { return attributeType; }
|
||||
public void setAttributeType(String attributeType) { this.attributeType = attributeType; }
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class DynamoDbStreamRecord {
|
||||
|
||||
private String eventId;
|
||||
private String eventVersion;
|
||||
private String eventName;
|
||||
private String eventSource;
|
||||
private String awsRegion;
|
||||
private String sequenceNumber;
|
||||
private long approximateCreationDateTime;
|
||||
private JsonNode keys;
|
||||
private JsonNode newImage;
|
||||
private JsonNode oldImage;
|
||||
private String streamViewType;
|
||||
|
||||
public DynamoDbStreamRecord() {}
|
||||
|
||||
public String getEventId() { return eventId; }
|
||||
public void setEventId(String eventId) { this.eventId = eventId; }
|
||||
|
||||
public String getEventVersion() { return eventVersion; }
|
||||
public void setEventVersion(String eventVersion) { this.eventVersion = eventVersion; }
|
||||
|
||||
public String getEventName() { return eventName; }
|
||||
public void setEventName(String eventName) { this.eventName = eventName; }
|
||||
|
||||
public String getEventSource() { return eventSource; }
|
||||
public void setEventSource(String eventSource) { this.eventSource = eventSource; }
|
||||
|
||||
public String getAwsRegion() { return awsRegion; }
|
||||
public void setAwsRegion(String awsRegion) { this.awsRegion = awsRegion; }
|
||||
|
||||
public String getSequenceNumber() { return sequenceNumber; }
|
||||
public void setSequenceNumber(String sequenceNumber) { this.sequenceNumber = sequenceNumber; }
|
||||
|
||||
public long getApproximateCreationDateTime() { return approximateCreationDateTime; }
|
||||
public void setApproximateCreationDateTime(long approximateCreationDateTime) {
|
||||
this.approximateCreationDateTime = approximateCreationDateTime;
|
||||
}
|
||||
|
||||
public JsonNode getKeys() { return keys; }
|
||||
public void setKeys(JsonNode keys) { this.keys = keys; }
|
||||
|
||||
public JsonNode getNewImage() { return newImage; }
|
||||
public void setNewImage(JsonNode newImage) { this.newImage = newImage; }
|
||||
|
||||
public JsonNode getOldImage() { return oldImage; }
|
||||
public void setOldImage(JsonNode oldImage) { this.oldImage = oldImage; }
|
||||
|
||||
public String getStreamViewType() { return streamViewType; }
|
||||
public void setStreamViewType(String streamViewType) { this.streamViewType = streamViewType; }
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class GlobalSecondaryIndex {
|
||||
|
||||
private String indexName;
|
||||
private List<KeySchemaElement> keySchema;
|
||||
private String indexArn;
|
||||
private String projectionType;
|
||||
|
||||
public GlobalSecondaryIndex() {}
|
||||
|
||||
public GlobalSecondaryIndex(String indexName, List<KeySchemaElement> keySchema,
|
||||
String indexArn, String projectionType) {
|
||||
this.indexName = indexName;
|
||||
this.keySchema = keySchema;
|
||||
this.indexArn = indexArn;
|
||||
this.projectionType = projectionType != null ? projectionType : "ALL";
|
||||
}
|
||||
|
||||
public String getIndexName() { return indexName; }
|
||||
public void setIndexName(String indexName) { this.indexName = indexName; }
|
||||
|
||||
public List<KeySchemaElement> getKeySchema() { return keySchema; }
|
||||
public void setKeySchema(List<KeySchemaElement> keySchema) { this.keySchema = keySchema; }
|
||||
|
||||
public String getIndexArn() { return indexArn; }
|
||||
public void setIndexArn(String indexArn) { this.indexArn = indexArn; }
|
||||
|
||||
public String getProjectionType() { return projectionType; }
|
||||
public void setProjectionType(String projectionType) { this.projectionType = projectionType; }
|
||||
|
||||
public String getPartitionKeyName() {
|
||||
return keySchema.stream()
|
||||
.filter(k -> "HASH".equals(k.getKeyType()))
|
||||
.map(KeySchemaElement::getAttributeName)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
}
|
||||
|
||||
public String getSortKeyName() {
|
||||
return keySchema.stream()
|
||||
.filter(k -> "RANGE".equals(k.getKeyType()))
|
||||
.map(KeySchemaElement::getAttributeName)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class KeySchemaElement {
|
||||
|
||||
private String attributeName;
|
||||
private String keyType; // HASH or RANGE
|
||||
|
||||
public KeySchemaElement() {}
|
||||
|
||||
public KeySchemaElement(String attributeName, String keyType) {
|
||||
this.attributeName = attributeName;
|
||||
this.keyType = keyType;
|
||||
}
|
||||
|
||||
public String getAttributeName() { return attributeName; }
|
||||
public void setAttributeName(String attributeName) { this.attributeName = attributeName; }
|
||||
|
||||
public String getKeyType() { return keyType; }
|
||||
public void setKeyType(String keyType) { this.keyType = keyType; }
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Represents a Local Secondary Index (LSI).
|
||||
* LSIs share the same partition key (HASH) as the base table,
|
||||
* but have a different sort key (RANGE).
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class LocalSecondaryIndex {
|
||||
|
||||
private String indexName;
|
||||
private List<KeySchemaElement> keySchema;
|
||||
private String indexArn;
|
||||
private String projectionType;
|
||||
private long indexSizeBytes;
|
||||
private long itemCount;
|
||||
|
||||
public LocalSecondaryIndex() {}
|
||||
|
||||
public LocalSecondaryIndex(String indexName, List<KeySchemaElement> keySchema,
|
||||
String indexArn, String projectionType) {
|
||||
this.indexName = indexName;
|
||||
this.keySchema = keySchema;
|
||||
this.indexArn = indexArn;
|
||||
this.projectionType = projectionType != null ? projectionType : "ALL";
|
||||
}
|
||||
|
||||
public String getIndexName() { return indexName; }
|
||||
public void setIndexName(String indexName) { this.indexName = indexName; }
|
||||
|
||||
public List<KeySchemaElement> getKeySchema() { return keySchema; }
|
||||
public void setKeySchema(List<KeySchemaElement> keySchema) { this.keySchema = keySchema; }
|
||||
|
||||
public String getIndexArn() { return indexArn; }
|
||||
public void setIndexArn(String indexArn) { this.indexArn = indexArn; }
|
||||
|
||||
public String getProjectionType() { return projectionType; }
|
||||
public void setProjectionType(String projectionType) { this.projectionType = projectionType; }
|
||||
|
||||
public long getIndexSizeBytes() { return indexSizeBytes; }
|
||||
public void setIndexSizeBytes(long indexSizeBytes) { this.indexSizeBytes = indexSizeBytes; }
|
||||
|
||||
public long getItemCount() { return itemCount; }
|
||||
public void setItemCount(long itemCount) { this.itemCount = itemCount; }
|
||||
|
||||
public String getPartitionKeyName() {
|
||||
return keySchema.stream()
|
||||
.filter(k -> "HASH".equals(k.getKeyType()))
|
||||
.map(KeySchemaElement::getAttributeName)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
}
|
||||
|
||||
public String getSortKeyName() {
|
||||
return keySchema.stream()
|
||||
.filter(k -> "RANGE".equals(k.getKeyType()))
|
||||
.map(KeySchemaElement::getAttributeName)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class ProvisionedThroughput {
|
||||
|
||||
private long readCapacityUnits;
|
||||
private long writeCapacityUnits;
|
||||
private Instant lastIncreaseDateTime;
|
||||
private Instant lastDecreaseDateTime;
|
||||
private long numberOfDecreasesToday;
|
||||
|
||||
public ProvisionedThroughput() {}
|
||||
|
||||
public ProvisionedThroughput(long readCapacityUnits, long writeCapacityUnits) {
|
||||
this.readCapacityUnits = readCapacityUnits;
|
||||
this.writeCapacityUnits = writeCapacityUnits;
|
||||
this.numberOfDecreasesToday = 0;
|
||||
}
|
||||
|
||||
public long getReadCapacityUnits() { return readCapacityUnits; }
|
||||
public void setReadCapacityUnits(long readCapacityUnits) { this.readCapacityUnits = readCapacityUnits; }
|
||||
|
||||
public long getWriteCapacityUnits() { return writeCapacityUnits; }
|
||||
public void setWriteCapacityUnits(long writeCapacityUnits) { this.writeCapacityUnits = writeCapacityUnits; }
|
||||
|
||||
public Instant getLastIncreaseDateTime() { return lastIncreaseDateTime; }
|
||||
public void setLastIncreaseDateTime(Instant lastIncreaseDateTime) { this.lastIncreaseDateTime = lastIncreaseDateTime; }
|
||||
|
||||
public Instant getLastDecreaseDateTime() { return lastDecreaseDateTime; }
|
||||
public void setLastDecreaseDateTime(Instant lastDecreaseDateTime) { this.lastDecreaseDateTime = lastDecreaseDateTime; }
|
||||
|
||||
public long getNumberOfDecreasesToday() { return numberOfDecreasesToday; }
|
||||
public void setNumberOfDecreasesToday(long numberOfDecreasesToday) { this.numberOfDecreasesToday = numberOfDecreasesToday; }
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class StreamDescription {
|
||||
|
||||
private String streamArn;
|
||||
private String streamLabel;
|
||||
private String streamStatus;
|
||||
private String streamViewType;
|
||||
private String tableName;
|
||||
private Instant creationDateTime;
|
||||
private String startingSequenceNumber;
|
||||
|
||||
public StreamDescription() {}
|
||||
|
||||
public String getStreamArn() { return streamArn; }
|
||||
public void setStreamArn(String streamArn) { this.streamArn = streamArn; }
|
||||
|
||||
public String getStreamLabel() { return streamLabel; }
|
||||
public void setStreamLabel(String streamLabel) { this.streamLabel = streamLabel; }
|
||||
|
||||
public String getStreamStatus() { return streamStatus; }
|
||||
public void setStreamStatus(String streamStatus) { this.streamStatus = streamStatus; }
|
||||
|
||||
public String getStreamViewType() { return streamViewType; }
|
||||
public void setStreamViewType(String streamViewType) { this.streamViewType = streamViewType; }
|
||||
|
||||
public String getTableName() { return tableName; }
|
||||
public void setTableName(String tableName) { this.tableName = tableName; }
|
||||
|
||||
public Instant getCreationDateTime() { return creationDateTime; }
|
||||
public void setCreationDateTime(Instant creationDateTime) { this.creationDateTime = creationDateTime; }
|
||||
|
||||
public String getStartingSequenceNumber() { return startingSequenceNumber; }
|
||||
public void setStartingSequenceNumber(String startingSequenceNumber) {
|
||||
this.startingSequenceNumber = startingSequenceNumber;
|
||||
}
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
package io.github.hectorvent.floci.services.dynamodb.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Represents a DynamoDB table definition (metadata, not items).
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class TableDefinition {
|
||||
|
||||
private String tableName;
|
||||
private List<KeySchemaElement> keySchema;
|
||||
private List<AttributeDefinition> attributeDefinitions;
|
||||
private String tableStatus;
|
||||
private Instant creationDateTime;
|
||||
private long itemCount;
|
||||
private long tableSizeBytes;
|
||||
private ProvisionedThroughput provisionedThroughput;
|
||||
private String tableArn;
|
||||
private Map<String, String> tags;
|
||||
private List<GlobalSecondaryIndex> globalSecondaryIndexes;
|
||||
private List<LocalSecondaryIndex> localSecondaryIndexes;
|
||||
private String ttlAttributeName;
|
||||
private boolean ttlEnabled;
|
||||
private boolean streamEnabled;
|
||||
private String streamArn;
|
||||
private String streamViewType;
|
||||
|
||||
public TableDefinition() {
|
||||
this.keySchema = new ArrayList<>();
|
||||
this.attributeDefinitions = new ArrayList<>();
|
||||
this.tags = new HashMap<>();
|
||||
this.globalSecondaryIndexes = new ArrayList<>();
|
||||
this.localSecondaryIndexes = new ArrayList<>();
|
||||
}
|
||||
|
||||
public TableDefinition(String tableName,
|
||||
List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> attributeDefinitions) {
|
||||
this(tableName, keySchema, attributeDefinitions, "us-east-1", "000000000000");
|
||||
}
|
||||
|
||||
public TableDefinition(String tableName,
|
||||
List<KeySchemaElement> keySchema,
|
||||
List<AttributeDefinition> attributeDefinitions,
|
||||
String region, String accountId) {
|
||||
this.tableName = tableName;
|
||||
this.keySchema = keySchema;
|
||||
this.attributeDefinitions = attributeDefinitions;
|
||||
this.tableStatus = "ACTIVE";
|
||||
this.creationDateTime = Instant.now();
|
||||
this.itemCount = 0;
|
||||
this.tableSizeBytes = 0;
|
||||
this.tableArn = "arn:aws:dynamodb:" + region + ":" + accountId + ":table/" + tableName;
|
||||
this.provisionedThroughput = new ProvisionedThroughput(5, 5);
|
||||
this.tags = new HashMap<>();
|
||||
this.globalSecondaryIndexes = new ArrayList<>();
|
||||
this.localSecondaryIndexes = new ArrayList<>();
|
||||
}
|
||||
|
||||
public String getTableName() { return tableName; }
|
||||
public void setTableName(String tableName) { this.tableName = tableName; }
|
||||
|
||||
public List<KeySchemaElement> getKeySchema() { return keySchema; }
|
||||
public void setKeySchema(List<KeySchemaElement> keySchema) { this.keySchema = keySchema; }
|
||||
|
||||
public List<AttributeDefinition> getAttributeDefinitions() { return attributeDefinitions; }
|
||||
public void setAttributeDefinitions(List<AttributeDefinition> attributeDefinitions) { this.attributeDefinitions = attributeDefinitions; }
|
||||
|
||||
public String getTableStatus() { return tableStatus; }
|
||||
public void setTableStatus(String tableStatus) { this.tableStatus = tableStatus; }
|
||||
|
||||
public Instant getCreationDateTime() { return creationDateTime; }
|
||||
public void setCreationDateTime(Instant creationDateTime) { this.creationDateTime = creationDateTime; }
|
||||
|
||||
public long getItemCount() { return itemCount; }
|
||||
public void setItemCount(long itemCount) { this.itemCount = itemCount; }
|
||||
|
||||
public long getTableSizeBytes() { return tableSizeBytes; }
|
||||
public void setTableSizeBytes(long tableSizeBytes) { this.tableSizeBytes = tableSizeBytes; }
|
||||
|
||||
public ProvisionedThroughput getProvisionedThroughput() { return provisionedThroughput; }
|
||||
public void setProvisionedThroughput(ProvisionedThroughput provisionedThroughput) { this.provisionedThroughput = provisionedThroughput; }
|
||||
|
||||
public String getTableArn() { return tableArn; }
|
||||
public void setTableArn(String tableArn) { this.tableArn = tableArn; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
|
||||
public List<GlobalSecondaryIndex> getGlobalSecondaryIndexes() { return globalSecondaryIndexes; }
|
||||
public void setGlobalSecondaryIndexes(List<GlobalSecondaryIndex> globalSecondaryIndexes) {
|
||||
this.globalSecondaryIndexes = globalSecondaryIndexes != null ? globalSecondaryIndexes : new ArrayList<>();
|
||||
}
|
||||
|
||||
public List<LocalSecondaryIndex> getLocalSecondaryIndexes() { return localSecondaryIndexes; }
|
||||
public void setLocalSecondaryIndexes(List<LocalSecondaryIndex> localSecondaryIndexes) {
|
||||
this.localSecondaryIndexes = localSecondaryIndexes != null ? localSecondaryIndexes : new ArrayList<>();
|
||||
}
|
||||
|
||||
public String getTtlAttributeName() { return ttlAttributeName; }
|
||||
public void setTtlAttributeName(String ttlAttributeName) { this.ttlAttributeName = ttlAttributeName; }
|
||||
|
||||
public boolean isTtlEnabled() { return ttlEnabled; }
|
||||
public void setTtlEnabled(boolean ttlEnabled) { this.ttlEnabled = ttlEnabled; }
|
||||
|
||||
public boolean isStreamEnabled() { return streamEnabled; }
|
||||
public void setStreamEnabled(boolean streamEnabled) { this.streamEnabled = streamEnabled; }
|
||||
|
||||
public String getStreamArn() { return streamArn; }
|
||||
public void setStreamArn(String streamArn) { this.streamArn = streamArn; }
|
||||
|
||||
public String getStreamViewType() { return streamViewType; }
|
||||
public void setStreamViewType(String streamViewType) { this.streamViewType = streamViewType; }
|
||||
|
||||
/** Returns the partition key attribute name. */
|
||||
public String getPartitionKeyName() {
|
||||
return keySchema.stream()
|
||||
.filter(k -> "HASH".equals(k.getKeyType()))
|
||||
.map(KeySchemaElement::getAttributeName)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
}
|
||||
|
||||
/** Returns the sort key attribute name, or null if none. */
|
||||
public String getSortKeyName() {
|
||||
return keySchema.stream()
|
||||
.filter(k -> "RANGE".equals(k.getKeyType()))
|
||||
.map(KeySchemaElement::getAttributeName)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public Optional<GlobalSecondaryIndex> findGsi(String indexName) {
|
||||
if (globalSecondaryIndexes == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return globalSecondaryIndexes.stream()
|
||||
.filter(g -> indexName.equals(g.getIndexName()))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public Optional<LocalSecondaryIndex> findLsi(String indexName) {
|
||||
if (localSecondaryIndexes == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return localSecondaryIndexes.stream()
|
||||
.filter(l -> indexName.equals(l.getIndexName()))
|
||||
.findFirst();
|
||||
}
|
||||
}
|
||||
+311
@@ -0,0 +1,311 @@
|
||||
package io.github.hectorvent.floci.services.elasticache;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
|
||||
import io.github.hectorvent.floci.services.elasticache.proxy.SigV4Validator;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Query-protocol handler for all ElastiCache actions (form-encoded POST, XML response).
|
||||
* Covers both the management plane (replication groups, users) and the auth-token
|
||||
* validation endpoint used by the Redis IAM auth flow.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ElastiCacheQueryHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ElastiCacheQueryHandler.class);
|
||||
|
||||
private final SigV4Validator sigV4Validator;
|
||||
private final ElastiCacheService service;
|
||||
|
||||
@Inject
|
||||
public ElastiCacheQueryHandler(SigV4Validator sigV4Validator, ElastiCacheService service) {
|
||||
this.sigV4Validator = sigV4Validator;
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
public Response handle(String action, MultivaluedMap<String, String> params) {
|
||||
LOG.debugv("ElastiCache action: {0}", action);
|
||||
return switch (action) {
|
||||
case "ValidateIamAuthToken" -> handleValidateIamAuthToken(params);
|
||||
case "CreateReplicationGroup" -> handleCreateReplicationGroup(params);
|
||||
case "DescribeReplicationGroups" -> handleDescribeReplicationGroups(params);
|
||||
case "DeleteReplicationGroup" -> handleDeleteReplicationGroup(params);
|
||||
case "CreateUser" -> handleCreateUser(params);
|
||||
case "DescribeUsers" -> handleDescribeUsers(params);
|
||||
case "ModifyUser" -> handleModifyUser(params);
|
||||
case "DeleteUser" -> handleDeleteUser(params);
|
||||
default -> AwsQueryResponse.error("UnsupportedOperation",
|
||||
"Operation " + action + " is not supported.", AwsNamespaces.EC, 400);
|
||||
};
|
||||
}
|
||||
|
||||
// ── Replication Groups ────────────────────────────────────────────────────
|
||||
|
||||
private Response handleCreateReplicationGroup(MultivaluedMap<String, String> params) {
|
||||
String groupId = params.getFirst("ReplicationGroupId");
|
||||
String description = params.getFirst("ReplicationGroupDescription");
|
||||
String authToken = params.getFirst("AuthToken");
|
||||
|
||||
if (groupId == null || groupId.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue",
|
||||
"ReplicationGroupId is required.", AwsNamespaces.EC, 400);
|
||||
}
|
||||
|
||||
String transitEncryption = params.getFirst("TransitEncryptionEnabled");
|
||||
AuthMode authMode;
|
||||
if (authToken != null && !authToken.isBlank()) {
|
||||
authMode = AuthMode.PASSWORD;
|
||||
} else if ("true".equalsIgnoreCase(transitEncryption)) {
|
||||
authMode = AuthMode.IAM;
|
||||
} else {
|
||||
authMode = AuthMode.NO_AUTH;
|
||||
}
|
||||
|
||||
try {
|
||||
ReplicationGroup group = service.createReplicationGroup(
|
||||
groupId, description != null ? description : "", authMode, authToken);
|
||||
String result = replicationGroupXml(group);
|
||||
return Response.ok(AwsQueryResponse.envelope("CreateReplicationGroup", AwsNamespaces.EC, result)).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleDescribeReplicationGroups(MultivaluedMap<String, String> params) {
|
||||
String filterId = params.getFirst("ReplicationGroupId");
|
||||
try {
|
||||
Collection<ReplicationGroup> groups = service.listReplicationGroups(filterId);
|
||||
var xml = new XmlBuilder().start("ReplicationGroups");
|
||||
for (ReplicationGroup g : groups) {
|
||||
xml.raw(replicationGroupXml(g));
|
||||
}
|
||||
xml.end("ReplicationGroups").start("Marker").end("Marker");
|
||||
return Response.ok(AwsQueryResponse.envelope("DescribeReplicationGroups", AwsNamespaces.EC, xml.build())).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleDeleteReplicationGroup(MultivaluedMap<String, String> params) {
|
||||
String groupId = params.getFirst("ReplicationGroupId");
|
||||
if (groupId == null || groupId.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue",
|
||||
"ReplicationGroupId is required.", AwsNamespaces.EC, 400);
|
||||
}
|
||||
try {
|
||||
ReplicationGroup group = service.getReplicationGroup(groupId);
|
||||
service.deleteReplicationGroup(groupId);
|
||||
String result = replicationGroupXml(group);
|
||||
return Response.ok(AwsQueryResponse.envelope("DeleteReplicationGroup", AwsNamespaces.EC, result)).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
// ── Users ─────────────────────────────────────────────────────────────────
|
||||
|
||||
private Response handleCreateUser(MultivaluedMap<String, String> params) {
|
||||
String userId = params.getFirst("UserId");
|
||||
String userName = params.getFirst("UserName");
|
||||
String accessString = params.getFirst("AccessString");
|
||||
String authModeType = params.getFirst("AuthenticationMode.Type");
|
||||
|
||||
if (userId == null || userId.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue", "UserId is required.", AwsNamespaces.EC, 400);
|
||||
}
|
||||
if (userName == null || userName.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue", "UserName is required.", AwsNamespaces.EC, 400);
|
||||
}
|
||||
|
||||
AuthMode authMode;
|
||||
List<String> passwords = new ArrayList<>();
|
||||
if ("iam".equalsIgnoreCase(authModeType)) {
|
||||
authMode = AuthMode.IAM;
|
||||
} else if ("password".equalsIgnoreCase(authModeType)) {
|
||||
authMode = AuthMode.PASSWORD;
|
||||
passwords = extractPasswordList(params, "AuthenticationMode.Passwords.member.");
|
||||
} else {
|
||||
authMode = AuthMode.NO_AUTH;
|
||||
}
|
||||
|
||||
try {
|
||||
ElastiCacheUser user = service.createUser(userId, userName, authMode, passwords, accessString);
|
||||
return Response.ok(AwsQueryResponse.envelope("CreateUser", AwsNamespaces.EC, userXml(user))).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleDescribeUsers(MultivaluedMap<String, String> params) {
|
||||
String filterId = params.getFirst("UserId");
|
||||
try {
|
||||
Collection<ElastiCacheUser> users = service.listUsers(filterId);
|
||||
var xml = new XmlBuilder().start("Users");
|
||||
for (ElastiCacheUser u : users) {
|
||||
xml.start("member").raw(userXml(u)).end("member");
|
||||
}
|
||||
xml.end("Users").start("Marker").end("Marker");
|
||||
return Response.ok(AwsQueryResponse.envelope("DescribeUsers", AwsNamespaces.EC, xml.build())).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleModifyUser(MultivaluedMap<String, String> params) {
|
||||
String userId = params.getFirst("UserId");
|
||||
if (userId == null || userId.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue", "UserId is required.", AwsNamespaces.EC, 400);
|
||||
}
|
||||
List<String> passwords = extractPasswordList(params, "AuthenticationMode.Passwords.member.");
|
||||
try {
|
||||
ElastiCacheUser user = service.modifyUser(userId, passwords.isEmpty() ? null : passwords);
|
||||
return Response.ok(AwsQueryResponse.envelope("ModifyUser", AwsNamespaces.EC, userXml(user))).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleDeleteUser(MultivaluedMap<String, String> params) {
|
||||
String userId = params.getFirst("UserId");
|
||||
if (userId == null || userId.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameterValue", "UserId is required.", AwsNamespaces.EC, 400);
|
||||
}
|
||||
try {
|
||||
ElastiCacheUser user = service.getUser(userId);
|
||||
service.deleteUser(userId);
|
||||
return Response.ok(AwsQueryResponse.envelope("DeleteUser", AwsNamespaces.EC, userXml(user))).build();
|
||||
} catch (AwsException e) {
|
||||
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.EC, e.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
// ── IAM Token Validation ──────────────────────────────────────────────────
|
||||
|
||||
private Response handleValidateIamAuthToken(MultivaluedMap<String, String> params) {
|
||||
String token = params.getFirst("Token");
|
||||
if (token == null || token.isBlank()) {
|
||||
return AwsQueryResponse.error("InvalidParameter", "Token parameter is required.", AwsNamespaces.EC, 400);
|
||||
}
|
||||
try {
|
||||
boolean valid = sigV4Validator.validate(token, null);
|
||||
if (!valid) {
|
||||
return AwsQueryResponse.error("SignatureDoesNotMatch",
|
||||
"The request signature does not match.", AwsNamespaces.EC, 403);
|
||||
}
|
||||
String clusterId = extractUriHost(token);
|
||||
String userId = extractQueryParam(token, "User");
|
||||
LOG.infov("ElastiCache IAM token validated: clusterId={0} userId={1}", clusterId, userId);
|
||||
String result = new XmlBuilder()
|
||||
.elem("Valid", true)
|
||||
.elem("ClusterId", clusterId)
|
||||
.elem("UserId", userId)
|
||||
.build();
|
||||
return Response.ok(AwsQueryResponse.envelope("ValidateIamAuthToken", AwsNamespaces.EC, result)).build();
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("ElastiCache token validation error: {0}", e.getMessage());
|
||||
return AwsQueryResponse.error("InvalidToken",
|
||||
"Failed to validate token: " + e.getMessage(), AwsNamespaces.EC, 400);
|
||||
}
|
||||
}
|
||||
|
||||
// ── XML helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
private String replicationGroupXml(ReplicationGroup g) {
|
||||
Endpoint ep = g.getConfigurationEndpoint();
|
||||
boolean authTokenEnabled = g.getAuthMode() == AuthMode.PASSWORD;
|
||||
var xml = new XmlBuilder()
|
||||
.start("ReplicationGroup")
|
||||
.elem("ReplicationGroupId", g.getReplicationGroupId())
|
||||
.elem("Description", g.getDescription())
|
||||
.elem("Status", g.getStatus().name().toLowerCase())
|
||||
.elem("AuthTokenEnabled", authTokenEnabled)
|
||||
.elem("TransitEncryptionEnabled", authTokenEnabled)
|
||||
.elem("AtRestEncryptionEnabled", false)
|
||||
.elem("ClusterEnabled", false)
|
||||
.elem("MultiAZ", "disabled")
|
||||
.elem("AutomaticFailover", "disabled")
|
||||
.elem("SnapshotRetentionLimit", 0L);
|
||||
if (ep != null) {
|
||||
xml.start("ConfigurationEndpoint")
|
||||
.elem("Address", ep.address())
|
||||
.elem("Port", (long) ep.port())
|
||||
.end("ConfigurationEndpoint");
|
||||
}
|
||||
return xml.end("ReplicationGroup").build();
|
||||
}
|
||||
|
||||
private String userXml(ElastiCacheUser u) {
|
||||
String authType = switch (u.getAuthMode()) {
|
||||
case IAM -> "iam";
|
||||
case PASSWORD -> "password";
|
||||
case NO_AUTH -> "no-password-required";
|
||||
};
|
||||
int pwCount = (u.getPasswords() != null) ? u.getPasswords().size() : 0;
|
||||
return new XmlBuilder()
|
||||
.elem("UserId", u.getUserId())
|
||||
.elem("UserName", u.getUserName())
|
||||
.elem("Status", u.getStatus())
|
||||
.elem("AccessString", u.getAccessString())
|
||||
.start("Authentication")
|
||||
.elem("Type", authType)
|
||||
.elem("PasswordCount", (long) pwCount)
|
||||
.end("Authentication")
|
||||
.elem("Engine", "redis")
|
||||
.elem("MinimumEngineVersion", "6.0")
|
||||
.start("UserGroupIds").end("UserGroupIds")
|
||||
.elem("ARN", "arn:aws:elasticache:us-east-1:000000000000:user:" + u.getUserId())
|
||||
.build();
|
||||
}
|
||||
|
||||
private static List<String> extractPasswordList(MultivaluedMap<String, String> params, String prefix) {
|
||||
List<String> passwords = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String pw = params.getFirst(prefix + i);
|
||||
if (pw == null) {
|
||||
break;
|
||||
}
|
||||
passwords.add(pw);
|
||||
}
|
||||
return passwords;
|
||||
}
|
||||
|
||||
private static String extractUriHost(String token) {
|
||||
try {
|
||||
return java.net.URI.create("http://" + token).getHost();
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static String extractQueryParam(String token, String name) {
|
||||
try {
|
||||
String rawQuery = java.net.URI.create("http://" + token).getRawQuery();
|
||||
if (rawQuery == null) {
|
||||
return "";
|
||||
}
|
||||
for (String pair : rawQuery.split("&")) {
|
||||
int eq = pair.indexOf('=');
|
||||
if (eq >= 0 && name.equals(pair.substring(0, eq))) {
|
||||
return java.net.URLDecoder.decode(pair.substring(eq + 1),
|
||||
java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
package io.github.hectorvent.floci.services.elasticache;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerManager;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.Endpoint;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ElastiCacheUser;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroup;
|
||||
import io.github.hectorvent.floci.services.elasticache.model.ReplicationGroupStatus;
|
||||
import io.github.hectorvent.floci.services.elasticache.proxy.ElastiCacheProxyManager;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Core ElastiCache business logic — replication groups and users.
|
||||
* Creates Valkey containers and auth proxies on group creation.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ElastiCacheService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ElastiCacheService.class);
|
||||
|
||||
private final StorageBackend<String, ReplicationGroup> groups;
|
||||
private final StorageBackend<String, ElastiCacheUser> users;
|
||||
private final ElastiCacheContainerManager containerManager;
|
||||
private final ElastiCacheProxyManager proxyManager;
|
||||
private final EmulatorConfig config;
|
||||
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
|
||||
|
||||
@Inject
|
||||
public ElastiCacheService(ElastiCacheContainerManager containerManager,
|
||||
ElastiCacheProxyManager proxyManager,
|
||||
EmulatorConfig config) {
|
||||
this.containerManager = containerManager;
|
||||
this.proxyManager = proxyManager;
|
||||
this.config = config;
|
||||
this.groups = new InMemoryStorage<>();
|
||||
this.users = new InMemoryStorage<>();
|
||||
}
|
||||
|
||||
public ReplicationGroup createReplicationGroup(String groupId, String description,
|
||||
AuthMode authMode, String authToken) {
|
||||
if (groups.get(groupId).isPresent()) {
|
||||
throw new AwsException("ReplicationGroupAlreadyExistsFault",
|
||||
"Replication group " + groupId + " already exists.", 400);
|
||||
}
|
||||
|
||||
int proxyPort = allocateProxyPort();
|
||||
String image = config.services().elasticache().defaultImage();
|
||||
|
||||
LOG.infov("Creating replication group {0} with authMode={1} on proxy port {2}",
|
||||
groupId, authMode, proxyPort);
|
||||
|
||||
ElastiCacheContainerHandle handle = containerManager.start(groupId, image);
|
||||
|
||||
Endpoint endpoint = new Endpoint("localhost", proxyPort);
|
||||
ReplicationGroup group = new ReplicationGroup(
|
||||
groupId, description, ReplicationGroupStatus.AVAILABLE,
|
||||
authMode, endpoint, Instant.now(), proxyPort);
|
||||
group.setContainerId(handle.getContainerId());
|
||||
group.setContainerHost(handle.getHost());
|
||||
group.setContainerPort(handle.getPort());
|
||||
group.setAuthToken(authToken);
|
||||
|
||||
proxyManager.startProxy(groupId, authMode, proxyPort,
|
||||
handle.getHost(), handle.getPort(),
|
||||
(username, password) -> validatePassword(groupId, username, password));
|
||||
|
||||
groups.put(groupId, group);
|
||||
LOG.infov("Replication group {0} created, endpoint=localhost:{1}", groupId, proxyPort);
|
||||
return group;
|
||||
}
|
||||
|
||||
public ReplicationGroup getReplicationGroup(String groupId) {
|
||||
return groups.get(groupId).orElseThrow(() ->
|
||||
new AwsException("ReplicationGroupNotFoundFault",
|
||||
"Replication group " + groupId + " not found.", 404));
|
||||
}
|
||||
|
||||
public Collection<ReplicationGroup> listReplicationGroups(String filterGroupId) {
|
||||
if (filterGroupId != null && !filterGroupId.isBlank()) {
|
||||
return groups.get(filterGroupId)
|
||||
.map(List::of)
|
||||
.orElse(List.of());
|
||||
}
|
||||
return groups.scan(k -> true);
|
||||
}
|
||||
|
||||
public void deleteReplicationGroup(String groupId) {
|
||||
ReplicationGroup group = groups.get(groupId).orElseThrow(() ->
|
||||
new AwsException("ReplicationGroupNotFoundFault",
|
||||
"Replication group " + groupId + " not found.", 404));
|
||||
|
||||
group.setStatus(ReplicationGroupStatus.DELETING);
|
||||
groups.put(groupId, group);
|
||||
|
||||
proxyManager.stopProxy(groupId);
|
||||
|
||||
if (group.getContainerId() != null) {
|
||||
containerManager.stop(new ElastiCacheContainerHandle(
|
||||
group.getContainerId(), groupId, group.getContainerHost(), group.getContainerPort()));
|
||||
}
|
||||
|
||||
releaseProxyPort(group.getProxyPort());
|
||||
groups.delete(groupId);
|
||||
LOG.infov("Replication group {0} deleted", groupId);
|
||||
}
|
||||
|
||||
public ElastiCacheUser createUser(String userId, String userName, AuthMode authMode,
|
||||
List<String> passwords, String accessString) {
|
||||
if (users.get(userId).isPresent()) {
|
||||
throw new AwsException("UserAlreadyExistsFault",
|
||||
"User " + userId + " already exists.", 400);
|
||||
}
|
||||
|
||||
ElastiCacheUser user = new ElastiCacheUser(
|
||||
userId, userName, authMode,
|
||||
passwords != null ? passwords : List.of(),
|
||||
accessString != null ? accessString : "on ~* +@all",
|
||||
"active", Instant.now());
|
||||
|
||||
users.put(userId, user);
|
||||
LOG.infov("ElastiCache user {0} created with authMode={1}", userId, authMode);
|
||||
return user;
|
||||
}
|
||||
|
||||
public ElastiCacheUser getUser(String userId) {
|
||||
return users.get(userId).orElseThrow(() ->
|
||||
new AwsException("UserNotFoundFault", "User " + userId + " not found.", 404));
|
||||
}
|
||||
|
||||
public Collection<ElastiCacheUser> listUsers(String filterUserId) {
|
||||
if (filterUserId != null && !filterUserId.isBlank()) {
|
||||
return users.get(filterUserId)
|
||||
.map(List::of)
|
||||
.orElse(List.of());
|
||||
}
|
||||
return users.scan(k -> true);
|
||||
}
|
||||
|
||||
public ElastiCacheUser modifyUser(String userId, List<String> passwords) {
|
||||
ElastiCacheUser user = getUser(userId);
|
||||
if (passwords != null) {
|
||||
user.setPasswords(passwords);
|
||||
}
|
||||
users.put(userId, user);
|
||||
return user;
|
||||
}
|
||||
|
||||
public void deleteUser(String userId) {
|
||||
if (users.get(userId).isEmpty()) {
|
||||
throw new AwsException("UserNotFoundFault", "User " + userId + " not found.", 404);
|
||||
}
|
||||
users.delete(userId);
|
||||
LOG.infov("ElastiCache user {0} deleted", userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a Redis AUTH password for the given group.
|
||||
* Checks the group-level authToken first, then falls back to per-user passwords.
|
||||
* Called by the TCP auth proxy for PASSWORD-mode groups.
|
||||
*/
|
||||
public boolean validatePassword(String groupId, String username, String password) {
|
||||
if (username == null || username.isEmpty()) {
|
||||
// AUTH password form: check group-level authToken first
|
||||
ReplicationGroup group = groups.get(groupId).orElse(null);
|
||||
if (group != null && group.getAuthToken() != null
|
||||
&& password.equals(group.getAuthToken())) {
|
||||
return true;
|
||||
}
|
||||
// Fall back to any PASSWORD user matching this password
|
||||
return users.scan(k -> true).stream()
|
||||
.filter(u -> u.getAuthMode() == AuthMode.PASSWORD)
|
||||
.anyMatch(u -> u.getPasswords() != null && u.getPasswords().contains(password));
|
||||
}
|
||||
// AUTH username password form: find user by userName
|
||||
return users.scan(k -> true).stream()
|
||||
.filter(u -> username.equals(u.getUserName()) && u.getAuthMode() == AuthMode.PASSWORD)
|
||||
.anyMatch(u -> u.getPasswords() != null && u.getPasswords().contains(password));
|
||||
}
|
||||
|
||||
private int allocateProxyPort() {
|
||||
int base = config.services().elasticache().proxyBasePort();
|
||||
int max = config.services().elasticache().proxyMaxPort();
|
||||
for (int port = base; port <= max; port++) {
|
||||
if (usedPorts.add(port)) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
throw new AwsException("InsufficientReplicationGroupCapacity",
|
||||
"No available proxy ports in range " + base + "-" + max, 503);
|
||||
}
|
||||
|
||||
private void releaseProxyPort(int port) {
|
||||
usedPorts.remove(port);
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package io.github.hectorvent.floci.services.elasticache.container;
|
||||
|
||||
import java.io.Closeable;
|
||||
|
||||
/**
|
||||
* Wraps a running backend Docker container for an ElastiCache replication group.
|
||||
*/
|
||||
public class ElastiCacheContainerHandle {
|
||||
|
||||
private final String containerId;
|
||||
private final String groupId;
|
||||
private final String host;
|
||||
private final int port;
|
||||
private Closeable logStream;
|
||||
|
||||
public ElastiCacheContainerHandle(String containerId, String groupId, String host, int port) {
|
||||
this.containerId = containerId;
|
||||
this.groupId = groupId;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public String getContainerId() { return containerId; }
|
||||
public String getGroupId() { return groupId; }
|
||||
public String getHost() { return host; }
|
||||
public int getPort() { return port; }
|
||||
public Closeable getLogStream() { return logStream; }
|
||||
public void setLogStream(Closeable logStream) { this.logStream = logStream; }
|
||||
}
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
package io.github.hectorvent.floci.services.elasticache.container;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.CreateContainerResponse;
|
||||
import com.github.dockerjava.api.model.ExposedPort;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.HostConfig;
|
||||
import com.github.dockerjava.api.model.Ports;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Manages backend Docker container lifecycle for ElastiCache replication groups.
|
||||
* In native (dev) mode, binds container port 6379 to a random host port.
|
||||
* In Docker mode, uses the container's internal network IP directly.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ElastiCacheContainerManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ElastiCacheContainerManager.class);
|
||||
private static final int BACKEND_PORT = 6379;
|
||||
private static final String HOST_DOCKER_INTERNAL = "host.docker.internal";
|
||||
private static final DateTimeFormatter LOG_STREAM_DATE_FMT = DateTimeFormatter.ofPattern("yyyy/MM/dd");
|
||||
|
||||
private final DockerClient dockerClient;
|
||||
private final ImageCacheService imageCacheService;
|
||||
private final DockerHostResolver dockerHostResolver;
|
||||
private final EmulatorConfig config;
|
||||
private final CloudWatchLogsService cloudWatchLogsService;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public ElastiCacheContainerManager(DockerClient dockerClient,
|
||||
ImageCacheService imageCacheService,
|
||||
DockerHostResolver dockerHostResolver,
|
||||
EmulatorConfig config,
|
||||
CloudWatchLogsService cloudWatchLogsService,
|
||||
RegionResolver regionResolver) {
|
||||
this.dockerClient = dockerClient;
|
||||
this.imageCacheService = imageCacheService;
|
||||
this.dockerHostResolver = dockerHostResolver;
|
||||
this.config = config;
|
||||
this.cloudWatchLogsService = cloudWatchLogsService;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
public ElastiCacheContainerHandle start(String groupId, String image) {
|
||||
LOG.infov("Starting ElastiCache backend container for group: {0}", groupId);
|
||||
imageCacheService.ensureImageExists(image);
|
||||
|
||||
boolean nativeMode = HOST_DOCKER_INTERNAL.equals(dockerHostResolver.resolve());
|
||||
|
||||
HostConfig hostConfig = buildHostConfig(nativeMode);
|
||||
String containerName = "floci-valkey-" + groupId;
|
||||
|
||||
config.services().elasticache().dockerNetwork()
|
||||
.or(() -> config.services().dockerNetwork())
|
||||
.ifPresent(network -> {
|
||||
if (!network.isBlank()) {
|
||||
hostConfig.withNetworkMode(network);
|
||||
LOG.debugv("Attaching ElastiCache container to network: {0}", network);
|
||||
}
|
||||
});
|
||||
|
||||
CreateContainerResponse container = dockerClient.createContainerCmd(image)
|
||||
.withName(containerName)
|
||||
.withEnv(List.of("VALKEY_EXTRA_FLAGS=--loglevel verbose"))
|
||||
.withExposedPorts(ExposedPort.tcp(BACKEND_PORT))
|
||||
.withHostConfig(hostConfig)
|
||||
.exec();
|
||||
|
||||
String containerId = container.getId();
|
||||
LOG.infov("Created ElastiCache container {0} for group {1}", containerId, groupId);
|
||||
|
||||
dockerClient.startContainerCmd(containerId).exec();
|
||||
LOG.infov("Started ElastiCache container {0}", containerId);
|
||||
|
||||
String backendHost;
|
||||
int backendPort;
|
||||
|
||||
if (nativeMode) {
|
||||
// Retrieve the actual allocated host port from the container inspect
|
||||
var inspect = dockerClient.inspectContainerCmd(containerId).exec();
|
||||
var bindings = inspect.getNetworkSettings().getPorts().getBindings();
|
||||
var binding = bindings.get(ExposedPort.tcp(BACKEND_PORT));
|
||||
if (binding != null && binding.length > 0) {
|
||||
backendPort = Integer.parseInt(binding[0].getHostPortSpec());
|
||||
} else {
|
||||
backendPort = BACKEND_PORT;
|
||||
}
|
||||
backendHost = "localhost";
|
||||
} else {
|
||||
// Docker mode: use container IP on the docker network
|
||||
var inspect = dockerClient.inspectContainerCmd(containerId).exec();
|
||||
var networks = inspect.getNetworkSettings().getNetworks();
|
||||
String containerIp = null;
|
||||
if (networks != null) {
|
||||
for (Map.Entry<String, ?> entry : networks.entrySet()) {
|
||||
var netEntry = (com.github.dockerjava.api.model.ContainerNetwork) entry.getValue();
|
||||
containerIp = netEntry.getIpAddress();
|
||||
if (containerIp != null && !containerIp.isBlank()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (containerIp == null || containerIp.isBlank()) {
|
||||
containerIp = inspect.getNetworkSettings().getIpAddress();
|
||||
}
|
||||
backendHost = containerIp;
|
||||
backendPort = BACKEND_PORT;
|
||||
}
|
||||
|
||||
LOG.infov("ElastiCache backend for group {0}: {1}:{2}", groupId, backendHost, backendPort);
|
||||
|
||||
ElastiCacheContainerHandle handle = new ElastiCacheContainerHandle(
|
||||
containerId, groupId, backendHost, backendPort);
|
||||
|
||||
String shortId = containerId.length() >= 8 ? containerId.substring(0, 8) : containerId;
|
||||
attachLogStream(handle, groupId, containerId, shortId);
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
public void stop(ElastiCacheContainerHandle handle) {
|
||||
if (handle == null) {
|
||||
return;
|
||||
}
|
||||
LOG.infov("Stopping ElastiCache container {0}", handle.getContainerId());
|
||||
|
||||
if (handle.getLogStream() != null) {
|
||||
try { handle.getLogStream().close(); } catch (Exception ignored) {}
|
||||
}
|
||||
|
||||
try {
|
||||
dockerClient.stopContainerCmd(handle.getContainerId()).withTimeout(5).exec();
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error stopping ElastiCache container {0}: {1}",
|
||||
handle.getContainerId(), e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
dockerClient.removeContainerCmd(handle.getContainerId()).withForce(true).exec();
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Error removing ElastiCache container {0}: {1}",
|
||||
handle.getContainerId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private HostConfig buildHostConfig(boolean nativeMode) {
|
||||
HostConfig hostConfig = HostConfig.newHostConfig();
|
||||
if (nativeMode) {
|
||||
// Bind BACKEND_PORT → random host port so the JVM can reach the container
|
||||
int freePort = findFreePort();
|
||||
Ports portBindings = new Ports();
|
||||
portBindings.bind(ExposedPort.tcp(BACKEND_PORT), Ports.Binding.bindPort(freePort));
|
||||
hostConfig.withPortBindings(portBindings);
|
||||
LOG.debugv("Native mode: binding container port 6379 → host port {0}", freePort);
|
||||
}
|
||||
return hostConfig;
|
||||
}
|
||||
|
||||
private static int findFreePort() {
|
||||
try (ServerSocket s = new ServerSocket(0)) {
|
||||
s.setReuseAddress(true);
|
||||
return s.getLocalPort();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Could not find a free port for ElastiCache container", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void attachLogStream(ElastiCacheContainerHandle handle, String groupId,
|
||||
String containerId, String shortId) {
|
||||
String logGroup = "/aws/elasticache/cluster/" + groupId + "/engine-log";
|
||||
String region = regionResolver.getDefaultRegion();
|
||||
String logStream = LOG_STREAM_DATE_FMT.format(LocalDate.now()) + "/" + shortId;
|
||||
ensureLogGroupAndStream(logGroup, logStream, region);
|
||||
|
||||
try {
|
||||
ResultCallback.Adapter<Frame> logCallback = dockerClient.logContainerCmd(containerId)
|
||||
.withStdOut(true)
|
||||
.withStdErr(true)
|
||||
.withFollowStream(true)
|
||||
.withTimestamps(false)
|
||||
.exec(new ResultCallback.Adapter<>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
String line = new String(frame.getPayload(), StandardCharsets.UTF_8).stripTrailing();
|
||||
if (!line.isEmpty()) {
|
||||
LOG.infov("[elasticache:{0}] {1}", groupId, line);
|
||||
forwardToCloudWatchLogs(logGroup, logStream, region, line);
|
||||
}
|
||||
}
|
||||
});
|
||||
handle.setLogStream(logCallback);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not attach log stream for ElastiCache container {0}: {1}",
|
||||
containerId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureLogGroupAndStream(String logGroup, String logStream, String region) {
|
||||
try {
|
||||
cloudWatchLogsService.createLogGroup(logGroup, null, null, region);
|
||||
} catch (AwsException ignored) {
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not create CW log group {0}: {1}", logGroup, e.getMessage());
|
||||
}
|
||||
try {
|
||||
cloudWatchLogsService.createLogStream(logGroup, logStream, region);
|
||||
} catch (AwsException ignored) {
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not create CW log stream {0}/{1}: {2}", logGroup, logStream, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void forwardToCloudWatchLogs(String logGroup, String logStream, String region, String line) {
|
||||
try {
|
||||
Map<String, Object> event = new HashMap<>();
|
||||
event.put("timestamp", System.currentTimeMillis());
|
||||
event.put("message", line);
|
||||
cloudWatchLogsService.putLogEvents(logGroup, logStream, List.of(event), region);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not forward ElastiCache log line to CloudWatch Logs: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package io.github.hectorvent.floci.services.elasticache.model;
|
||||
|
||||
public enum AuthMode {
|
||||
IAM, PASSWORD, NO_AUTH
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package io.github.hectorvent.floci.services.elasticache.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
public class ElastiCacheUser {
|
||||
|
||||
private String userId;
|
||||
private String userName;
|
||||
private AuthMode authMode;
|
||||
private List<String> passwords;
|
||||
private String accessString;
|
||||
private String status;
|
||||
private Instant createdAt;
|
||||
|
||||
public ElastiCacheUser() {}
|
||||
|
||||
public ElastiCacheUser(String userId, String userName, AuthMode authMode,
|
||||
List<String> passwords, String accessString,
|
||||
String status, Instant createdAt) {
|
||||
this.userId = userId;
|
||||
this.userName = userName;
|
||||
this.authMode = authMode;
|
||||
this.passwords = passwords;
|
||||
this.accessString = accessString;
|
||||
this.status = status;
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public String getUserId() { return userId; }
|
||||
public void setUserId(String userId) { this.userId = userId; }
|
||||
|
||||
public String getUserName() { return userName; }
|
||||
public void setUserName(String userName) { this.userName = userName; }
|
||||
|
||||
public AuthMode getAuthMode() { return authMode; }
|
||||
public void setAuthMode(AuthMode authMode) { this.authMode = authMode; }
|
||||
|
||||
public List<String> getPasswords() { return passwords; }
|
||||
public void setPasswords(List<String> passwords) { this.passwords = passwords; }
|
||||
|
||||
public String getAccessString() { return accessString; }
|
||||
public void setAccessString(String accessString) { this.accessString = accessString; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
|
||||
public Instant getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package io.github.hectorvent.floci.services.elasticache.model;
|
||||
|
||||
public record Endpoint(String address, int port) {}
|
||||
Loaded 100 of 313 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user