mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(elbv2) alb proxy codedeploy ecs (#677)
* feat(elbv2,codedeploy): real ALB Vert.x proxy and ECS blue/green deployment ELB v2 Phase 2: replace the mock ALB with a real Vert.x HTTP reverse proxy. ElbV2DataPlane compiles listener rules into an atomic rule chain and proxies requests to target group members. ElbV2HealthChecker runs periodic health checks against registered targets. shiftListenerForward atomically rewrites the default forward rule (simple or weighted) for CodeDeploy traffic shifts. CodeDeploy Phase 3: implement full ECS blue/green deployment. CreateDeployment drives the complete lifecycle — green task set creation, BeforeInstall / AfterInstall / BeforeAllowTraffic hooks, ALB listener traffic shift (AllAtOnce, Canary, or Linear), AfterAllowTraffic hook, green task set promoted to PRIMARY, blue task set deleted. Compute platform is resolved from the Application when the deployment group doesn't carry it, matching real AWS SDK behavior. * fix: refactor to use arnUtils
This commit is contained in:
1 parent
57a8d58ed4
commit
91ed829ea0
11 files changed
+2087
-21
No files matched your search
@@ -718,6 +718,9 @@ public interface EmulatorConfig {
|
||||
interface ElbV2ServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("false")
|
||||
boolean mock();
|
||||
}
|
||||
|
||||
interface EksServiceConfig {
|
||||
|
||||
+421
-10
@@ -8,6 +8,10 @@ import io.github.hectorvent.floci.services.codedeploy.model.Application;
|
||||
import io.github.hectorvent.floci.services.codedeploy.model.Deployment;
|
||||
import io.github.hectorvent.floci.services.codedeploy.model.DeploymentConfig;
|
||||
import io.github.hectorvent.floci.services.codedeploy.model.DeploymentGroup;
|
||||
import io.github.hectorvent.floci.services.ecs.EcsService;
|
||||
import io.github.hectorvent.floci.services.ecs.model.TaskSet;
|
||||
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
|
||||
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;
|
||||
@@ -34,11 +38,16 @@ public class CodeDeployService {
|
||||
private static final Logger LOG = Logger.getLogger(CodeDeployService.class);
|
||||
|
||||
private final LambdaService lambdaService;
|
||||
private final EcsService ecsService;
|
||||
private final ElbV2Service elbV2Service;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Inject
|
||||
public CodeDeployService(LambdaService lambdaService, ObjectMapper mapper) {
|
||||
public CodeDeployService(LambdaService lambdaService, EcsService ecsService,
|
||||
ElbV2Service elbV2Service, ObjectMapper mapper) {
|
||||
this.lambdaService = lambdaService;
|
||||
this.ecsService = ecsService;
|
||||
this.elbV2Service = elbV2Service;
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
@@ -68,6 +77,16 @@ public class CodeDeployService {
|
||||
String afterAllowTraffic;
|
||||
}
|
||||
|
||||
private static final class EcsAppSpecInfo {
|
||||
String taskDefinition;
|
||||
String containerName;
|
||||
int containerPort;
|
||||
String beforeInstall;
|
||||
String afterInstall;
|
||||
String beforeAllowTraffic;
|
||||
String afterAllowTraffic;
|
||||
}
|
||||
|
||||
private static final class TrafficRoutingInfo {
|
||||
final String type;
|
||||
final int percentage;
|
||||
@@ -400,11 +419,19 @@ public class CodeDeployService {
|
||||
|
||||
public String createDeployment(String region, String appName, String groupName,
|
||||
String configName, Map<String, Object> revision, String description) {
|
||||
getApplication(region, appName);
|
||||
getDeploymentGroup(region, appName, groupName);
|
||||
Application app = getApplication(region, appName);
|
||||
DeploymentGroup group = getDeploymentGroup(region, appName, groupName);
|
||||
// Compute platform is authoritative on the Application; the deployment group may also carry it
|
||||
String computePlatform = group.getComputePlatform();
|
||||
if (computePlatform == null) {
|
||||
computePlatform = app.getComputePlatform();
|
||||
}
|
||||
|
||||
if ("ECS".equals(computePlatform)) {
|
||||
return createEcsDeployment(region, appName, groupName, group, configName, revision, description);
|
||||
}
|
||||
|
||||
AppSpecInfo appSpec = parseAppSpec(revision);
|
||||
DeploymentGroup group = getDeploymentGroup(region, appName, groupName);
|
||||
String effectiveConfig = configName != null ? configName : group.getDeploymentConfigName();
|
||||
|
||||
String deploymentId = generateDeploymentId();
|
||||
@@ -500,9 +527,7 @@ public class CodeDeployService {
|
||||
if (target == null) {
|
||||
return List.of();
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> lambdaTarget = (Map<String, Object>) target.get("lambdaTarget");
|
||||
String targetId = lambdaTarget != null ? (String) lambdaTarget.get("targetId") : null;
|
||||
String targetId = extractTargetId(target);
|
||||
return targetId != null ? List.of(targetId) : List.of();
|
||||
}
|
||||
|
||||
@@ -512,15 +537,24 @@ public class CodeDeployService {
|
||||
if (target == null) {
|
||||
return List.of();
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> lambdaTarget = (Map<String, Object>) target.get("lambdaTarget");
|
||||
String targetId = lambdaTarget != null ? (String) lambdaTarget.get("targetId") : null;
|
||||
String targetId = extractTargetId(target);
|
||||
if (targetId == null || (!targetIds.isEmpty() && !targetIds.contains(targetId))) {
|
||||
return List.of();
|
||||
}
|
||||
return List.of(target);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private String extractTargetId(Map<String, Object> target) {
|
||||
String type = (String) target.get("deploymentTargetType");
|
||||
if ("ECSTarget".equals(type)) {
|
||||
Map<String, Object> ecsTarget = (Map<String, Object>) target.get("ecsTarget");
|
||||
return ecsTarget != null ? (String) ecsTarget.get("targetId") : null;
|
||||
}
|
||||
Map<String, Object> lambdaTarget = (Map<String, Object>) target.get("lambdaTarget");
|
||||
return lambdaTarget != null ? (String) lambdaTarget.get("targetId") : null;
|
||||
}
|
||||
|
||||
public String putLifecycleEventHookExecutionStatus(String deploymentId, String executionId, String status) {
|
||||
CompletableFuture<String> future = hookFutures.get(executionId);
|
||||
if (future != null && !future.isDone()) {
|
||||
@@ -582,6 +616,383 @@ public class CodeDeployService {
|
||||
return info;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private EcsAppSpecInfo parseEcsAppSpec(Map<String, Object> revision) {
|
||||
if (revision == null) {
|
||||
throw new AwsException("InvalidRevisionException", "Revision is required", 400);
|
||||
}
|
||||
Object appSpecContent = revision.get("appSpecContent");
|
||||
if (!(appSpecContent instanceof Map)) {
|
||||
throw new AwsException("InvalidRevisionException", "Missing appSpecContent in revision", 400);
|
||||
}
|
||||
String content = (String) ((Map<String, Object>) appSpecContent).get("content");
|
||||
if (content == null || content.isBlank()) {
|
||||
throw new AwsException("InvalidRevisionException", "Missing content in appSpecContent", 400);
|
||||
}
|
||||
|
||||
EcsAppSpecInfo info = new EcsAppSpecInfo();
|
||||
try {
|
||||
JsonNode root = mapper.readTree(content);
|
||||
JsonNode resources = root.get("Resources");
|
||||
if (resources != null && resources.isArray() && !resources.isEmpty()) {
|
||||
JsonNode firstResource = resources.get(0);
|
||||
if (firstResource.isObject()) {
|
||||
JsonNode resourceNode = firstResource.fields().next().getValue();
|
||||
JsonNode props = resourceNode.path("Properties");
|
||||
info.taskDefinition = props.path("TaskDefinition").asText(null);
|
||||
JsonNode lbInfo = props.path("LoadBalancerInfo");
|
||||
if (!lbInfo.isMissingNode()) {
|
||||
info.containerName = lbInfo.path("ContainerName").asText(null);
|
||||
info.containerPort = lbInfo.path("ContainerPort").asInt(80);
|
||||
}
|
||||
}
|
||||
}
|
||||
JsonNode hooks = root.get("Hooks");
|
||||
if (hooks != null && hooks.isArray()) {
|
||||
for (JsonNode hook : hooks) {
|
||||
if (hook.has("BeforeInstall")) {
|
||||
info.beforeInstall = hook.get("BeforeInstall").asText(null);
|
||||
}
|
||||
if (hook.has("AfterInstall")) {
|
||||
info.afterInstall = hook.get("AfterInstall").asText(null);
|
||||
}
|
||||
if (hook.has("BeforeAllowTraffic")) {
|
||||
info.beforeAllowTraffic = hook.get("BeforeAllowTraffic").asText(null);
|
||||
}
|
||||
if (hook.has("AfterAllowTraffic")) {
|
||||
info.afterAllowTraffic = hook.get("AfterAllowTraffic").asText(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InvalidRevisionException", "Failed to parse ECS AppSpec: " + e.getMessage(), 400);
|
||||
}
|
||||
|
||||
if (info.taskDefinition == null) {
|
||||
throw new AwsException("InvalidRevisionException", "ECS AppSpec must specify TaskDefinition", 400);
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private String createEcsDeployment(String region, String appName, String groupName,
|
||||
DeploymentGroup group, String configName,
|
||||
Map<String, Object> revision, String description) {
|
||||
EcsAppSpecInfo appSpec = parseEcsAppSpec(revision);
|
||||
String effectiveConfig = configName != null ? configName : group.getDeploymentConfigName();
|
||||
|
||||
String deploymentId = generateDeploymentId();
|
||||
double now = Instant.now().toEpochMilli() / 1000.0;
|
||||
|
||||
Deployment deployment = new Deployment();
|
||||
deployment.setDeploymentId(deploymentId);
|
||||
deployment.setApplicationName(appName);
|
||||
deployment.setDeploymentGroupName(groupName);
|
||||
deployment.setDeploymentConfigName(effectiveConfig);
|
||||
deployment.setStatus("Queued");
|
||||
deployment.setRevision(revision);
|
||||
deployment.setCreateTime(now);
|
||||
deployment.setDescription(description);
|
||||
deployment.setCreator("user");
|
||||
deployment.setComputePlatform("ECS");
|
||||
deploymentsFor(region).put(deploymentId, deployment);
|
||||
|
||||
// Determine ECS cluster/service from deployment group
|
||||
String clusterName = "default";
|
||||
String serviceName = null;
|
||||
List<Map<String, Object>> ecsSvcs = group.getEcsServices();
|
||||
if (ecsSvcs != null && !ecsSvcs.isEmpty()) {
|
||||
Map<String, Object> svc = ecsSvcs.get(0);
|
||||
clusterName = (String) svc.getOrDefault("clusterName", "default");
|
||||
serviceName = (String) svc.get("serviceName");
|
||||
}
|
||||
if (serviceName == null) {
|
||||
throw new AwsException("InvalidDeploymentConfigException",
|
||||
"ECS deployment group must specify ecsServices", 400);
|
||||
}
|
||||
|
||||
// Determine blue/green TG ARNs from loadBalancerInfo
|
||||
String blueTgArn = null;
|
||||
String greenTgArn = null;
|
||||
List<String> listenerArns = new ArrayList<>();
|
||||
Map<String, Object> lbInfo = group.getLoadBalancerInfo();
|
||||
if (lbInfo != null) {
|
||||
List<Map<String, Object>> pairList = (List<Map<String, Object>>) lbInfo.get("targetGroupPairInfoList");
|
||||
if (pairList != null && !pairList.isEmpty()) {
|
||||
Map<String, Object> pair = pairList.get(0);
|
||||
List<Map<String, Object>> tgList = (List<Map<String, Object>>) pair.get("targetGroups");
|
||||
if (tgList != null && tgList.size() >= 2) {
|
||||
String blueName = (String) tgList.get(0).get("name");
|
||||
String greenName = (String) tgList.get(1).get("name");
|
||||
TargetGroup blueTg = elbV2Service.getTargetGroupByName(region, blueName);
|
||||
TargetGroup greenTg = elbV2Service.getTargetGroupByName(region, greenName);
|
||||
if (blueTg != null) { blueTgArn = blueTg.getTargetGroupArn(); }
|
||||
if (greenTg != null) { greenTgArn = greenTg.getTargetGroupArn(); }
|
||||
}
|
||||
Map<String, Object> prodRoute = (Map<String, Object>) pair.get("prodTrafficRoute");
|
||||
if (prodRoute != null) {
|
||||
List<String> arns = (List<String>) prodRoute.get("listenerArns");
|
||||
if (arns != null) { listenerArns.addAll(arns); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String targetId = clusterName + ":" + serviceName;
|
||||
String targetArn = AwsArnUtils.Arn.of("ecs", region, "000000000000", "service/" + clusterName + "/" + serviceName).toString();
|
||||
|
||||
Map<String, Object> ecsTargetMap = new ConcurrentHashMap<>();
|
||||
ecsTargetMap.put("deploymentId", deploymentId);
|
||||
ecsTargetMap.put("targetId", targetId);
|
||||
ecsTargetMap.put("targetArn", targetArn);
|
||||
ecsTargetMap.put("status", "Pending");
|
||||
ecsTargetMap.put("lastUpdatedAt", now);
|
||||
ecsTargetMap.put("lifecycleEvents", new CopyOnWriteArrayList<>());
|
||||
ecsTargetMap.put("taskSetsInfo", new CopyOnWriteArrayList<>());
|
||||
|
||||
Map<String, Object> targetMap = new ConcurrentHashMap<>();
|
||||
targetMap.put("deploymentTargetType", "ECSTarget");
|
||||
targetMap.put("ecsTarget", ecsTargetMap);
|
||||
deploymentTargetsFor(region).put(deploymentId, targetMap);
|
||||
|
||||
AtomicBoolean stopFlag = new AtomicBoolean(false);
|
||||
stopFlags.put(deploymentId, stopFlag);
|
||||
|
||||
final String finalCluster = clusterName;
|
||||
final String finalService = serviceName;
|
||||
final String finalBlueTgArn = blueTgArn;
|
||||
final String finalGreenTgArn = greenTgArn;
|
||||
final List<String> finalListenerArns = listenerArns;
|
||||
Thread.ofVirtual().name("codedeploy-ecs-" + deploymentId).start(
|
||||
() -> runEcsStateMachine(region, deployment, appSpec, ecsTargetMap, stopFlag,
|
||||
effectiveConfig, finalCluster, finalService,
|
||||
finalBlueTgArn, finalGreenTgArn, finalListenerArns));
|
||||
|
||||
return deploymentId;
|
||||
}
|
||||
|
||||
private void runEcsStateMachine(String region, Deployment deployment, EcsAppSpecInfo appSpec,
|
||||
Map<String, Object> ecsTargetMap, AtomicBoolean stopFlag,
|
||||
String configName, String clusterName, String serviceName,
|
||||
String blueTgArn, String greenTgArn,
|
||||
List<String> listenerArns) {
|
||||
String deploymentId = deployment.getDeploymentId();
|
||||
TaskSet greenTaskSet = null;
|
||||
TaskSet blueTaskSet = null;
|
||||
try {
|
||||
deployment.setStatus("InProgress");
|
||||
deployment.setStartTime(Instant.now().toEpochMilli() / 1000.0);
|
||||
updateEcsTargetStatus(ecsTargetMap, "InProgress");
|
||||
|
||||
if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
|
||||
|
||||
// Find existing primary (blue) task set
|
||||
List<TaskSet> existing = ecsService.describeTaskSets(clusterName, serviceName, null, region);
|
||||
blueTaskSet = existing.stream()
|
||||
.filter(ts -> "PRIMARY".equals(ts.getStatus()))
|
||||
.findFirst()
|
||||
.orElse(existing.isEmpty() ? null : existing.get(0));
|
||||
|
||||
if (appSpec.beforeInstall != null) {
|
||||
boolean ok = invokeHook(region, deployment, appSpec.beforeInstall,
|
||||
"BeforeInstall", ecsTargetMap, stopFlag);
|
||||
if (!ok) {
|
||||
finishEcsFailed(deployment, ecsTargetMap, "BeforeInstallHookFailed",
|
||||
"Hook function reported failure: BeforeInstall");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
|
||||
|
||||
// Install: create green task set
|
||||
Map<String, Object> installEvent = addLifecycleEvent(ecsTargetMap, "Install");
|
||||
try {
|
||||
greenTaskSet = ecsService.createTaskSet(clusterName, serviceName,
|
||||
appSpec.taskDefinition, null, 100.0, "PERCENT", deploymentId, region);
|
||||
appendTaskSetInfo(ecsTargetMap, greenTaskSet, greenTgArn, 0.0);
|
||||
finishLifecycleEvent(installEvent, "Succeeded");
|
||||
} catch (Exception e) {
|
||||
finishLifecycleEvent(installEvent, "Failed");
|
||||
finishEcsFailed(deployment, ecsTargetMap, "InstallFailed", e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
|
||||
|
||||
if (appSpec.afterInstall != null) {
|
||||
boolean ok = invokeHook(region, deployment, appSpec.afterInstall,
|
||||
"AfterInstall", ecsTargetMap, stopFlag);
|
||||
if (!ok) {
|
||||
finishEcsFailed(deployment, ecsTargetMap, "AfterInstallHookFailed",
|
||||
"Hook function reported failure: AfterInstall");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
|
||||
|
||||
if (appSpec.beforeAllowTraffic != null) {
|
||||
boolean ok = invokeHook(region, deployment, appSpec.beforeAllowTraffic,
|
||||
"BeforeAllowTraffic", ecsTargetMap, stopFlag);
|
||||
if (!ok) {
|
||||
finishEcsFailed(deployment, ecsTargetMap, "BeforeAllowTrafficHookFailed",
|
||||
"Hook function reported failure: BeforeAllowTraffic");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
|
||||
|
||||
// AllowTraffic: shift ELB traffic blue → green
|
||||
if (!listenerArns.isEmpty() && blueTgArn != null && greenTgArn != null) {
|
||||
executeEcsAllowTraffic(region, deployment, configName, ecsTargetMap,
|
||||
listenerArns, blueTgArn, greenTgArn, stopFlag);
|
||||
} else {
|
||||
Map<String, Object> allowEvent = addLifecycleEvent(ecsTargetMap, "AllowTraffic");
|
||||
finishLifecycleEvent(allowEvent, "Succeeded");
|
||||
}
|
||||
|
||||
if (stopFlag.get()) { finishEcsStopped(deployment, ecsTargetMap); return; }
|
||||
|
||||
if (appSpec.afterAllowTraffic != null) {
|
||||
boolean ok = invokeHook(region, deployment, appSpec.afterAllowTraffic,
|
||||
"AfterAllowTraffic", ecsTargetMap, stopFlag);
|
||||
if (!ok) {
|
||||
finishEcsFailed(deployment, ecsTargetMap, "AfterAllowTrafficHookFailed",
|
||||
"Hook function reported failure: AfterAllowTraffic");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Promote green as primary
|
||||
if (greenTaskSet != null) {
|
||||
ecsService.updateServicePrimaryTaskSet(clusterName, serviceName,
|
||||
greenTaskSet.getTaskSetArn(), region);
|
||||
}
|
||||
|
||||
// Terminate blue task set
|
||||
if (blueTaskSet != null) {
|
||||
Map<String, Object> terminateEvent = addLifecycleEvent(ecsTargetMap, "TerminateBlueInstances");
|
||||
try {
|
||||
ecsService.deleteTaskSet(clusterName, serviceName,
|
||||
blueTaskSet.getTaskSetArn(), true, region);
|
||||
finishLifecycleEvent(terminateEvent, "Succeeded");
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not delete blue task set: {0}", e.getMessage());
|
||||
finishLifecycleEvent(terminateEvent, "Succeeded");
|
||||
}
|
||||
}
|
||||
|
||||
updateEcsTargetStatus(ecsTargetMap, "Succeeded");
|
||||
deployment.setStatus("Succeeded");
|
||||
deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0);
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
finishEcsStopped(deployment, ecsTargetMap);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("ECS deployment {0} failed: {1}", deploymentId, e.getMessage());
|
||||
finishEcsFailed(deployment, ecsTargetMap, "DeploymentFailed", e.getMessage());
|
||||
} finally {
|
||||
stopFlags.remove(deploymentId);
|
||||
}
|
||||
}
|
||||
|
||||
private void executeEcsAllowTraffic(String region, Deployment deployment, String configName,
|
||||
Map<String, Object> ecsTargetMap, List<String> listenerArns,
|
||||
String blueTgArn, String greenTgArn,
|
||||
AtomicBoolean stopFlag) throws InterruptedException {
|
||||
TrafficRoutingInfo trc = getTrafficRoutingInfo(region, configName);
|
||||
Map<String, Object> event = addLifecycleEvent(ecsTargetMap, "AllowTraffic");
|
||||
try {
|
||||
switch (trc.type) {
|
||||
case "TimeBasedCanary" -> {
|
||||
for (String listenerArn : listenerArns) {
|
||||
elbV2Service.shiftListenerForward(region, listenerArn,
|
||||
blueTgArn, greenTgArn, trc.percentage);
|
||||
}
|
||||
long waitMs = Math.min(trc.intervalSeconds * 1000L, 5000L);
|
||||
if (waitMs > 0 && !stopFlag.get()) {
|
||||
Thread.sleep(waitMs);
|
||||
}
|
||||
if (!stopFlag.get()) {
|
||||
for (String listenerArn : listenerArns) {
|
||||
elbV2Service.shiftListenerForward(region, listenerArn,
|
||||
blueTgArn, greenTgArn, 100);
|
||||
}
|
||||
}
|
||||
}
|
||||
case "TimeBasedLinear" -> {
|
||||
int steps = (int) Math.ceil(100.0 / trc.percentage);
|
||||
for (int step = 1; step <= steps && !stopFlag.get(); step++) {
|
||||
int pct = Math.min(step * trc.percentage, 100);
|
||||
for (String listenerArn : listenerArns) {
|
||||
elbV2Service.shiftListenerForward(region, listenerArn,
|
||||
blueTgArn, greenTgArn, pct);
|
||||
}
|
||||
if (pct < 100) {
|
||||
long waitMs = Math.min(trc.intervalSeconds * 1000L, 2000L);
|
||||
if (waitMs > 0) {
|
||||
Thread.sleep(waitMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
for (String listenerArn : listenerArns) {
|
||||
elbV2Service.shiftListenerForward(region, listenerArn,
|
||||
blueTgArn, greenTgArn, 100);
|
||||
}
|
||||
}
|
||||
}
|
||||
finishLifecycleEvent(event, "Succeeded");
|
||||
} catch (InterruptedException e) {
|
||||
finishLifecycleEvent(event, "Failed");
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
finishLifecycleEvent(event, "Failed");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void appendTaskSetInfo(Map<String, Object> ecsTargetMap, TaskSet ts,
|
||||
String tgArn, double trafficWeight) {
|
||||
Map<String, Object> tsInfo = new ConcurrentHashMap<>();
|
||||
tsInfo.put("identifer", ts.getId());
|
||||
tsInfo.put("desiredCount", ts.getComputedDesiredCount());
|
||||
tsInfo.put("pendingCount", ts.getPendingCount());
|
||||
tsInfo.put("runningCount", ts.getRunningCount());
|
||||
tsInfo.put("status", ts.getStatus());
|
||||
tsInfo.put("trafficWeight", trafficWeight);
|
||||
if (tgArn != null) {
|
||||
tsInfo.put("targetGroup", Map.of("arn", tgArn));
|
||||
}
|
||||
List<Map<String, Object>> taskSetsInfo = (List<Map<String, Object>>) ecsTargetMap.get("taskSetsInfo");
|
||||
if (taskSetsInfo != null) {
|
||||
taskSetsInfo.add(tsInfo);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateEcsTargetStatus(Map<String, Object> ecsTargetMap, String status) {
|
||||
ecsTargetMap.put("status", status);
|
||||
ecsTargetMap.put("lastUpdatedAt", Instant.now().toEpochMilli() / 1000.0);
|
||||
}
|
||||
|
||||
private void finishEcsStopped(Deployment deployment, Map<String, Object> ecsTargetMap) {
|
||||
updateEcsTargetStatus(ecsTargetMap, "Skipped");
|
||||
deployment.setStatus("Stopped");
|
||||
deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0);
|
||||
}
|
||||
|
||||
private void finishEcsFailed(Deployment deployment, Map<String, Object> ecsTargetMap,
|
||||
String errorCode, String message) {
|
||||
updateEcsTargetStatus(ecsTargetMap, "Failed");
|
||||
deployment.setStatus("Failed");
|
||||
deployment.setCompleteTime(Instant.now().toEpochMilli() / 1000.0);
|
||||
deployment.setErrorInformation(Map.of("code", errorCode, "message", message != null ? message : ""));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private TrafficRoutingInfo getTrafficRoutingInfo(String region, String configName) {
|
||||
if (configName == null) {
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Action;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Listener;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Rule;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.RuleCondition;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpClientOptions;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.http.HttpServerOptions;
|
||||
import io.vertx.core.http.RequestOptions;
|
||||
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.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ApplicationScoped
|
||||
public class ElbV2DataPlane {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ElbV2DataPlane.class);
|
||||
|
||||
private static final List<String> HOP_BY_HOP_HEADERS = List.of(
|
||||
"connection", "keep-alive", "transfer-encoding", "upgrade", "te", "trailers", "proxy-authorization", "proxy-authenticate"
|
||||
);
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
|
||||
@Inject
|
||||
ElbV2Service elbV2Service;
|
||||
|
||||
@Inject
|
||||
ElbV2HealthChecker healthChecker;
|
||||
|
||||
@Inject
|
||||
EmulatorConfig config;
|
||||
|
||||
private final Map<String, HttpServer> servers = new ConcurrentHashMap<>();
|
||||
private final Map<String, AtomicReference<List<CompiledRule>>> ruleChains = new ConcurrentHashMap<>();
|
||||
private final Map<String, AtomicInteger> rrCounters = new ConcurrentHashMap<>();
|
||||
private final Map<String, String> listenerRegions = new ConcurrentHashMap<>();
|
||||
|
||||
private HttpClient proxyClient;
|
||||
|
||||
@PostConstruct
|
||||
void init() {
|
||||
proxyClient = vertx.createHttpClient(new HttpClientOptions()
|
||||
.setMaxPoolSize(100)
|
||||
.setConnectTimeout(5000)
|
||||
.setKeepAlive(true));
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
for (Map.Entry<String, HttpServer> e : servers.entrySet()) {
|
||||
e.getValue().close();
|
||||
}
|
||||
servers.clear();
|
||||
ruleChains.clear();
|
||||
rrCounters.clear();
|
||||
listenerRegions.clear();
|
||||
}
|
||||
|
||||
public void startListener(Listener listener, String region, List<Rule> rules) {
|
||||
if (config.services().elbv2().mock()) {
|
||||
return;
|
||||
}
|
||||
String listenerArn = listener.getListenerArn();
|
||||
List<CompiledRule> compiled = compileRules(rules);
|
||||
ruleChains.put(listenerArn, new AtomicReference<>(compiled));
|
||||
listenerRegions.put(listenerArn, region);
|
||||
|
||||
HttpServer server = vertx.createHttpServer(new HttpServerOptions()
|
||||
.setHost("0.0.0.0")
|
||||
.setPort(listener.getPort()));
|
||||
|
||||
server.requestHandler(req -> handleRequest(req, listenerArn, region));
|
||||
server.listen()
|
||||
.onSuccess(s -> LOG.infov("ELBv2 listener started on port {0} for {1}", listener.getPort(), listenerArn))
|
||||
.onFailure(err -> LOG.warnv("ELBv2 listener failed to start on port {0}: {1}", listener.getPort(), err.getMessage()));
|
||||
|
||||
servers.put(listenerArn, server);
|
||||
}
|
||||
|
||||
public void stopListener(String listenerArn) {
|
||||
HttpServer server = servers.remove(listenerArn);
|
||||
if (server != null) {
|
||||
server.close();
|
||||
}
|
||||
ruleChains.remove(listenerArn);
|
||||
listenerRegions.remove(listenerArn);
|
||||
}
|
||||
|
||||
public void recompileRules(String listenerArn, List<Rule> rules) {
|
||||
AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);
|
||||
if (ref != null) {
|
||||
ref.set(compileRules(rules));
|
||||
}
|
||||
}
|
||||
|
||||
private void handleRequest(io.vertx.core.http.HttpServerRequest req, String listenerArn, String region) {
|
||||
AtomicReference<List<CompiledRule>> ref = ruleChains.get(listenerArn);
|
||||
if (ref == null) {
|
||||
req.response().setStatusCode(502).end("No rule chain");
|
||||
return;
|
||||
}
|
||||
List<CompiledRule> chain = ref.get();
|
||||
for (CompiledRule compiled : chain) {
|
||||
if (compiled.matches(req)) {
|
||||
executeAction(req, compiled.action, region);
|
||||
return;
|
||||
}
|
||||
}
|
||||
req.response().setStatusCode(502).end("No matching rule");
|
||||
}
|
||||
|
||||
private void executeAction(io.vertx.core.http.HttpServerRequest req, Action action, String region) {
|
||||
if (action == null) {
|
||||
req.response().setStatusCode(502).end("No action");
|
||||
return;
|
||||
}
|
||||
switch (action.getType() != null ? action.getType() : "") {
|
||||
case "forward" -> executeForward(req, action, region);
|
||||
case "redirect" -> executeRedirect(req, action);
|
||||
case "fixed-response" -> executeFixedResponse(req, action);
|
||||
default -> req.response().setStatusCode(502).end("Unsupported action type");
|
||||
}
|
||||
}
|
||||
|
||||
private void executeForward(io.vertx.core.http.HttpServerRequest req, Action action, String region) {
|
||||
String tgArn = resolveTgArn(action);
|
||||
if (tgArn == null) {
|
||||
req.response().setStatusCode(502).end("No target group");
|
||||
return;
|
||||
}
|
||||
TargetGroup tg = elbV2Service.getTargetGroup(region, tgArn);
|
||||
if (tg == null) {
|
||||
req.response().setStatusCode(502).end("Target group not found");
|
||||
return;
|
||||
}
|
||||
List<TargetDescription> allTargets = tg.getTargets();
|
||||
List<TargetDescription> healthy = allTargets.stream()
|
||||
.filter(t -> healthChecker.isHealthy(tgArn, t, ElbV2HealthChecker.effectivePort(t, tg)))
|
||||
.collect(Collectors.toList());
|
||||
List<TargetDescription> candidates = healthy.isEmpty() ? allTargets : healthy;
|
||||
if (candidates.isEmpty()) {
|
||||
req.response().setStatusCode(503).end("No targets available");
|
||||
return;
|
||||
}
|
||||
AtomicInteger counter = rrCounters.computeIfAbsent(tgArn, k -> new AtomicInteger(0));
|
||||
int idx = Math.abs(counter.getAndIncrement() % candidates.size());
|
||||
TargetDescription target = candidates.get(idx);
|
||||
int targetPort = ElbV2HealthChecker.effectivePort(target, tg);
|
||||
proxyRequest(req, target.getId(), targetPort);
|
||||
}
|
||||
|
||||
private String resolveTgArn(Action action) {
|
||||
if (action.getTargetGroupArn() != null) {
|
||||
return action.getTargetGroupArn();
|
||||
}
|
||||
List<Action.TargetGroupTuple> tuples = action.getTargetGroups();
|
||||
if (tuples == null || tuples.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
double total = tuples.stream().mapToDouble(t -> t.getWeight() != null ? t.getWeight() : 1).sum();
|
||||
double roll = Math.random() * total;
|
||||
double cumulative = 0;
|
||||
for (Action.TargetGroupTuple tuple : tuples) {
|
||||
cumulative += (tuple.getWeight() != null ? tuple.getWeight() : 1);
|
||||
if (roll < cumulative) {
|
||||
return tuple.getTargetGroupArn();
|
||||
}
|
||||
}
|
||||
return tuples.get(tuples.size() - 1).getTargetGroupArn();
|
||||
}
|
||||
|
||||
private void proxyRequest(io.vertx.core.http.HttpServerRequest req, String host, int port) {
|
||||
req.bodyHandler(body -> {
|
||||
RequestOptions opts = new RequestOptions()
|
||||
.setHost(host)
|
||||
.setPort(port)
|
||||
.setURI(req.uri())
|
||||
.setMethod(req.method());
|
||||
proxyClient.request(opts)
|
||||
.onSuccess(clientReq -> {
|
||||
req.headers().forEach(entry -> {
|
||||
if (!HOP_BY_HOP_HEADERS.contains(entry.getKey().toLowerCase())) {
|
||||
clientReq.putHeader(entry.getKey(), entry.getValue());
|
||||
}
|
||||
});
|
||||
clientReq.putHeader("Host", host + ":" + port);
|
||||
clientReq.send(body)
|
||||
.onSuccess(resp -> {
|
||||
req.response().setStatusCode(resp.statusCode());
|
||||
resp.headers().forEach(entry -> {
|
||||
if (!HOP_BY_HOP_HEADERS.contains(entry.getKey().toLowerCase())) {
|
||||
req.response().putHeader(entry.getKey(), entry.getValue());
|
||||
}
|
||||
});
|
||||
resp.body()
|
||||
.onSuccess(req.response()::end)
|
||||
.onFailure(err -> req.response().setStatusCode(502).end("Body error"));
|
||||
})
|
||||
.onFailure(err -> req.response().setStatusCode(502).end("Bad gateway"));
|
||||
})
|
||||
.onFailure(err -> req.response().setStatusCode(503).end("Service unavailable"));
|
||||
});
|
||||
}
|
||||
|
||||
private void executeRedirect(io.vertx.core.http.HttpServerRequest req, Action action) {
|
||||
String reqHost = req.host();
|
||||
String reqPort = "";
|
||||
if (reqHost != null && reqHost.contains(":")) {
|
||||
String[] parts = reqHost.split(":", 2);
|
||||
reqHost = parts[0];
|
||||
reqPort = parts[1];
|
||||
}
|
||||
String reqPath = req.path() != null ? req.path() : "/";
|
||||
String reqQuery = req.query();
|
||||
String reqProtocol = "HTTP";
|
||||
|
||||
String protocol = action.getRedirectProtocol() != null ? action.getRedirectProtocol() : reqProtocol;
|
||||
String host = action.getRedirectHost() != null ? action.getRedirectHost() : reqHost;
|
||||
String portStr = action.getRedirectPort() != null ? action.getRedirectPort() : reqPort;
|
||||
String path = action.getRedirectPath() != null ? action.getRedirectPath() : reqPath;
|
||||
String query = action.getRedirectQuery() != null ? action.getRedirectQuery() : (reqQuery != null ? reqQuery : "");
|
||||
|
||||
final String finalReqHost = reqHost;
|
||||
final String finalReqPort = reqPort;
|
||||
|
||||
protocol = substitute(protocol, finalReqHost, finalReqPort, reqPath, reqProtocol, reqQuery);
|
||||
host = substitute(host, finalReqHost, finalReqPort, reqPath, reqProtocol, reqQuery);
|
||||
portStr = substitute(portStr, finalReqHost, finalReqPort, reqPath, reqProtocol, reqQuery);
|
||||
path = substitute(path, finalReqHost, finalReqPort, reqPath, reqProtocol, reqQuery);
|
||||
query = substitute(query, finalReqHost, finalReqPort, reqPath, reqProtocol, reqQuery);
|
||||
|
||||
StringBuilder location = new StringBuilder(protocol.toLowerCase()).append("://").append(host);
|
||||
if (!portStr.isEmpty()) {
|
||||
location.append(":").append(portStr);
|
||||
}
|
||||
location.append(path);
|
||||
if (!query.isEmpty()) {
|
||||
location.append("?").append(query);
|
||||
}
|
||||
|
||||
int statusCode = "HTTP_301".equals(action.getRedirectStatusCode()) ? 301 : 302;
|
||||
req.response()
|
||||
.setStatusCode(statusCode)
|
||||
.putHeader("Location", location.toString())
|
||||
.end();
|
||||
}
|
||||
|
||||
private String substitute(String template, String host, String port, String path, String protocol, String query) {
|
||||
if (template == null) {
|
||||
return "";
|
||||
}
|
||||
String result = template
|
||||
.replace("#{host}", host != null ? host : "")
|
||||
.replace("#{port}", port != null ? port : "")
|
||||
.replace("#{path}", path != null ? path : "/")
|
||||
.replace("#{protocol}", protocol != null ? protocol : "HTTP");
|
||||
if (query != null && !query.isEmpty()) {
|
||||
result = result.replace("#{query}", query);
|
||||
} else {
|
||||
result = result.replace("#{query}", "");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void executeFixedResponse(io.vertx.core.http.HttpServerRequest req, Action action) {
|
||||
int statusCode = 200;
|
||||
try {
|
||||
if (action.getFixedResponseStatusCode() != null) {
|
||||
statusCode = Integer.parseInt(action.getFixedResponseStatusCode());
|
||||
}
|
||||
} catch (NumberFormatException ignored) {
|
||||
}
|
||||
req.response().setStatusCode(statusCode);
|
||||
if (action.getFixedResponseContentType() != null) {
|
||||
req.response().putHeader("Content-Type", action.getFixedResponseContentType());
|
||||
}
|
||||
String body = action.getFixedResponseMessageBody() != null ? action.getFixedResponseMessageBody() : "";
|
||||
req.response().end(body);
|
||||
}
|
||||
|
||||
private List<CompiledRule> compileRules(List<Rule> rules) {
|
||||
return rules.stream()
|
||||
.map(CompiledRule::new)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Action getRoutingAction(Rule rule) {
|
||||
List<Action> actions = rule.getActions();
|
||||
if (actions == null || actions.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
Action last = null;
|
||||
for (Action a : actions) {
|
||||
String type = a.getType();
|
||||
if ("forward".equals(type) || "redirect".equals(type) || "fixed-response".equals(type)) {
|
||||
last = a;
|
||||
}
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
private static boolean globMatches(String pattern, String text) {
|
||||
if (text == null) {
|
||||
return false;
|
||||
}
|
||||
StringBuilder regex = new StringBuilder("(?i)");
|
||||
for (char c : pattern.toCharArray()) {
|
||||
if (c == '*') {
|
||||
regex.append(".*");
|
||||
} else if (c == '?') {
|
||||
regex.append('.');
|
||||
} else {
|
||||
regex.append(Pattern.quote(String.valueOf(c)));
|
||||
}
|
||||
}
|
||||
return Pattern.matches(regex.toString(), text);
|
||||
}
|
||||
|
||||
private class CompiledRule {
|
||||
final Rule rule;
|
||||
final Action action;
|
||||
|
||||
CompiledRule(Rule rule) {
|
||||
this.rule = rule;
|
||||
this.action = getRoutingAction(rule);
|
||||
}
|
||||
|
||||
boolean matches(io.vertx.core.http.HttpServerRequest req) {
|
||||
if (rule.isDefault()) {
|
||||
return true;
|
||||
}
|
||||
for (RuleCondition condition : rule.getConditions()) {
|
||||
if (!matchesCondition(condition, req)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean matchesCondition(RuleCondition condition, io.vertx.core.http.HttpServerRequest req) {
|
||||
String field = condition.getField();
|
||||
if (field == null) {
|
||||
return true;
|
||||
}
|
||||
return switch (field) {
|
||||
case "host-header" -> {
|
||||
List<String> patterns = condition.getHostHeaderValues().isEmpty()
|
||||
? condition.getValues()
|
||||
: condition.getHostHeaderValues();
|
||||
String host = req.host();
|
||||
if (host != null && host.contains(":")) {
|
||||
host = host.substring(0, host.indexOf(':'));
|
||||
}
|
||||
String effectiveHost = host;
|
||||
yield patterns.stream().anyMatch(p -> globMatches(p, effectiveHost));
|
||||
}
|
||||
case "path-pattern" -> {
|
||||
List<String> patterns = condition.getPathPatternValues().isEmpty()
|
||||
? condition.getValues()
|
||||
: condition.getPathPatternValues();
|
||||
String path = req.path();
|
||||
yield patterns.stream().anyMatch(p -> globMatches(p, path));
|
||||
}
|
||||
case "http-header" -> {
|
||||
String headerName = condition.getHttpHeaderName();
|
||||
if (headerName == null) {
|
||||
yield true;
|
||||
}
|
||||
String headerValue = req.getHeader(headerName);
|
||||
yield condition.getHttpHeaderValues().stream().anyMatch(p -> globMatches(p, headerValue));
|
||||
}
|
||||
case "http-request-method" -> {
|
||||
String method = req.method().name();
|
||||
yield condition.getHttpMethodValues().stream()
|
||||
.anyMatch(m -> m.equalsIgnoreCase(method));
|
||||
}
|
||||
case "query-string" -> {
|
||||
String queryString = req.query();
|
||||
Map<String, String> queryParams = parseQueryString(queryString);
|
||||
yield condition.getQueryStringValues().stream().allMatch(pair -> {
|
||||
String key = pair.getKey();
|
||||
String valuePattern = pair.getValue();
|
||||
if (key == null) {
|
||||
return queryParams.values().stream().anyMatch(v -> globMatches(valuePattern, v));
|
||||
}
|
||||
String paramValue = queryParams.get(key);
|
||||
return paramValue != null && globMatches(valuePattern, paramValue);
|
||||
});
|
||||
}
|
||||
case "source-ip" -> true;
|
||||
default -> true;
|
||||
};
|
||||
}
|
||||
|
||||
private Map<String, String> parseQueryString(String query) {
|
||||
Map<String, String> params = new java.util.LinkedHashMap<>();
|
||||
if (query == null || query.isEmpty()) {
|
||||
return params;
|
||||
}
|
||||
for (String pair : query.split("&")) {
|
||||
int eq = pair.indexOf('=');
|
||||
if (eq >= 0) {
|
||||
params.put(pair.substring(0, eq), pair.substring(eq + 1));
|
||||
} else {
|
||||
params.put(pair, "");
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
|
||||
import io.vertx.core.Vertx;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@ApplicationScoped
|
||||
public class ElbV2HealthChecker {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ElbV2HealthChecker.class);
|
||||
|
||||
private final Vertx vertx;
|
||||
private final EmulatorConfig config;
|
||||
|
||||
// tgArn → (targetKey → TargetState)
|
||||
private final Map<String, Map<String, TargetState>> states = new ConcurrentHashMap<>();
|
||||
// tgArn → timerId
|
||||
private final Map<String, Long> timers = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public ElbV2HealthChecker(Vertx vertx, EmulatorConfig config) {
|
||||
this.vertx = vertx;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public static int effectivePort(TargetDescription target, TargetGroup tg) {
|
||||
if (target.getPort() != null) {
|
||||
return target.getPort();
|
||||
}
|
||||
if (tg.getPort() != null) {
|
||||
return tg.getPort();
|
||||
}
|
||||
return 80;
|
||||
}
|
||||
|
||||
public void startMonitoring(TargetGroup tg) {
|
||||
if (config.services().elbv2().mock()) {
|
||||
return;
|
||||
}
|
||||
String tgArn = tg.getTargetGroupArn();
|
||||
states.computeIfAbsent(tgArn, k -> new ConcurrentHashMap<>());
|
||||
|
||||
long intervalMs = (tg.getHealthCheckIntervalSeconds() != null ? tg.getHealthCheckIntervalSeconds() : 30) * 1000L;
|
||||
long timerId = vertx.setPeriodic(intervalMs, id -> probeAll(tgArn, tg));
|
||||
timers.put(tgArn, timerId);
|
||||
}
|
||||
|
||||
public void stopMonitoring(String tgArn) {
|
||||
Long timerId = timers.remove(tgArn);
|
||||
if (timerId != null) {
|
||||
vertx.cancelTimer(timerId);
|
||||
}
|
||||
states.remove(tgArn);
|
||||
}
|
||||
|
||||
public void addTargets(String tgArn, List<TargetDescription> targets, TargetGroup tg) {
|
||||
if (config.services().elbv2().mock()) {
|
||||
return;
|
||||
}
|
||||
Map<String, TargetState> tgStates = states.computeIfAbsent(tgArn, k -> new ConcurrentHashMap<>());
|
||||
for (TargetDescription t : targets) {
|
||||
int port = effectivePort(t, tg);
|
||||
String key = stateKey(t.getId(), port);
|
||||
tgStates.putIfAbsent(key, new TargetState());
|
||||
}
|
||||
}
|
||||
|
||||
public void removeTargets(String tgArn, List<TargetDescription> targets, TargetGroup tg) {
|
||||
Map<String, TargetState> tgStates = states.get(tgArn);
|
||||
if (tgStates == null) {
|
||||
return;
|
||||
}
|
||||
for (TargetDescription t : targets) {
|
||||
int port = effectivePort(t, tg);
|
||||
tgStates.remove(stateKey(t.getId(), port));
|
||||
}
|
||||
}
|
||||
|
||||
public String getState(String tgArn, String targetId, int port) {
|
||||
Map<String, TargetState> tgStates = states.get(tgArn);
|
||||
if (tgStates == null) {
|
||||
return "initial";
|
||||
}
|
||||
TargetState s = tgStates.get(stateKey(targetId, port));
|
||||
if (s == null) {
|
||||
return "initial";
|
||||
}
|
||||
return s.status;
|
||||
}
|
||||
|
||||
public boolean isHealthy(String tgArn, TargetDescription target, int port) {
|
||||
String state = getState(tgArn, target.getId(), port);
|
||||
return "healthy".equals(state) || "initial".equals(state);
|
||||
}
|
||||
|
||||
private void probeAll(String tgArn, TargetGroup tg) {
|
||||
Map<String, TargetState> tgStates = states.get(tgArn);
|
||||
if (tgStates == null || !Boolean.TRUE.equals(tg.getHealthCheckEnabled())) {
|
||||
return;
|
||||
}
|
||||
for (Map.Entry<String, TargetState> entry : tgStates.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
TargetState state = entry.getValue();
|
||||
String[] parts = key.split(":", 2);
|
||||
if (parts.length != 2) {
|
||||
continue;
|
||||
}
|
||||
String host = parts[0];
|
||||
int port;
|
||||
try {
|
||||
port = Integer.parseInt(parts[1]);
|
||||
} catch (NumberFormatException e) {
|
||||
continue;
|
||||
}
|
||||
String path = tg.getHealthCheckPath() != null ? tg.getHealthCheckPath() : "/";
|
||||
String matcher = tg.getMatcher() != null ? tg.getMatcher() : "200";
|
||||
int timeout = tg.getHealthCheckTimeoutSeconds() != null ? tg.getHealthCheckTimeoutSeconds() : 5;
|
||||
int healthyThreshold = tg.getHealthyThresholdCount() != null ? tg.getHealthyThresholdCount() : 5;
|
||||
int unhealthyThreshold = tg.getUnhealthyThresholdCount() != null ? tg.getUnhealthyThresholdCount() : 2;
|
||||
|
||||
vertx.executeBlocking(() -> {
|
||||
return probe(host, port, path, timeout);
|
||||
}).onSuccess(statusCode -> {
|
||||
boolean success = matchesStatusCode(statusCode, matcher);
|
||||
if (success) {
|
||||
state.consecutiveFailures = 0;
|
||||
state.consecutiveSuccesses++;
|
||||
if (state.consecutiveSuccesses >= healthyThreshold) {
|
||||
state.status = "healthy";
|
||||
}
|
||||
} else {
|
||||
state.consecutiveSuccesses = 0;
|
||||
state.consecutiveFailures++;
|
||||
if (state.consecutiveFailures >= unhealthyThreshold) {
|
||||
state.status = "unhealthy";
|
||||
}
|
||||
}
|
||||
}).onFailure(err -> {
|
||||
state.consecutiveSuccesses = 0;
|
||||
state.consecutiveFailures++;
|
||||
if (state.consecutiveFailures >= unhealthyThreshold) {
|
||||
state.status = "unhealthy";
|
||||
}
|
||||
LOG.debugv("Health check failed for {0}:{1} - {2}", host, port, err.getMessage());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private int probe(String host, int port, String path, int timeoutSeconds) throws IOException {
|
||||
URL url = new URL("http", host, port, path);
|
||||
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
||||
conn.setConnectTimeout(timeoutSeconds * 1000);
|
||||
conn.setReadTimeout(timeoutSeconds * 1000);
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setInstanceFollowRedirects(false);
|
||||
try {
|
||||
conn.connect();
|
||||
return conn.getResponseCode();
|
||||
} finally {
|
||||
conn.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
static boolean matchesStatusCode(int code, String matcher) {
|
||||
String codeStr = String.valueOf(code);
|
||||
if (matcher.contains("-")) {
|
||||
String[] range = matcher.split("-", 2);
|
||||
try {
|
||||
int low = Integer.parseInt(range[0].trim());
|
||||
int high = Integer.parseInt(range[1].trim());
|
||||
return code >= low && code <= high;
|
||||
} catch (NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return Arrays.stream(matcher.split(","))
|
||||
.map(String::trim)
|
||||
.anyMatch(codeStr::equals);
|
||||
}
|
||||
|
||||
private static String stateKey(String targetId, int port) {
|
||||
return targetId + ":" + port;
|
||||
}
|
||||
|
||||
private static class TargetState {
|
||||
volatile String status = "initial";
|
||||
volatile int consecutiveSuccesses = 0;
|
||||
volatile int consecutiveFailures = 0;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.*;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
@@ -13,6 +14,12 @@ import java.util.stream.Collectors;
|
||||
@ApplicationScoped
|
||||
public class ElbV2Service {
|
||||
|
||||
@Inject
|
||||
ElbV2DataPlane dataPlane;
|
||||
|
||||
@Inject
|
||||
ElbV2HealthChecker healthChecker;
|
||||
|
||||
private static final String CANONICAL_HOSTED_ZONE_ID = "Z35SXDOTRQ7X7K";
|
||||
private static final String DEFAULT_ACCOUNT = "000000000000";
|
||||
|
||||
@@ -112,6 +119,7 @@ public class ElbV2Service {
|
||||
Map<String, Listener> regionListeners = listeners.getOrDefault(region, Map.of());
|
||||
Map<String, Rule> regionRules = rules.getOrDefault(region, Map.of());
|
||||
for (String listenerArn : listenerArns) {
|
||||
dataPlane.stopListener(listenerArn);
|
||||
regionListeners.remove(listenerArn);
|
||||
List<String> ruleArns = listenerToRules.remove(listenerArn);
|
||||
if (ruleArns != null) {
|
||||
@@ -198,6 +206,7 @@ public class ElbV2Service {
|
||||
if (!initialTags.isEmpty()) {
|
||||
tags.put(arn, new LinkedHashMap<>(initialTags));
|
||||
}
|
||||
healthChecker.startMonitoring(tg);
|
||||
return tg;
|
||||
}
|
||||
|
||||
@@ -235,6 +244,7 @@ public class ElbV2Service {
|
||||
throw new AwsException("ResourceInUse",
|
||||
"Target group '" + tg.getTargetGroupName() + "' is currently in use by a listener or rule.", 400);
|
||||
}
|
||||
healthChecker.stopMonitoring(arn);
|
||||
targetGroups.getOrDefault(region, Map.of()).remove(arn);
|
||||
tgToLbs.remove(arn);
|
||||
tags.remove(arn);
|
||||
@@ -314,6 +324,7 @@ public class ElbV2Service {
|
||||
if (!initialTags.isEmpty()) {
|
||||
tags.put(listenerArn, new LinkedHashMap<>(initialTags));
|
||||
}
|
||||
dataPlane.startListener(listener, region, getListenerRules(region, listenerArn));
|
||||
return listener;
|
||||
}
|
||||
|
||||
@@ -339,6 +350,7 @@ public class ElbV2Service {
|
||||
if (listener == null) {
|
||||
return;
|
||||
}
|
||||
dataPlane.stopListener(listenerArn);
|
||||
lbToListeners.getOrDefault(listener.getLoadBalancerArn(), List.of()).remove(listenerArn);
|
||||
|
||||
Map<String, Rule> regionRules = rules.getOrDefault(region, Map.of());
|
||||
@@ -378,6 +390,8 @@ public class ElbV2Service {
|
||||
.filter(r -> r != null && r.isDefault())
|
||||
.forEach(r -> r.setActions(new ArrayList<>(defaultActions)));
|
||||
}
|
||||
dataPlane.stopListener(listenerArn);
|
||||
dataPlane.startListener(requireListener(region, listenerArn), region, getListenerRules(region, listenerArn));
|
||||
return listener;
|
||||
}
|
||||
|
||||
@@ -430,6 +444,7 @@ public class ElbV2Service {
|
||||
if (!initialTags.isEmpty()) {
|
||||
tags.put(ruleArn, new LinkedHashMap<>(initialTags));
|
||||
}
|
||||
dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));
|
||||
return rule;
|
||||
}
|
||||
|
||||
@@ -462,15 +477,19 @@ public class ElbV2Service {
|
||||
throw new AwsException("OperationNotPermitted",
|
||||
"The default rule for a listener cannot be deleted.", 400);
|
||||
}
|
||||
String listenerArn = rule.getListenerArn();
|
||||
regionRules.remove(ruleArn);
|
||||
listenerToRules.getOrDefault(rule.getListenerArn(), List.of()).remove(ruleArn);
|
||||
listenerToRules.getOrDefault(listenerArn, List.of()).remove(ruleArn);
|
||||
tags.remove(ruleArn);
|
||||
dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));
|
||||
}
|
||||
|
||||
public Rule modifyRule(String region, String ruleArn, List<RuleCondition> conditions, List<Action> actions) {
|
||||
Rule rule = requireRule(region, ruleArn);
|
||||
String listenerArn = rule.getListenerArn();
|
||||
if (conditions != null) rule.setConditions(new ArrayList<>(conditions));
|
||||
if (actions != null) rule.setActions(new ArrayList<>(actions));
|
||||
dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));
|
||||
return rule;
|
||||
}
|
||||
|
||||
@@ -509,6 +528,11 @@ public class ElbV2Service {
|
||||
|
||||
// commit
|
||||
arnToPriority.forEach((arn, priority) -> regionRules.get(arn).setPriority(String.valueOf(priority)));
|
||||
|
||||
Set<String> affectedListeners = arnToPriority.keySet().stream()
|
||||
.map(arn -> regionRules.get(arn).getListenerArn())
|
||||
.collect(Collectors.toSet());
|
||||
affectedListeners.forEach(la -> dataPlane.recompileRules(la, getListenerRules(region, la)));
|
||||
}
|
||||
|
||||
// ── Targets ───────────────────────────────────────────────────────────────
|
||||
@@ -521,6 +545,7 @@ public class ElbV2Service {
|
||||
existing.removeIf(e -> e.getId().equals(t.getId()) && Objects.equals(e.getPort(), t.getPort()));
|
||||
existing.add(t);
|
||||
}
|
||||
healthChecker.addTargets(tgArn, targets, tg);
|
||||
}
|
||||
|
||||
public void deregisterTargets(String region, String tgArn, List<TargetDescription> targets) {
|
||||
@@ -528,6 +553,7 @@ public class ElbV2Service {
|
||||
for (TargetDescription t : targets) {
|
||||
tg.getTargets().removeIf(e -> e.getId().equals(t.getId()) && Objects.equals(e.getPort(), t.getPort()));
|
||||
}
|
||||
healthChecker.removeTargets(tgArn, targets, tg);
|
||||
}
|
||||
|
||||
public List<TargetHealth> describeTargetHealth(String region, String tgArn,
|
||||
@@ -539,10 +565,17 @@ public class ElbV2Service {
|
||||
return candidates.stream().map(t -> {
|
||||
TargetHealth th = new TargetHealth();
|
||||
th.setTarget(t);
|
||||
th.setHealthCheckPort(tg.getHealthCheckPort() != null ? tg.getHealthCheckPort() : "traffic-port");
|
||||
th.setState("initial");
|
||||
th.setReason("Elb.RegistrationInProgress");
|
||||
th.setDescription("Target registration is in progress");
|
||||
int port = ElbV2HealthChecker.effectivePort(t, tg);
|
||||
th.setHealthCheckPort(String.valueOf(port));
|
||||
String state = healthChecker.getState(tgArn, t.getId(), port);
|
||||
th.setState(state);
|
||||
if ("initial".equals(state)) {
|
||||
th.setReason("Elb.RegistrationInProgress");
|
||||
th.setDescription("Target registration is in progress");
|
||||
} else if ("unhealthy".equals(state)) {
|
||||
th.setReason("Target.FailedHealthChecks");
|
||||
th.setDescription("Health checks failed");
|
||||
}
|
||||
return th;
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
@@ -630,6 +663,56 @@ public class ElbV2Service {
|
||||
return r;
|
||||
}
|
||||
|
||||
public TargetGroup getTargetGroup(String region, String arn) {
|
||||
return targetGroups.getOrDefault(region, Map.of()).get(arn);
|
||||
}
|
||||
|
||||
public TargetGroup getTargetGroupByName(String region, String name) {
|
||||
return targetGroups.getOrDefault(region, Map.of()).values().stream()
|
||||
.filter(tg -> tg.getTargetGroupName().equals(name))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public void shiftListenerForward(String region, String listenerArn,
|
||||
String blueTgArn, String greenTgArn, int greenWeightPct) {
|
||||
Rule defaultRule = listenerToRules.getOrDefault(listenerArn, List.of()).stream()
|
||||
.map(arn -> rules.getOrDefault(region, Map.of()).get(arn))
|
||||
.filter(r -> r != null && r.isDefault())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (defaultRule == null) {
|
||||
return;
|
||||
}
|
||||
Action action = new Action();
|
||||
action.setType("forward");
|
||||
if (greenWeightPct >= 100) {
|
||||
action.setTargetGroupArn(greenTgArn);
|
||||
} else {
|
||||
Action.TargetGroupTuple blueTuple = new Action.TargetGroupTuple();
|
||||
blueTuple.setTargetGroupArn(blueTgArn);
|
||||
blueTuple.setWeight(100 - greenWeightPct);
|
||||
Action.TargetGroupTuple greenTuple = new Action.TargetGroupTuple();
|
||||
greenTuple.setTargetGroupArn(greenTgArn);
|
||||
greenTuple.setWeight(greenWeightPct);
|
||||
action.setTargetGroups(List.of(blueTuple, greenTuple));
|
||||
}
|
||||
defaultRule.setActions(List.of(action));
|
||||
dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));
|
||||
}
|
||||
|
||||
private List<Rule> getListenerRules(String region, String listenerArn) {
|
||||
Map<String, Rule> regionRules = rules.getOrDefault(region, Map.of());
|
||||
return listenerToRules.getOrDefault(listenerArn, List.of()).stream()
|
||||
.map(regionRules::get)
|
||||
.filter(Objects::nonNull)
|
||||
.sorted(Comparator.comparingInt(r -> {
|
||||
if ("default".equals(r.getPriority())) return Integer.MAX_VALUE;
|
||||
try { return Integer.parseInt(r.getPriority()); } catch (NumberFormatException e) { return Integer.MAX_VALUE; }
|
||||
}))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static void validateName(String name, String resource) {
|
||||
if (name == null || name.isEmpty()) {
|
||||
throw new AwsException("ValidationError", "Name is required for " + resource + ".", 400);
|
||||
|
||||
@@ -548,6 +548,12 @@ public class LambdaService {
|
||||
}
|
||||
codeStore.delete(functionName);
|
||||
functionStore.delete(region, functionName);
|
||||
versionCounters.remove(region + "::" + functionName);
|
||||
if (aliasStore != null) {
|
||||
for (LambdaAlias alias : aliasStore.list(region, functionName)) {
|
||||
aliasStore.delete(region, functionName, alias.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
LOG.infov("Deleted Lambda function: {0}", functionName);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user