Files
floci/docs/services/redshift.md
T
Vũ Thế Huy 426fbcb284 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
2026-08-31 09:03:26 -04:00

147 lines
7.1 KiB
Markdown

# Redshift
**Protocol:** Query (XML) for the management API
**Management Endpoint:** `POST http://localhost:4566/` with `Action=` param
**Data Endpoint:** Floci's auth proxy on the `Endpoint` and `Port` returned by `DescribeClusters` (PostgreSQL wire protocol)
Floci emulates Amazon Redshift by managing a real [PostgreSQL](https://www.postgresql.org/) Docker container per cluster behind a Redshift-shaped control plane. Each cluster sits behind a lightweight auth proxy on the Floci host, so the endpoint is reachable from outside Docker and the master password is validated at the proxy — a `ModifyCluster` password change takes effect for new connections immediately. Redshift speaks the PostgreSQL wire protocol, so the cluster endpoint returned by `DescribeClusters` works with any standard PostgreSQL driver (`psql`, JDBC, `psycopg`, …).
> **Always read the host and port from `DescribeClusters`** rather than assuming a fixed port. PostgreSQL listens on `5432` *inside* the container; the port you connect to is dynamically assigned on the host and returned as `Clusters[0].Endpoint.Port`. Redshift's conventional port is `5439`, but the emulator does not bind it — use whatever `DescribeClusters` reports.
The container has **no persistent volume**: if the physical container survives a Floci restart it is adopted and its data is kept, but if the container itself is gone (host reboot, `docker rm`, a pruned dev box) the cluster comes back empty. Use `CreateClusterSnapshot` / `RestoreFromClusterSnapshot` to preserve data explicitly.
## Supported Actions
<!-- floci:actions:start -->
| Action | Description |
| --- | --- |
| `CreateCluster` | Create a cluster and start a PostgreSQL container for it |
| `DescribeClusters` | List clusters and their connection details |
| `DeleteCluster` | Stop and remove a cluster and its container |
| `CreateClusterSnapshot` | Back up a cluster to a SQL dump via `pg_dump` |
| `DescribeClusterSnapshots` | List snapshots, optionally filtered by snapshot or cluster identifier |
| `DeleteClusterSnapshot` | Remove a snapshot and its stored dump |
| `RestoreFromClusterSnapshot` | Create a new cluster and load a snapshot's dump into it via `psql` |
| `CreateClusterParameterGroup` | Register a parameter group (metadata only) |
| `DescribeClusterParameterGroups` | List parameter groups, optionally filtered by name |
| `DescribeClusterParameters` | Return the parameters of a group, with any values set by `ModifyClusterParameterGroup` |
| `ModifyClusterParameterGroup` | Update parameter values on a group |
| `DeleteClusterParameterGroup` | Remove a parameter group |
| `CreateTags` | Add or overwrite tags on a cluster, snapshot, subnet group or parameter group |
| `DeleteTags` | Remove tags by key from a resource |
| `DescribeTags` | List tagged resources and their tags |
| `CreateClusterSubnetGroup` | Register a cluster subnet group (metadata only) |
| `DescribeClusterSubnetGroups` | List subnet groups, optionally filtered by name |
| `ModifyClusterSubnetGroup` | Update a subnet group's description or subnet list |
| `DeleteClusterSubnetGroup` | Remove a subnet group |
| `ModifyCluster` | Update node type, parameter group, security groups, or the master password |
| `RebootCluster` | Restart a cluster's container |
<!-- floci:actions:end -->
## Configuration
| Variable | Default | Description |
|----------|---------|-------------|
| `FLOCI_SERVICES_REDSHIFT_ENABLED` | `true` | Enable or disable Redshift |
| `FLOCI_SERVICES_REDSHIFT_IMAGE_VERSION` | `postgres:15-alpine` | PostgreSQL Docker image backing each cluster |
| `FLOCI_SERVICES_REDSHIFT_DEFAULT_PORT` | `5439` | Reported Redshift port hint (the real host port is dynamic and comes from `DescribeClusters`) |
| `FLOCI_SERVICES_REDSHIFT_PROXY_BASE_PORT` | `7100` | Lowest host port the per-cluster auth proxies bind |
| `FLOCI_SERVICES_REDSHIFT_PROXY_MAX_PORT` | `7199` | Highest host port the per-cluster auth proxies bind |
| `FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST` | _(unset)_ | Hostname advertised in `DescribeClusters`; unset resolves from the Docker host |
Redshift needs the Docker socket so it can launch PostgreSQL containers. Each cluster's container is published on a dynamically assigned host port, returned by `DescribeClusters`.
### Docker Compose
```yaml
services:
floci:
image: floci/floci:latest
ports:
- "4566:4566"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
```
For private registry authentication and other Docker settings see [Docker Configuration](../configuration/docker.md).
## Examples
### Management API (AWS CLI)
```bash
export AWS_ENDPOINT_URL=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
# Create a cluster (starts a PostgreSQL container)
aws redshift create-cluster \
--cluster-identifier my-warehouse \
--node-type dc2.large \
--master-username admin \
--master-user-password Secret123
# Read the cluster endpoint and port
aws redshift describe-clusters \
--cluster-identifier my-warehouse \
--query 'Clusters[0].Endpoint'
# Snapshot and restore
aws redshift create-cluster-snapshot \
--snapshot-identifier snap-1 \
--cluster-identifier my-warehouse
aws redshift restore-from-cluster-snapshot \
--cluster-identifier my-warehouse-restored \
--snapshot-identifier snap-1
# Delete
aws redshift delete-cluster \
--cluster-identifier my-warehouse \
--skip-final-cluster-snapshot
```
### Data plane (Python + psycopg)
```python
import psycopg
# Read host and port from DescribeClusters — the host port is dynamic.
host, port = "localhost", 32768 # e.g. Clusters[0].Endpoint.Address / .Port
with psycopg.connect(f"host={host} port={port} dbname=dev user=admin password=Secret123") as conn:
conn.execute("CREATE TABLE people (name text)")
conn.execute("INSERT INTO people VALUES ('Alice')")
for row in conn.execute("SELECT * FROM people"):
print(row)
```
### Management API (Python / boto3)
```python
import boto3
redshift = boto3.client(
"redshift",
endpoint_url="http://localhost:4566",
region_name="us-east-1",
)
cluster = redshift.create_cluster(
ClusterIdentifier="my-warehouse",
NodeType="dc2.large",
MasterUsername="admin",
MasterUserPassword="Secret123",
)
print(cluster["Cluster"]["Endpoint"])
```
## Out of Scope
- Real Redshift SQL semantics — the data plane is stock PostgreSQL, so Redshift-only SQL (distribution/sort keys, `COPY`/`UNLOAD` from S3, `SUPER`/`SPECTRUM`) is not emulated.
- Multi-node clusters — `NodeType` and `NumberOfNodes` are stored as metadata; every cluster is a single PostgreSQL container.
- Parameter groups apply no real engine settings; values are stored and echoed back only.
- Subnet groups, VPC routing, and security groups are metadata only.
- Resize, pause/resume, IAM authentication, snapshot schedules, and cross-region snapshot copy.
- The auth proxy validates only the master user's password. Non-master users pass straight through to PostgreSQL, which remains the authority for their credentials.
- IAM database authentication (`GetClusterCredentials`), and `sslmode=verify-full` against the self-signed proxy certificate.