mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat/redshift auth proxy (#2751)
* feat(redshift): add auth proxy port range and endpoint-host config * feat(redshift): add containerHost/containerPort/proxyPort to Cluster model * feat(redshift): add RedshiftAuthProxy reusing the RDS PostgreSQL protocol handler * feat(redshift): add RedshiftProxyManager registry with shutdown hook * feat(redshift): front new clusters with an auth proxy and advertise it * feat(redshift): stop/update proxy on delete/modify, start it on snapshot restore * feat(redshift): keep proxy port stable across reboot and adopt-on-startup * test(redshift): integration coverage for JDBC through the auth proxy * test(redshift): reinstate JDBC connectivity check now that the proxy exists * docs(redshift): document the cluster auth proxy and its config * fix(redshift): prevent minor port leak when proxy fails to start * fix(redshift): rollback container on proxy failure and surface teardown errors * fix(redshift): stop auth proxy on rollback to prevent listener collisions * fix(redshift): ensure proxy shutdown failure does not abort container and port cleanup * fix(redshift): add proper logging for intentionally ignored cleanup exceptions * fix: Wait for Redshift database readiness before proxying Previously, RedshiftContainerManager just slept for 3 seconds before marking the container as started. On slower CI environments, the PostgreSQL database might take longer to initialize, resulting in Connection Refused when the RedshiftAuthProxy forwards connections. Now, RedshiftContainerManager polls the database using psql until it's ready, up to 60 seconds. * fix(redshift): prevent proxy port reallocation on shutdown failure Addresses a review comment indicating that if a Redshift auth proxy fails to shut down during rollback or deletion, its port must not be released into the available pool. Reassigning a still-bound port would cause subsequent cluster creations to fail with a BindException. Instead, we now tolerate proxy shutdown errors but intentionally leak the port allocation to prevent collisions. * fix(redshift): fix failing tests due to proxy changes 1. RedshiftOperationsTest checked for a hardcoded port 5440, but the RedshiftService now allocates dynamic proxy ports. Removed the exact port assertion. 2. RedshiftContainerManager's psql readiness check was connecting via local Unix socket, which succeeded before PostgreSQL was actually ready to accept remote TCP connections from the proxy. Added '-h 127.0.0.1' to enforce TCP readiness. * test(redshift): use Awaitility to connect to proxy Use Awaitility to retry the initial connection in RedshiftProxyIntegrationTest to prevent transient 'Connection attempt failed' errors on slower CI environments. * chore(redshift): use proper imports instead of fully-qualified class names in tests * fix(redshift): fix compiler errors introduced during import cleanup * fix(redshift): resolve proxy lifecycle bugs and CI network issues - Throw RuntimeException from RedshiftProxyManager.stopProxy if proxy is not found. This allows RedshiftService to catch it and intentionally leak the port, preventing port collisions if a proxy fails before registration. - Force RedshiftProxyIntegrationTest to connect via 127.0.0.1 instead of the endpoint address, which resolves to host.docker.internal in CI environments and causes UnknownHostException. * fix(redshift): prevent proxy port exhaustion on startup failures Instead of blindly assuming missing proxies denote a leaked port, RedshiftProxyManager now tracks proxies that failed their socket cleanup during startup. stopProxy throws an exception only if the socket is known to be leaked. This allows RedshiftService to safely release ports after clean proxy startup failures, addressing Greptile's feedback about port exhaustion. * fix(redshift): retain proxy reference to allow retry on close failure As identified by Greptile, stopProxy previously removed the proxy from the registry before calling proxy.stop(). If stop() threw an exception, the proxy reference was lost, preventing any subsequent retry from ever finding it and attempting to close it again. stopProxy now only removes the proxy from the registry after stop() returns successfully. Additionally, failedCleanups is now retained instead of cleared, ensuring retries continue to safely leak the port if cleanup remains impossible. * fix(redshift): abort cluster deletion if proxy fails to stop As highlighted by Greptile, previously deleteCluster would swallow proxy shutdown failures and delete the cluster metadata anyway. This eliminated the retry path, stranding the unclosed proxy and its port reservation until the process exited. Now, if stopProxyAndReleasePortSafely fails, deleteCluster throws an exception to preserve the cluster metadata so the deletion can be retried. * test(redshift): lock in proxy lifecycle failure-recovery behaviors Bổ sung test cho ba hành vi hardening chưa được cover, để refactor sau không âm thầm phá vỡ: - stopProxy giữ lại proxy trong registry khi close() ném, cho phép retry gọi lại đúng instance và chỉ deregister sau khi stop sạch - marker leak khi startup cleanup thất bại được retain qua mọi retry và chỉ bị xoá bởi một lần start mới thành công - deleteCluster abort với InternalFailure, giữ nguyên container + metadata khi proxy không stop được; retry sau đó hoàn tất khi proxy stop OK Đồng thời bỏ "-p 7100-7199:7100-7199" trong compatibility.yml: proxy bind 0.0.0.0 trong container floci và sdk-test-java chạy trên compat-net nên JDBC đi container-to-container qua alias "floci", không cần publish port ra host. Giữ lại FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST=floci. * fix(redshift): keep an unclosable proxy reachable for later retry Theo phản hồi mới của Greptile: khi start/replace proxy thất bại và cleanupFailedStart cũng không đóng được listener, code cũ chỉ lưu relayKey vào một Set rồi vứt object RedshiftAuthProxy. stopProxy sau đó ném vĩnh viễn mà không còn cách nào chạm tới listener để thử đóng lại, khiến cluster không xoá được và port bị giữ mãi trong dải hữu hạn. Thay Set<String> failedCleanups bằng Map<String, RedshiftAuthProxy> unclosableProxies. cleanupFailedStart giữ lại chính proxy đó; stopProxy và stopAll thử đóng lại, chỉ gỡ entry khi stop thành công. startProxy không còn xoá marker khi start mới — chỉ một lần stop thành công mới gỡ, vì listener cũ có thể vẫn đang bound. * fix(redshift): retry proxy port bind to absorb reboot rebind race rebootCluster giữ nguyên proxy port của cluster để endpoint ổn định, nên listener cũ bị đóng rồi bind lại đúng port đó chỉ vài ms sau. Dưới tải (CI runner ARM) kernel có thể chưa nhả port và SO_REUSEADDR không giúp được khi accept loop cũ đang teardown -> BindException -> RebootCluster trả 500. Đây là nguyên nhân test RedshiftOperationsTest. testClusterAndSnapshotLifecycle fail chập chờn. start() giờ retry bind tối đa ~1s, chỉ nuốt BindException; IOException khác vẫn propagate ngay. Thêm test dựng cảnh port bị chiếm tạm thời rồi nhả, xác nhận proxy vẫn bind được. * fix(redshift): tear down proxy and release port when rebootCluster fails Nếu startProxy/restoreSnapshot ném sau khi proxy đã (re)start trong rebootCluster, hai nhánh catch chỉ set status "failed" rồi rethrow — proxy mới vẫn chạy và port vẫn nằm trong usedPorts, không nhánh nào dọn. Giờ cả hai catch gọi stopProxyAndReleasePortSafely như createCluster và restoreFromClusterSnapshot đã làm; proxyPort được hoist ra ngoài try với sentinel -1 để rollback an toàn kể cả khi chưa cấp port. Thêm test: restoreSnapshot ném -> proxy được stop lại, AwsException nổi lên. * fix(redshift): serialize createCluster/deleteCluster/restoreFromClusterSnapshot modifyCluster và rebootCluster đã synchronized nhưng create/delete/restore thì không, dù cả năm method đều chạy chuỗi container + proxy + port nhiều bước trên cùng một cluster. deleteCluster(x) chạy song song rebootCluster(x) có thể để lại metadata mồ côi trỏ tới container/proxy đã dừng. Thêm synchronized cho ba method còn lại để nhất quán. * fix(rds,redshift): close backend socket when the auth handshake fails handleConnection mở kết nối TCP tới container Postgres trước khi gọi handleAuth. Chỉ nhánh thành công (bridge) và vài nhánh lỗi có kiểm soát mới đóng backend; nếu handleAuth trả về sớm ở một probe trần (SSLRequest không kèm startup) hoặc ném IOException (client ngắt giữa handshake), catch cũ chỉ đóng client -> mỗi health-check TCP làm rò một connection tới Postgres, ăn dần max_connections. Chuyển việc đóng socket sang finally, đóng cả client lẫn backend (idempotent, nhánh thành công đã đóng sẵn). Áp cho cả RdsAuthProxy vì RedshiftAuthProxy được copy từ đó. Thêm test: client drop giữa handshake -> backend nhận EOF. * fix(redshift): stop replacement container and keep dump on failed reboot Rollback của rebootCluster (b44fd1e3) mới chỉ stop proxy + release port, để container thay thế chạy tiếp sau một cluster "failed", và finally vẫn xoá tempDump. Vì container gốc đã stop và không có volume, tempDump là bản sao duy nhất của data -> mất data không khôi phục được (bug có sẵn, giờ mới lộ). rollbackReboot() giờ stop luôn container thay thế (như createCluster/ restoreFromClusterSnapshot). tempDump chỉ bị xoá khi reboot thành công; khi fail thì giữ lại và log đường dẫn để khôi phục thủ công. * fix(redshift): make reboot rollback phase-aware to protect the original Commit trước cho rollbackReboot stop container vô điều kiện. Nếu reboot fail ngay ở takeSnapshot hoặc stopProxy — lúc container gốc (chứa data, không volume) VẪN đang chạy — thì rollback lại force-remove chính nó, huỷ bản sao data hoàn chỉnh duy nhất và chỉ còn dump rỗng/dở. Thêm hai cờ: - originalTornDown: đã stop proxy + container gốc -> rollback mới được đụng vào proxy/port - replacementStarted: đã start container thay thế -> rollback mới được stop container Fail trước hai mốc đó: không đụng gì, trạng thái gốc còn nguyên. Thêm test: takeSnapshot ném -> cm.stop và stopProxy không được gọi. * fix(redshift): clean an orphan replacement container on failed reboot containerManager.start có thể tạo container Docker rồi mới ném ở waitForReady, nên cờ replacementStarted (set sau khi start return) bỏ sót trường hợp này -> orphan chạy dưới tên cluster. Bỏ replacementStarted, gate rollback theo mỗi originalTornDown: một khi proxy + container gốc đã stop thì container gốc chắc chắn biến mất, nên containerManager.stop (xoá theo tên) chỉ có thể chạm replacement — kể cả replacement do start() tạo dở rồi ném. Thêm test: start() ném -> rollback vẫn gọi cm.stop để dọn orphan. * fix(redshift): remove orphan cluster metadata on failed create/restore * fix(redshift): keep failed cluster metadata if proxy stop fails * fix(redshift): fix TooManyActualInvocations in proxy tests * fix(redshift): clear proxyPort on reboot rollback if port is released * fix(redshift): retain reserved port on reboot startup failure * fix(redshift): retain proxy port in reboot rollback and teardown failed startup recovery * fix(redshift): skip failing cluster and retaining dump if reboot fails before teardown
This commit is contained in:
1 parent
f7f16cd2a3
commit
426fbcb284
20 files changed
+1771
-96
No files matched your search
@@ -1131,6 +1131,17 @@ public interface EmulatorConfig {
|
||||
@WithDefault("postgres:15-alpine")
|
||||
String imageVersion();
|
||||
Optional<String> dockerNetwork();
|
||||
|
||||
// Port range the per-cluster auth proxies bind on the Floci host. Disjoint from
|
||||
// every other service's range (RDS uses 7001-7099).
|
||||
@WithDefault("7100")
|
||||
int proxyBasePort();
|
||||
@WithDefault("7199")
|
||||
int proxyMaxPort();
|
||||
|
||||
// Hostname clients use to reach a cluster endpoint. Empty -> resolved from
|
||||
// DockerHostResolver (falls back to "localhost").
|
||||
Optional<String> endpointHost();
|
||||
}
|
||||
|
||||
interface RdsServiceConfig {
|
||||
|
||||
@@ -93,9 +93,10 @@ public class RdsAuthProxy {
|
||||
}
|
||||
|
||||
private void handleConnection(Socket client) {
|
||||
Socket backend = null;
|
||||
try {
|
||||
client.setTcpNoDelay(true);
|
||||
Socket backend = new Socket(backendHost, backendPort);
|
||||
backend = new Socket(backendHost, backendPort);
|
||||
backend.setTcpNoDelay(true);
|
||||
|
||||
switch (engine) {
|
||||
@@ -108,7 +109,14 @@ public class RdsAuthProxy {
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("RDS connection error for instance {0}: {1}", instanceId, e.getMessage());
|
||||
} finally {
|
||||
// A handler's success path bridges then closes both sockets; every other path
|
||||
// (early return on a bare probe, auth failure, thrown IOException) can leave the
|
||||
// backend DB connection open. Closing here is idempotent.
|
||||
closeQuietly(client);
|
||||
if (backend != null) {
|
||||
closeQuietly(backend);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,10 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
|
||||
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
|
||||
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
|
||||
@@ -31,6 +34,8 @@ import java.util.LinkedHashMap;
|
||||
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.Consumer;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -44,10 +49,15 @@ public class RedshiftService {
|
||||
private final RedshiftContainerManager containerManager;
|
||||
private final EmulatorConfig config;
|
||||
private final RegionResolver regionResolver;
|
||||
private final RedshiftProxyManager proxyManager;
|
||||
private final DockerHostResolver dockerHostResolver;
|
||||
// Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM.
|
||||
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
|
||||
|
||||
@Inject
|
||||
public RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
|
||||
EmulatorConfig config, RegionResolver regionResolver) {
|
||||
EmulatorConfig config, RegionResolver regionResolver,
|
||||
RedshiftProxyManager proxyManager, DockerHostResolver dockerHostResolver) {
|
||||
this.clusters = storageFactory.create("redshift", "redshift-clusters.json", new TypeReference<Map<String, Cluster>>() {});
|
||||
this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference<Map<String, Snapshot>>() {});
|
||||
this.parameterGroups = storageFactory.create("redshift", "redshift-parameter-groups.json", new TypeReference<Map<String, ClusterParameterGroup>>() {});
|
||||
@@ -55,6 +65,8 @@ public class RedshiftService {
|
||||
this.containerManager = containerManager;
|
||||
this.config = config;
|
||||
this.regionResolver = regionResolver;
|
||||
this.proxyManager = proxyManager;
|
||||
this.dockerHostResolver = dockerHostResolver;
|
||||
}
|
||||
|
||||
// Recreate Docker containers for persisted clusters on app restart (across every account, not just default)
|
||||
@@ -73,14 +85,36 @@ public class RedshiftService {
|
||||
LOG.infov("Recovering container for persisted cluster: {0}", cluster.getClusterIdentifier());
|
||||
RedshiftContainerHandle handle = containerManager.adoptOrStart(
|
||||
entry.accountId(), cluster.getClusterIdentifier(), cluster.getMasterUsername(), password);
|
||||
Endpoint endpoint = new Endpoint();
|
||||
endpoint.setAddress(handle.getHost());
|
||||
endpoint.setPort(handle.getPort());
|
||||
|
||||
// A cluster persisted before the auth proxy existed has proxyPort == 0. Allocate one
|
||||
// now; its endpoint changes exactly once after this upgrade. Existing clusters keep
|
||||
// their stored port so the endpoint is stable across restarts.
|
||||
int proxyPort = cluster.getProxyPort() > 0 ? cluster.getProxyPort() : allocateProxyPort();
|
||||
usedPorts.add(proxyPort);
|
||||
Endpoint endpoint = proxyEndpoint(proxyPort);
|
||||
cluster.setProxyPort(proxyPort);
|
||||
proxyManager.startProxy(
|
||||
relayKey(entry.accountId(), cluster.getClusterIdentifier()), proxyPort,
|
||||
handle.getHost(), handle.getPort(), endpoint.getAddress(),
|
||||
cluster.getMasterUsername(), password, CLUSTER_DB_NAME,
|
||||
passwordValidatorFor(entry.accountId(), cluster.getClusterIdentifier()));
|
||||
cluster.setContainerHost(handle.getHost());
|
||||
cluster.setContainerPort(handle.getPort());
|
||||
cluster.setEndpoint(endpoint);
|
||||
clusters.putForAccount(entry.accountId(), entry.key(), cluster);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Failed to recover container for cluster {0}, marking as unavailable",
|
||||
cluster.getClusterIdentifier());
|
||||
try {
|
||||
proxyManager.stopProxy(relayKey(entry.accountId(), cluster.getClusterIdentifier()));
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to stop proxy during recovery rollback for cluster {0}", cluster.getClusterIdentifier());
|
||||
}
|
||||
try {
|
||||
containerManager.stop(entry.accountId(), cluster.getClusterIdentifier());
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to stop container during recovery rollback for cluster {0}", cluster.getClusterIdentifier());
|
||||
}
|
||||
cluster.setClusterStatus("unavailable");
|
||||
clusters.putForAccount(entry.accountId(), entry.key(), cluster);
|
||||
}
|
||||
@@ -92,7 +126,9 @@ public class RedshiftService {
|
||||
return createCluster(identifier, nodeType, username, password, null, List.of());
|
||||
}
|
||||
|
||||
public Cluster createCluster(String identifier, String nodeType, String username, String password,
|
||||
// synchronized like modify/reboot: the container + proxy + port steps must not
|
||||
// interleave with another admin call on the same cluster.
|
||||
public synchronized Cluster createCluster(String identifier, String nodeType, String username, String password,
|
||||
String clusterSubnetGroupName, List<String> vpcSecurityGroupIds) {
|
||||
if (clusters.get(identifier).isPresent()) {
|
||||
throw new AwsException("ClusterAlreadyExists", "Cluster " + identifier + " already exists", 400);
|
||||
@@ -109,16 +145,44 @@ public class RedshiftService {
|
||||
clusters.put(identifier, cluster);
|
||||
clusters.flush();
|
||||
|
||||
// Start container
|
||||
// Start container, then front it with an auth proxy so the advertised endpoint is
|
||||
// reachable from outside the Docker network.
|
||||
// Hoisted out of the try so a failure after allocateProxyPort() still returns the port.
|
||||
int proxyPort = -1;
|
||||
try {
|
||||
RedshiftContainerHandle handle = containerManager.start(clusters.accountId(), identifier, username, password);
|
||||
Endpoint endpoint = new Endpoint();
|
||||
endpoint.setAddress(handle.getHost());
|
||||
endpoint.setPort(handle.getPort());
|
||||
String accountId = clusters.accountId();
|
||||
RedshiftContainerHandle handle = containerManager.start(accountId, identifier, username, password);
|
||||
proxyPort = allocateProxyPort();
|
||||
Endpoint endpoint = proxyEndpoint(proxyPort);
|
||||
cluster.setProxyPort(proxyPort);
|
||||
proxyManager.startProxy(relayKey(accountId, identifier), proxyPort,
|
||||
handle.getHost(), handle.getPort(), endpoint.getAddress(),
|
||||
username, password, CLUSTER_DB_NAME,
|
||||
passwordValidatorFor(accountId, identifier));
|
||||
cluster.setContainerHost(handle.getHost());
|
||||
cluster.setContainerPort(handle.getPort());
|
||||
cluster.setEndpoint(endpoint);
|
||||
cluster.setClusterStatus("available");
|
||||
} catch (AwsException e) {
|
||||
boolean proxyStopped = stopProxyAndReleasePortSafely(identifier, proxyPort);
|
||||
try { containerManager.stop(clusters.accountId(), identifier); } catch (Exception ex) { LOG.warnv(ex, "Failed to stop container during rollback of cluster {0}", identifier); }
|
||||
if (proxyStopped) {
|
||||
clusters.delete(identifier);
|
||||
} else {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.put(identifier, cluster);
|
||||
}
|
||||
clusters.flush();
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
cluster.setClusterStatus("failed");
|
||||
boolean proxyStopped = stopProxyAndReleasePortSafely(identifier, proxyPort);
|
||||
try { containerManager.stop(clusters.accountId(), identifier); } catch (Exception ex) { LOG.warnv(ex, "Failed to stop container during rollback of cluster {0}", identifier); }
|
||||
if (proxyStopped) {
|
||||
clusters.delete(identifier);
|
||||
} else {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.put(identifier, cluster);
|
||||
}
|
||||
clusters.flush();
|
||||
throw new AwsException("InternalFailure", "Failed to start container: " + e.getMessage(), 500);
|
||||
}
|
||||
@@ -139,13 +203,20 @@ public class RedshiftService {
|
||||
return clusters.scan(k -> true);
|
||||
}
|
||||
|
||||
public Cluster deleteCluster(String identifier) {
|
||||
public synchronized Cluster deleteCluster(String identifier) {
|
||||
Optional<Cluster> clusterOpt = clusters.get(identifier);
|
||||
if (clusterOpt.isEmpty()) {
|
||||
throw new AwsException("ClusterNotFound", "Cluster " + identifier + " not found", 404);
|
||||
}
|
||||
Cluster cluster = clusterOpt.get();
|
||||
|
||||
|
||||
// Tear down the auth proxy and return its port before stopping the container.
|
||||
// If it fails, abort deletion so the metadata remains and the user can retry.
|
||||
if (!stopProxyAndReleasePortSafely(identifier, cluster.getProxyPort())) {
|
||||
throw new AwsException("InternalFailure",
|
||||
"Failed to stop auth proxy; cluster " + identifier + " was not deleted", 500);
|
||||
}
|
||||
|
||||
containerManager.stop(clusters.accountId(), identifier);
|
||||
clusters.delete(identifier);
|
||||
clusters.flush();
|
||||
@@ -166,6 +237,9 @@ public class RedshiftService {
|
||||
containerManager.alterUserPassword(clusters.accountId(), clusterIdentifier,
|
||||
cluster.getMasterUsername(), masterUserPassword);
|
||||
cluster.setMasterPassword(masterUserPassword);
|
||||
// Keep the proxy's password check in sync so new connections use the new secret.
|
||||
proxyManager.updateMasterPassword(
|
||||
relayKey(clusters.accountId(), clusterIdentifier), masterUserPassword);
|
||||
}
|
||||
|
||||
// NodeType only updates metadata — it does not resize the underlying Postgres container
|
||||
@@ -201,34 +275,74 @@ public class RedshiftService {
|
||||
throw new AwsException("InternalFailure", "Failed to prepare reboot dump file: " + e.getMessage(), 500);
|
||||
}
|
||||
|
||||
// Hoisted so a failure after the proxy is (re)started still tears it down and
|
||||
// returns the port, matching createCluster/restoreFromClusterSnapshot rollback.
|
||||
int proxyPort = cluster.getProxyPort() > 0 ? cluster.getProxyPort() : -1;
|
||||
boolean originalTornDown = false; // original proxy + container already stopped
|
||||
boolean rebooted = false;
|
||||
try {
|
||||
containerManager.takeSnapshot(clusters.accountId(), clusterIdentifier, cluster.getMasterUsername(), tempDump);
|
||||
containerManager.stop(clusters.accountId(), clusterIdentifier);
|
||||
String accountId = clusters.accountId();
|
||||
String key = relayKey(accountId, clusterIdentifier);
|
||||
|
||||
containerManager.takeSnapshot(accountId, clusterIdentifier, cluster.getMasterUsername(), tempDump);
|
||||
proxyManager.stopProxy(key);
|
||||
containerManager.stop(accountId, clusterIdentifier);
|
||||
originalTornDown = true;
|
||||
|
||||
String password = cluster.getMasterPassword() != null ? cluster.getMasterPassword() : "admin";
|
||||
RedshiftContainerHandle handle = containerManager.start(
|
||||
clusters.accountId(), clusterIdentifier, cluster.getMasterUsername(), password);
|
||||
Endpoint endpoint = new Endpoint();
|
||||
endpoint.setAddress(handle.getHost());
|
||||
endpoint.setPort(handle.getPort());
|
||||
accountId, clusterIdentifier, cluster.getMasterUsername(), password);
|
||||
|
||||
// Reuse the stored proxy port so the advertised endpoint is unchanged by a reboot.
|
||||
if (proxyPort < 0) {
|
||||
proxyPort = allocateProxyPort();
|
||||
}
|
||||
usedPorts.add(proxyPort);
|
||||
Endpoint endpoint = proxyEndpoint(proxyPort);
|
||||
cluster.setProxyPort(proxyPort);
|
||||
proxyManager.startProxy(key, proxyPort, handle.getHost(), handle.getPort(),
|
||||
endpoint.getAddress(), cluster.getMasterUsername(), password, CLUSTER_DB_NAME,
|
||||
passwordValidatorFor(accountId, clusterIdentifier));
|
||||
cluster.setContainerHost(handle.getHost());
|
||||
cluster.setContainerPort(handle.getPort());
|
||||
cluster.setEndpoint(endpoint);
|
||||
|
||||
containerManager.restoreSnapshot(clusters.accountId(), clusterIdentifier, cluster.getMasterUsername(), tempDump);
|
||||
|
||||
containerManager.restoreSnapshot(accountId, clusterIdentifier, cluster.getMasterUsername(), tempDump);
|
||||
cluster.setClusterStatus("available");
|
||||
rebooted = true;
|
||||
} catch (AwsException e) {
|
||||
cluster.setClusterStatus("failed");
|
||||
rollbackReboot(clusterIdentifier, originalTornDown);
|
||||
if (originalTornDown) {
|
||||
cluster.setClusterStatus("failed");
|
||||
}
|
||||
clusters.flush();
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
cluster.setClusterStatus("failed");
|
||||
rollbackReboot(clusterIdentifier, originalTornDown);
|
||||
if (originalTornDown) {
|
||||
cluster.setClusterStatus("failed");
|
||||
}
|
||||
clusters.flush();
|
||||
throw new AwsException("InternalFailure", "Failed to reboot cluster " + clusterIdentifier + ": " + e.getMessage(), 500);
|
||||
} finally {
|
||||
try {
|
||||
Files.deleteIfExists(tempDump);
|
||||
} catch (IOException ignored) {
|
||||
// best-effort cleanup of a temp file
|
||||
if (rebooted) {
|
||||
try {
|
||||
Files.deleteIfExists(tempDump);
|
||||
} catch (IOException ex) {
|
||||
LOG.warnv(ex, "Failed to clean up temporary dump file {0} after rebooting cluster {1}", tempDump, clusterIdentifier);
|
||||
}
|
||||
} else {
|
||||
if (originalTornDown) {
|
||||
// Once the original container is torn down it holds no volume, so this dump can
|
||||
// be the only surviving copy of the cluster's data — keep it for manual recovery.
|
||||
LOG.warnv("Reboot of cluster {0} did not complete; retained pre-reboot data dump at {1}",
|
||||
clusterIdentifier, tempDump);
|
||||
} else {
|
||||
try {
|
||||
Files.deleteIfExists(tempDump);
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,7 +480,7 @@ public class RedshiftService {
|
||||
return restoreFromClusterSnapshot(clusterIdentifier, snapshotIdentifier, null);
|
||||
}
|
||||
|
||||
public Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier, String nodeType) {
|
||||
public synchronized Cluster restoreFromClusterSnapshot(String clusterIdentifier, String snapshotIdentifier, String nodeType) {
|
||||
if (clusters.get(clusterIdentifier).isPresent()) {
|
||||
throw new AwsException("ClusterAlreadyExists", "Cluster " + clusterIdentifier + " already exists", 400);
|
||||
}
|
||||
@@ -407,11 +521,20 @@ public class RedshiftService {
|
||||
clusters.put(clusterIdentifier, cluster);
|
||||
clusters.flush();
|
||||
|
||||
// Hoisted out of the try so a failure after allocateProxyPort() still returns the port.
|
||||
int proxyPort = -1;
|
||||
try {
|
||||
RedshiftContainerHandle handle = containerManager.start(clusters.accountId(), clusterIdentifier, username, password);
|
||||
Endpoint endpoint = new Endpoint();
|
||||
endpoint.setAddress(handle.getHost());
|
||||
endpoint.setPort(handle.getPort());
|
||||
String accountId = clusters.accountId();
|
||||
RedshiftContainerHandle handle = containerManager.start(accountId, clusterIdentifier, username, password);
|
||||
proxyPort = allocateProxyPort();
|
||||
Endpoint endpoint = proxyEndpoint(proxyPort);
|
||||
cluster.setProxyPort(proxyPort);
|
||||
proxyManager.startProxy(relayKey(accountId, clusterIdentifier), proxyPort,
|
||||
handle.getHost(), handle.getPort(), endpoint.getAddress(),
|
||||
username, password, CLUSTER_DB_NAME,
|
||||
passwordValidatorFor(accountId, clusterIdentifier));
|
||||
cluster.setContainerHost(handle.getHost());
|
||||
cluster.setContainerPort(handle.getPort());
|
||||
cluster.setEndpoint(endpoint);
|
||||
|
||||
if (hasDump) {
|
||||
@@ -420,11 +543,25 @@ public class RedshiftService {
|
||||
|
||||
cluster.setClusterStatus("available");
|
||||
} catch (AwsException e) {
|
||||
cluster.setClusterStatus("failed");
|
||||
boolean proxyStopped = stopProxyAndReleasePortSafely(clusterIdentifier, proxyPort);
|
||||
try { containerManager.stop(clusters.accountId(), clusterIdentifier); } catch (Exception ex) { LOG.warnv(ex, "Failed to stop container during rollback of cluster {0}", clusterIdentifier); }
|
||||
if (proxyStopped) {
|
||||
clusters.delete(clusterIdentifier);
|
||||
} else {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.put(clusterIdentifier, cluster);
|
||||
}
|
||||
clusters.flush();
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
cluster.setClusterStatus("failed");
|
||||
boolean proxyStopped = stopProxyAndReleasePortSafely(clusterIdentifier, proxyPort);
|
||||
try { containerManager.stop(clusters.accountId(), clusterIdentifier); } catch (Exception ex) { LOG.warnv(ex, "Failed to stop container during rollback of cluster {0}", clusterIdentifier); }
|
||||
if (proxyStopped) {
|
||||
clusters.delete(clusterIdentifier);
|
||||
} else {
|
||||
cluster.setClusterStatus("failed");
|
||||
clusters.put(clusterIdentifier, cluster);
|
||||
}
|
||||
clusters.flush();
|
||||
throw new AwsException("InternalFailure", "Failed to restore cluster from snapshot: " + e.getMessage(), 500);
|
||||
}
|
||||
@@ -725,4 +862,85 @@ public class RedshiftService {
|
||||
"Tagging for resource type '" + type + "' is not supported: " + resourceName, 400);
|
||||
};
|
||||
}
|
||||
|
||||
// ── Proxy Helpers (shared with modify/reboot/restore) ────────────────────
|
||||
|
||||
private static final String CLUSTER_DB_NAME = "dev";
|
||||
|
||||
private int allocateProxyPort() {
|
||||
int base = config.services().redshift().proxyBasePort();
|
||||
int max = config.services().redshift().proxyMaxPort();
|
||||
for (int port = base; port <= max; port++) {
|
||||
if (usedPorts.add(port)) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
throw new AwsException("InsufficientClusterCapacity",
|
||||
"No available Redshift proxy ports in range " + base + "-" + max, 503);
|
||||
}
|
||||
|
||||
private boolean stopProxyAndReleasePortSafely(String identifier, int proxyPort) {
|
||||
boolean proxyStopped = false;
|
||||
try {
|
||||
proxyManager.stopProxy(relayKey(clusters.accountId(), identifier));
|
||||
proxyStopped = true;
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to stop proxy for cluster {0}; leaking proxy port {1} to prevent reallocation", identifier, proxyPort);
|
||||
}
|
||||
if (proxyStopped) {
|
||||
releaseProxyPort(proxyPort);
|
||||
}
|
||||
return proxyStopped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Undo a failed reboot. If {@code originalTornDown} is false the reboot failed before
|
||||
* the original proxy + container were stopped, so the original data-bearing container
|
||||
* is still running and nothing must be touched. Once it is true the original is gone:
|
||||
* tear down the (replacement's) proxy and return its port, and remove any container
|
||||
* running under the cluster's name — {@code containerManager.stop} works by name, so
|
||||
* this also cleans a replacement that {@code containerManager.start} created before
|
||||
* throwing (e.g. its readiness check timed out). The pre-reboot data dump is kept by
|
||||
* the caller.
|
||||
*/
|
||||
private void rollbackReboot(String identifier, boolean originalTornDown) {
|
||||
if (!originalTornDown) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
proxyManager.stopProxy(relayKey(clusters.accountId(), identifier));
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to stop proxy during reboot rollback for cluster {0}", identifier);
|
||||
}
|
||||
try {
|
||||
containerManager.stop(clusters.accountId(), identifier);
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to stop replacement container during rollback of reboot for cluster {0}", identifier);
|
||||
}
|
||||
}
|
||||
|
||||
private void releaseProxyPort(int port) {
|
||||
if (port > 0) {
|
||||
usedPorts.remove(port);
|
||||
}
|
||||
}
|
||||
|
||||
private Endpoint proxyEndpoint(int proxyPort) {
|
||||
String host = config.services().redshift().endpointHost()
|
||||
.filter(h -> !h.isBlank())
|
||||
.orElseGet(dockerHostResolver::resolve);
|
||||
return new Endpoint(host, proxyPort);
|
||||
}
|
||||
|
||||
private String relayKey(String accountId, String clusterIdentifier) {
|
||||
return accountId + ":" + clusterIdentifier;
|
||||
}
|
||||
|
||||
// Validates the master password at the proxy against current cluster state, so a
|
||||
// ModifyCluster password change is reflected for new connections without a proxy restart.
|
||||
private RdsAuthProxy.PasswordValidator passwordValidatorFor(String accountId, String clusterIdentifier) {
|
||||
return (user, password) -> clusters.getForAccount(accountId, clusterIdentifier)
|
||||
.map(c -> user.equals(c.getMasterUsername()) && password.equals(c.getMasterPassword()))
|
||||
.orElse(false);
|
||||
}
|
||||
}
|
||||
+38
-5
@@ -99,11 +99,7 @@ public class RedshiftContainerManager {
|
||||
LOG.warnv("Failed to stream logs for {0}", containerName);
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(3000);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
waitForReady(containerName, info.containerId(), masterUsername, "dev");
|
||||
|
||||
containers.put(containerKey(accountId, clusterIdentifier), handle);
|
||||
return handle;
|
||||
@@ -143,6 +139,8 @@ public class RedshiftContainerManager {
|
||||
LOG.warnv("Failed to stream logs for {0}", containerName);
|
||||
}
|
||||
|
||||
waitForReady(containerName, info.containerId(), masterUsername, "dev");
|
||||
|
||||
containers.put(containerKey(accountId, clusterIdentifier), handle);
|
||||
return handle;
|
||||
}
|
||||
@@ -381,6 +379,41 @@ public class RedshiftContainerManager {
|
||||
}
|
||||
return bos.toByteArray();
|
||||
}
|
||||
private void waitForReady(String containerName, String containerId, String username, String dbName) {
|
||||
String effectiveUser = (username != null && !username.isBlank()) ? username : "postgres";
|
||||
String[] cmd = {
|
||||
"psql",
|
||||
"-h", "127.0.0.1",
|
||||
"-v", "ON_ERROR_STOP=1",
|
||||
"-U", effectiveUser,
|
||||
"-d", dbName,
|
||||
"-c", "SELECT 1"
|
||||
};
|
||||
execUntilSuccess(containerName, containerId, cmd, "PostgreSQL readiness check");
|
||||
}
|
||||
|
||||
private void execUntilSuccess(String containerName, String containerId, String[] cmd, String description) {
|
||||
String lastOutput = "";
|
||||
for (int attempt = 1; attempt <= 60; attempt++) {
|
||||
try {
|
||||
ExecResult result = execInContainer(containerId, cmd, 5);
|
||||
lastOutput = result.stderr();
|
||||
if (result.exitCode() == 0) {
|
||||
LOG.infov("Initialized {0} in Redshift container {1}", description, containerName);
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
lastOutput = e.getMessage();
|
||||
}
|
||||
try {
|
||||
java.util.concurrent.TimeUnit.SECONDS.sleep(1);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("Interrupted initializing " + description + " in " + containerName, e);
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Timed out initializing " + description + " in " + containerName + ": " + lastOutput);
|
||||
}
|
||||
|
||||
public record ExecResult(long exitCode, String stdout, String stderr) {}
|
||||
}
|
||||
@@ -37,6 +37,23 @@ public class Cluster {
|
||||
public List<String> getVpcSecurityGroupIds() { return vpcSecurityGroupIds; }
|
||||
public void setVpcSecurityGroupIds(List<String> vpcSecurityGroupIds) { this.vpcSecurityGroupIds = vpcSecurityGroupIds; }
|
||||
|
||||
// Real backend address of this cluster's PostgreSQL container. `endpoint` now points at the
|
||||
// auth proxy, not the container, so the container address is kept here for proxy wiring and
|
||||
// for restarting the proxy after a reboot or an adopt-on-startup.
|
||||
private String containerHost = null;
|
||||
private int containerPort = 0;
|
||||
|
||||
// Host port the cluster's auth proxy binds. Kept stable across reboot and adopt so the
|
||||
// advertised endpoint does not change.
|
||||
private int proxyPort = 0;
|
||||
|
||||
public String getContainerHost() { return containerHost; }
|
||||
public void setContainerHost(String containerHost) { this.containerHost = containerHost; }
|
||||
public int getContainerPort() { return containerPort; }
|
||||
public void setContainerPort(int containerPort) { this.containerPort = containerPort; }
|
||||
public int getProxyPort() { return proxyPort; }
|
||||
public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; }
|
||||
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.services.rds.proxy.PostgresProtocolHandler;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.BindException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
|
||||
/**
|
||||
* TCP auth proxy for a single Redshift cluster's backing PostgreSQL container.
|
||||
* Redshift speaks the PostgreSQL wire protocol, so the RDS PostgreSQL protocol
|
||||
* handler is reused verbatim for the auth intercept; client and backend are then
|
||||
* bridged transparently. IAM auth is never enabled for Redshift, so the SigV4
|
||||
* validator is carried only to satisfy the shared handler signature.
|
||||
*/
|
||||
public class RedshiftAuthProxy {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftAuthProxy.class);
|
||||
|
||||
private final String clusterKey;
|
||||
private final String backendHost;
|
||||
private final int backendPort;
|
||||
private final String masterUsername;
|
||||
private volatile String masterPassword;
|
||||
private final String dbName;
|
||||
private final RdsSigV4Validator sigV4;
|
||||
private final RdsProxyTlsCertificates tlsCertificates;
|
||||
private final RdsAuthProxy.PasswordValidator passwordValidator;
|
||||
|
||||
private volatile boolean running;
|
||||
private ServerSocket serverSocket;
|
||||
|
||||
public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort,
|
||||
String masterUsername, String masterPassword, String dbName,
|
||||
RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates,
|
||||
RdsAuthProxy.PasswordValidator passwordValidator) {
|
||||
this.clusterKey = clusterKey;
|
||||
this.backendHost = backendHost;
|
||||
this.backendPort = backendPort;
|
||||
this.masterUsername = masterUsername;
|
||||
this.masterPassword = masterPassword;
|
||||
this.dbName = dbName;
|
||||
this.sigV4 = sigV4;
|
||||
this.tlsCertificates = tlsCertificates;
|
||||
this.passwordValidator = passwordValidator;
|
||||
}
|
||||
|
||||
public void start(int proxyPort) throws IOException {
|
||||
serverSocket = bindListener(proxyPort);
|
||||
running = true;
|
||||
Thread.ofVirtual().name("redshift-proxy-accept-" + clusterKey).start(this::acceptLoop);
|
||||
LOG.infov("Redshift proxy started for cluster {0} on port {1} -> {2}:{3}",
|
||||
clusterKey, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind the listener, retrying briefly on {@link BindException}. A reboot keeps the
|
||||
* cluster's proxy port fixed so the advertised endpoint is stable, which means the
|
||||
* old listener is closed and the same port rebound milliseconds later; under load
|
||||
* the kernel may not have released it yet and {@code SO_REUSEADDR} does not help
|
||||
* while the previous accept loop is still tearing down. ~1s of retry absorbs that
|
||||
* window; any other {@link IOException} propagates immediately.
|
||||
*/
|
||||
private ServerSocket bindListener(int proxyPort) throws IOException {
|
||||
BindException lastFailure = null;
|
||||
for (int attempt = 0; attempt < 40; attempt++) {
|
||||
ServerSocket socket = new ServerSocket();
|
||||
try {
|
||||
socket.setReuseAddress(true);
|
||||
socket.bind(new InetSocketAddress(proxyPort));
|
||||
return socket;
|
||||
} catch (BindException e) {
|
||||
closeQuietly(socket);
|
||||
lastFailure = e;
|
||||
} catch (IOException e) {
|
||||
closeQuietly(socket);
|
||||
throw e;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(25);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted while binding Redshift proxy port " + proxyPort, e);
|
||||
}
|
||||
}
|
||||
throw lastFailure;
|
||||
}
|
||||
|
||||
private static void closeQuietly(ServerSocket s) {
|
||||
try {
|
||||
s.close();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Error closing a discarded Redshift proxy listener socket");
|
||||
}
|
||||
}
|
||||
|
||||
/** Swap the master-password snapshot after a rotation; new connections authenticate against it. */
|
||||
public void updateMasterPassword(String newPassword) {
|
||||
this.masterPassword = newPassword;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
running = false;
|
||||
try {
|
||||
if (serverSocket != null) {
|
||||
serverSocket.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.warnv(e, "Error closing Redshift proxy server socket for cluster {0}", clusterKey);
|
||||
throw new RuntimeException("Failed to stop Redshift proxy for cluster " + clusterKey, e);
|
||||
}
|
||||
}
|
||||
|
||||
private void acceptLoop() {
|
||||
while (running) {
|
||||
try {
|
||||
Socket client = serverSocket.accept();
|
||||
Thread.ofVirtual().name("redshift-proxy-conn-" + clusterKey)
|
||||
.start(() -> handleConnection(client));
|
||||
} catch (IOException e) {
|
||||
if (running) {
|
||||
LOG.warnv("Accept error for Redshift cluster {0}: {1}", clusterKey, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleConnection(Socket client) {
|
||||
Socket backend = null;
|
||||
try {
|
||||
client.setTcpNoDelay(true);
|
||||
backend = new Socket(backendHost, backendPort);
|
||||
backend.setTcpNoDelay(true);
|
||||
// iamEnabled = false: the SigV4 branch inside handleAuth is never taken.
|
||||
PostgresProtocolHandler.handleAuth(
|
||||
client, backend, masterUsername, masterPassword, dbName,
|
||||
false, sigV4, tlsCertificates, passwordValidator::validate);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Redshift connection error for cluster {0}: {1}", clusterKey, e.getMessage());
|
||||
} finally {
|
||||
// handleAuth's success path bridges then closes both sockets; every other path
|
||||
// (early return on a bare probe, auth failure, thrown IOException) can leave the
|
||||
// backend connection to Postgres open. Closing here is idempotent.
|
||||
closeQuietly(client);
|
||||
if (backend != null) {
|
||||
closeQuietly(backend);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void closeQuietly(Socket s) {
|
||||
try {
|
||||
s.close();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Error closing Redshift proxy client socket");
|
||||
}
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
|
||||
import io.quarkus.runtime.ShutdownEvent;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Registry of all active Redshift auth proxies. One proxy per cluster, keyed by
|
||||
* the relay key "{accountId}:{clusterId}". Mirrors RdsProxyManager; Redshift is
|
||||
* always PostgreSQL and never IAM-enabled, so those parameters are dropped.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class RedshiftProxyManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftProxyManager.class);
|
||||
|
||||
private final RdsSigV4Validator sigV4Validator;
|
||||
private final RdsProxyTlsCertificates tlsCertificates;
|
||||
private final ConcurrentHashMap<String, RedshiftAuthProxy> proxies = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Proxies whose listener could not be closed during a failed start or replace. The
|
||||
* reference is kept (not discarded) so a later {@link #stopProxy}/{@link #stopAll}
|
||||
* can retry the close; until one succeeds, {@code stopProxy} keeps throwing so the
|
||||
* caller leaves the port reserved rather than handing it out to another cluster.
|
||||
*/
|
||||
private final ConcurrentHashMap<String, RedshiftAuthProxy> unclosableProxies = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates) {
|
||||
this.sigV4Validator = sigV4Validator;
|
||||
this.tlsCertificates = tlsCertificates;
|
||||
}
|
||||
|
||||
public synchronized void startProxy(String relayKey, int proxyPort,
|
||||
String backendHost, int backendPort, String advertisedHost,
|
||||
String masterUsername, String masterPassword, String dbName,
|
||||
RdsAuthProxy.PasswordValidator passwordValidator) {
|
||||
// A prior unclosable entry for this key is left in place: its listener may still
|
||||
// be bound, and only a successful stop (never a fresh start) may drop it.
|
||||
// Make sure the self-signed proxy certificate covers the host clients will connect to,
|
||||
// so sslmode=prefer/require handshakes succeed.
|
||||
tlsCertificates.ensureHost(advertisedHost);
|
||||
RedshiftAuthProxy proxy = new RedshiftAuthProxy(
|
||||
relayKey, backendHost, backendPort, masterUsername, masterPassword, dbName,
|
||||
sigV4Validator, tlsCertificates, passwordValidator);
|
||||
try {
|
||||
proxy.start(proxyPort);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
RuntimeException failure = new RuntimeException(
|
||||
"Failed to start Redshift proxy for cluster " + relayKey + " on port " + proxyPort, e);
|
||||
cleanupFailedStart(relayKey, proxy, failure);
|
||||
throw failure;
|
||||
}
|
||||
RedshiftAuthProxy previous = proxies.put(relayKey, proxy);
|
||||
if (previous != null) {
|
||||
try {
|
||||
previous.stop();
|
||||
} catch (RuntimeException e) {
|
||||
proxies.put(relayKey, previous);
|
||||
RuntimeException failure = new RuntimeException(
|
||||
"Failed to replace Redshift proxy for cluster " + relayKey, e);
|
||||
cleanupFailedStart(relayKey, proxy, failure);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void updateMasterPassword(String relayKey, String newPassword) {
|
||||
RedshiftAuthProxy proxy = proxies.get(relayKey);
|
||||
if (proxy != null) {
|
||||
proxy.updateMasterPassword(newPassword);
|
||||
LOG.infov("Updated Redshift proxy master password for cluster {0}", relayKey);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void stopProxy(String relayKey) {
|
||||
// Retry any listener a previous failed start/replace could not close. If it still
|
||||
// cannot be closed this throws, and the entry stays for the next retry.
|
||||
RedshiftAuthProxy unclosable = unclosableProxies.get(relayKey);
|
||||
if (unclosable != null) {
|
||||
unclosable.stop();
|
||||
unclosableProxies.remove(relayKey);
|
||||
LOG.infov("Recovered previously unclosable Redshift proxy for cluster {0}", relayKey);
|
||||
}
|
||||
RedshiftAuthProxy proxy = proxies.get(relayKey);
|
||||
if (proxy != null) {
|
||||
proxy.stop();
|
||||
proxies.remove(relayKey);
|
||||
LOG.infov("Stopped Redshift proxy for cluster {0}", relayKey);
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void stopAll() {
|
||||
proxies.forEach((relayKey, proxy) -> {
|
||||
try {
|
||||
proxy.stop();
|
||||
proxies.remove(relayKey, proxy);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Failed to stop Redshift proxy for cluster {0} during shutdown", relayKey);
|
||||
}
|
||||
});
|
||||
unclosableProxies.forEach((relayKey, proxy) -> {
|
||||
try {
|
||||
proxy.stop();
|
||||
unclosableProxies.remove(relayKey, proxy);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Failed to close leaked Redshift proxy for cluster {0} during shutdown", relayKey);
|
||||
}
|
||||
});
|
||||
LOG.info("Stopped all Redshift proxies");
|
||||
}
|
||||
|
||||
void onShutdown(@Observes ShutdownEvent event) {
|
||||
stopAll();
|
||||
}
|
||||
|
||||
private void cleanupFailedStart(String relayKey, RedshiftAuthProxy proxy, RuntimeException failure) {
|
||||
try {
|
||||
proxy.stop();
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
// Keep the listener reachable so stopProxy/stopAll can retry closing it later.
|
||||
unclosableProxies.put(relayKey, proxy);
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user