mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat: implement Amazon MSK service with Redpanda orchestration (#419)
* feat: implement Amazon MSK service with Redpanda orchestration * fix: adding missing msk service on the test
This commit is contained in:
1 parent
ed553c6cbf
commit
91071aaae7
24 files changed
+852
-12
No files matched your search
@@ -62,6 +62,10 @@ public interface EmulatorConfig {
|
||||
@WithDefault("./data")
|
||||
String persistentPath();
|
||||
|
||||
/** The path on the host machine where data is stored. Useful for Docker-in-Docker. */
|
||||
@WithDefault("${floci.storage.persistent-path}")
|
||||
String hostPersistentPath();
|
||||
|
||||
WalConfig wal();
|
||||
|
||||
ServiceStorageOverrides services();
|
||||
@@ -202,6 +206,7 @@ public interface EmulatorConfig {
|
||||
LambdaServiceConfig lambda();
|
||||
ApiGatewayServiceConfig apigateway();
|
||||
IamServiceConfig iam();
|
||||
MskServiceConfig msk();
|
||||
ElastiCacheServiceConfig elasticache();
|
||||
RdsServiceConfig rds();
|
||||
EventBridgeServiceConfig eventbridge();
|
||||
@@ -275,6 +280,17 @@ public interface EmulatorConfig {
|
||||
boolean enforcementEnabled();
|
||||
}
|
||||
|
||||
interface MskServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("false")
|
||||
boolean mock();
|
||||
|
||||
@WithDefault("redpandadata/redpanda:latest")
|
||||
String defaultImage();
|
||||
}
|
||||
|
||||
interface ElastiCacheServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
@@ -442,7 +458,7 @@ public interface EmulatorConfig {
|
||||
@WithDefault("5199")
|
||||
int registryMaxPort();
|
||||
|
||||
@WithDefault("./data/ecr")
|
||||
@WithDefault("${floci.storage.persistent-path}/ecr")
|
||||
String dataPath();
|
||||
|
||||
@WithDefault("false")
|
||||
|
||||
@@ -64,6 +64,10 @@ public class ResolvedServiceCatalog {
|
||||
"iam", config.storage().mode(), 5000L, AwsNamespaces.IAM, ServiceProtocol.QUERY,
|
||||
protocols(ServiceProtocol.QUERY),
|
||||
Set.of(), Set.of("iam"), Set.of(), Set.of()),
|
||||
descriptor("kafka", "msk", config.services().msk().enabled(), true,
|
||||
"msk", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
Set.of(), Set.of("kafka"), Set.of(), Set.of(io.github.hectorvent.floci.services.msk.MskController.class)),
|
||||
descriptor("sts", "iam", config.services().iam().enabled(), false,
|
||||
null, null, 5000L, AwsNamespaces.STS, ServiceProtocol.QUERY,
|
||||
protocols(ServiceProtocol.QUERY),
|
||||
|
||||
+20
-6
@@ -134,10 +134,26 @@ public class EcrRegistryManager {
|
||||
Ports portBindings = new Ports();
|
||||
portBindings.bind(exposed, Ports.Binding.bindPort(chosenPort));
|
||||
|
||||
String dataPath = Paths.get(config.services().ecr().dataPath(), "registry").toAbsolutePath().toString();
|
||||
String hostPersistentPath = config.storage().hostPersistentPath();
|
||||
boolean isVolume = !hostPersistentPath.startsWith("/") && !hostPersistentPath.startsWith(".");
|
||||
|
||||
HostConfig hostConfig = HostConfig.newHostConfig()
|
||||
.withPortBindings(portBindings)
|
||||
.withBinds(new Bind(dataPath, new Volume("/var/lib/registry")));
|
||||
.withPortBindings(portBindings);
|
||||
|
||||
List<String> env = new java.util.ArrayList<>(List.of(
|
||||
"REGISTRY_STORAGE_DELETE_ENABLED=true",
|
||||
"REGISTRY_HTTP_ADDR=0.0.0.0:" + CONTAINER_INTERNAL_PORT
|
||||
));
|
||||
|
||||
if (isVolume) {
|
||||
String internalMountPath = "/app/data";
|
||||
hostConfig.withBinds(new Bind(hostPersistentPath, new Volume(internalMountPath)));
|
||||
env.add("REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY=" + internalMountPath + "/ecr/registry");
|
||||
} else {
|
||||
String dataPath = Paths.get(config.services().ecr().dataPath(), "registry").toAbsolutePath().toString();
|
||||
String hostDataPath = dataPath.replace(config.storage().persistentPath(), hostPersistentPath);
|
||||
hostConfig.withBinds(new Bind(hostDataPath, new Volume("/var/lib/registry")));
|
||||
}
|
||||
|
||||
config.services().ecr().dockerNetwork()
|
||||
.or(() -> config.services().dockerNetwork())
|
||||
@@ -147,9 +163,7 @@ public class EcrRegistryManager {
|
||||
try {
|
||||
CreateContainerResponse created = dockerClient.createContainerCmd(image)
|
||||
.withName(name)
|
||||
.withEnv(
|
||||
"REGISTRY_STORAGE_DELETE_ENABLED=true",
|
||||
"REGISTRY_HTTP_ADDR=0.0.0.0:" + CONTAINER_INTERNAL_PORT)
|
||||
.withEnv(env)
|
||||
.withExposedPorts(exposed)
|
||||
.withHostConfig(hostConfig)
|
||||
.exec();
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package io.github.hectorvent.floci.services.msk;
|
||||
|
||||
import io.github.hectorvent.floci.services.msk.model.MskCluster;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.util.Map;
|
||||
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class MskController {
|
||||
|
||||
private final MskService mskService;
|
||||
|
||||
@Inject
|
||||
public MskController(MskService mskService) {
|
||||
this.mskService = mskService;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/v1/clusters")
|
||||
public Response createCluster(Map<String, Object> request) {
|
||||
String clusterName = (String) request.get("clusterName");
|
||||
MskCluster cluster = mskService.createCluster(clusterName);
|
||||
return Response.ok(Map.of("clusterArn", cluster.getClusterArn(), "clusterName", cluster.getClusterName(), "state", cluster.getState())).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/api/v2/clusters")
|
||||
public Response createClusterV2(Map<String, Object> request) {
|
||||
// Simple mapping to V1 for now
|
||||
String clusterName = (String) request.get("clusterName");
|
||||
MskCluster cluster = mskService.createCluster(clusterName);
|
||||
return Response.ok(Map.of("clusterArn", cluster.getClusterArn(), "clusterName", cluster.getClusterName(), "state", cluster.getState())).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/v1/clusters")
|
||||
public Response listClusters() {
|
||||
var clusters = mskService.listClusters();
|
||||
return Response.ok(Map.of("clusterInfoList", clusters)).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/api/v2/clusters")
|
||||
public Response listClustersV2() {
|
||||
var clusters = mskService.listClusters();
|
||||
return Response.ok(Map.of("clusterInfoList", clusters)).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/v1/clusters/{clusterArn}")
|
||||
public Response describeCluster(@PathParam("clusterArn") String clusterArn) {
|
||||
MskCluster cluster = mskService.describeCluster(clusterArn);
|
||||
return Response.ok(Map.of("clusterInfo", cluster)).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/api/v2/clusters/{clusterArn}")
|
||||
public Response describeClusterV2(@PathParam("clusterArn") String clusterArn) {
|
||||
MskCluster cluster = mskService.describeCluster(clusterArn);
|
||||
return Response.ok(Map.of("clusterInfo", cluster)).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/v1/clusters/{clusterArn}")
|
||||
public Response deleteCluster(@PathParam("clusterArn") String clusterArn) {
|
||||
mskService.deleteCluster(clusterArn);
|
||||
return Response.ok(Map.of("clusterArn", clusterArn, "state", "DELETING")).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/v1/clusters/{clusterArn}/bootstrap-brokers")
|
||||
public Response getBootstrapBrokers(@PathParam("clusterArn") String clusterArn) {
|
||||
String bootstrapBrokers = mskService.getBootstrapBrokers(clusterArn);
|
||||
return Response.ok(Map.of("bootstrapBrokerString", bootstrapBrokers)).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package io.github.hectorvent.floci.services.msk;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.msk.model.ClusterState;
|
||||
import io.github.hectorvent.floci.services.msk.model.MskCluster;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
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.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ApplicationScoped
|
||||
public class MskService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(MskService.class);
|
||||
private final StorageBackend<String, MskCluster> storage;
|
||||
private final EmulatorConfig config;
|
||||
private final RedpandaManager redpandaManager;
|
||||
private final ScheduledExecutorService poller = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
@Inject
|
||||
public MskService(StorageFactory storageFactory, EmulatorConfig config, RedpandaManager redpandaManager) {
|
||||
this.storage = storageFactory.create("msk", "msk-clusters.json", new TypeReference<Map<String, MskCluster>>() {});
|
||||
this.config = config;
|
||||
this.redpandaManager = redpandaManager;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
startReadinessPoller();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void shutdown() {
|
||||
poller.shutdown();
|
||||
if (!config.services().msk().mock()) {
|
||||
for (MskCluster cluster : storage.scan(k -> true)) {
|
||||
redpandaManager.stopContainer(cluster);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public MskCluster createCluster(String clusterName) {
|
||||
if (storage.scan(k -> true).stream().anyMatch(c -> c.getClusterName().equals(clusterName))) {
|
||||
throw new AwsException("ConflictException", "Cluster already exists: " + clusterName, 409);
|
||||
}
|
||||
|
||||
String clusterArn = String.format("arn:aws:kafka:%s:000000000000:cluster/%s/%s",
|
||||
"us-east-1", clusterName, java.util.UUID.randomUUID());
|
||||
|
||||
MskCluster cluster = new MskCluster(clusterArn, clusterName);
|
||||
|
||||
if (config.services().msk().mock()) {
|
||||
cluster.setState(ClusterState.ACTIVE);
|
||||
cluster.setBootstrapBrokers("localhost:9092");
|
||||
} else {
|
||||
redpandaManager.startContainer(cluster);
|
||||
}
|
||||
|
||||
storage.put(clusterArn, cluster);
|
||||
return cluster;
|
||||
}
|
||||
|
||||
public MskCluster describeCluster(String clusterArn) {
|
||||
return storage.get(clusterArn)
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Cluster not found: " + clusterArn, 404));
|
||||
}
|
||||
|
||||
public List<MskCluster> listClusters() {
|
||||
return storage.scan(k -> true);
|
||||
}
|
||||
|
||||
public void deleteCluster(String clusterArn) {
|
||||
MskCluster cluster = storage.get(clusterArn)
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Cluster not found: " + clusterArn, 404));
|
||||
|
||||
cluster.setState(ClusterState.DELETING);
|
||||
if (!config.services().msk().mock()) {
|
||||
redpandaManager.stopContainer(cluster);
|
||||
}
|
||||
storage.delete(clusterArn);
|
||||
}
|
||||
|
||||
public String getBootstrapBrokers(String clusterArn) {
|
||||
MskCluster cluster = describeCluster(clusterArn);
|
||||
return cluster.getBootstrapBrokers();
|
||||
}
|
||||
|
||||
private void startReadinessPoller() {
|
||||
poller.scheduleAtFixedRate(() -> {
|
||||
try {
|
||||
for (MskCluster cluster : storage.scan(k -> true)) {
|
||||
if (cluster.getState() == ClusterState.CREATING && !config.services().msk().mock()) {
|
||||
if (redpandaManager.isReady(cluster)) {
|
||||
LOG.infov("MSK Cluster {0} is now ACTIVE", cluster.getClusterName());
|
||||
cluster.setState(ClusterState.ACTIVE);
|
||||
storage.put(cluster.getClusterArn(), cluster);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error in MSK readiness poller", e);
|
||||
}
|
||||
}, 1, 2, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package io.github.hectorvent.floci.services.msk;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateContainerResponse;
|
||||
import com.github.dockerjava.api.model.Bind;
|
||||
import com.github.dockerjava.api.model.ExposedPort;
|
||||
import com.github.dockerjava.api.model.HostConfig;
|
||||
import com.github.dockerjava.api.model.Ports;
|
||||
import com.github.dockerjava.api.model.Volume;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
|
||||
import io.github.hectorvent.floci.services.msk.model.MskCluster;
|
||||
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.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.net.URL;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedpandaManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedpandaManager.class);
|
||||
private static final int KAFKA_PORT = 9092;
|
||||
private static final int ADMIN_PORT = 9644;
|
||||
|
||||
private final DockerClient dockerClient;
|
||||
private final ImageCacheService imageCacheService;
|
||||
private final ContainerDetector containerDetector;
|
||||
private final EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
public RedpandaManager(DockerClient dockerClient,
|
||||
ImageCacheService imageCacheService,
|
||||
ContainerDetector containerDetector,
|
||||
EmulatorConfig config) {
|
||||
this.dockerClient = dockerClient;
|
||||
this.imageCacheService = imageCacheService;
|
||||
this.containerDetector = containerDetector;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public void startContainer(MskCluster cluster) {
|
||||
String image = config.services().msk().defaultImage();
|
||||
LOG.infov("Starting Redpanda container for MSK cluster: {0} using image {1}", cluster.getClusterName(), image);
|
||||
imageCacheService.ensureImageExists(image);
|
||||
|
||||
String containerName = "floci-msk-" + cluster.getClusterName();
|
||||
|
||||
// Ensure internal persistence path exists
|
||||
Path dataPath = Path.of(config.storage().persistentPath(), "msk", cluster.getClusterName());
|
||||
try {
|
||||
Files.createDirectories(dataPath);
|
||||
} catch (IOException e) {
|
||||
LOG.errorv("Failed to create MSK data directory: {0}", dataPath, e);
|
||||
}
|
||||
|
||||
String hostPersistentPath = config.storage().hostPersistentPath();
|
||||
boolean isVolume = !hostPersistentPath.startsWith("/") && !hostPersistentPath.startsWith(".");
|
||||
|
||||
HostConfig hostConfig = HostConfig.newHostConfig();
|
||||
List<String> cmd = new java.util.ArrayList<>(List.of("redpanda", "start", "--overprovisioned", "--smp", "1", "--memory", "512M", "--reserve-memory", "0M"));
|
||||
|
||||
if (isVolume) {
|
||||
// Volume mode: mount the whole volume and point Redpanda to the subdirectory
|
||||
String internalMountPath = "/app/data";
|
||||
hostConfig.withBinds(new Bind(hostPersistentPath, new Volume(internalMountPath)));
|
||||
cmd.add("--data-dir");
|
||||
cmd.add(internalMountPath + "/msk/" + cluster.getClusterName());
|
||||
} else {
|
||||
// Directory mode: mount the specific subdirectory directly
|
||||
String hostDataPath = Path.of(hostPersistentPath, "msk", cluster.getClusterName())
|
||||
.toAbsolutePath().toString();
|
||||
hostConfig.withBinds(new Bind(hostDataPath, new Volume("/var/lib/redpanda/data")));
|
||||
}
|
||||
|
||||
config.services().dockerNetwork()
|
||||
.or(() -> config.services().dockerNetwork())
|
||||
.ifPresent(network -> {
|
||||
if (!network.isBlank()) {
|
||||
hostConfig.withNetworkMode(network);
|
||||
}
|
||||
});
|
||||
|
||||
Ports portBindings = new Ports();
|
||||
int hostKafkaPort = KAFKA_PORT;
|
||||
int hostAdminPort = ADMIN_PORT;
|
||||
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
hostKafkaPort = findFreePort();
|
||||
hostAdminPort = findFreePort();
|
||||
portBindings.bind(ExposedPort.tcp(KAFKA_PORT), Ports.Binding.bindPort(hostKafkaPort));
|
||||
portBindings.bind(ExposedPort.tcp(ADMIN_PORT), Ports.Binding.bindPort(hostAdminPort));
|
||||
hostConfig.withPortBindings(portBindings);
|
||||
}
|
||||
|
||||
// Cleanup stale container
|
||||
try {
|
||||
dockerClient.removeContainerCmd(containerName).withForce(true).exec();
|
||||
} catch (Exception ignored) {}
|
||||
|
||||
CreateContainerResponse container = dockerClient.createContainerCmd(image)
|
||||
.withName(containerName)
|
||||
.withExposedPorts(ExposedPort.tcp(KAFKA_PORT), ExposedPort.tcp(ADMIN_PORT))
|
||||
.withHostConfig(hostConfig)
|
||||
.withCmd(cmd)
|
||||
.exec();
|
||||
|
||||
String containerId = container.getId();
|
||||
cluster.setContainerId(containerId);
|
||||
dockerClient.startContainerCmd(containerId).exec();
|
||||
|
||||
String bootstrapHost;
|
||||
int bootstrapPort;
|
||||
String adminHost;
|
||||
int adminPort;
|
||||
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
bootstrapHost = "localhost";
|
||||
bootstrapPort = hostKafkaPort;
|
||||
adminHost = "localhost";
|
||||
adminPort = hostAdminPort;
|
||||
} else {
|
||||
var inspect = dockerClient.inspectContainerCmd(containerId).exec();
|
||||
String containerIp = inspect.getNetworkSettings().getNetworks().values().stream()
|
||||
.map(com.github.dockerjava.api.model.ContainerNetwork::getIpAddress)
|
||||
.filter(ip -> ip != null && !ip.isBlank())
|
||||
.findFirst()
|
||||
.orElse(inspect.getNetworkSettings().getIpAddress());
|
||||
bootstrapHost = containerIp;
|
||||
bootstrapPort = KAFKA_PORT;
|
||||
adminHost = containerIp;
|
||||
adminPort = ADMIN_PORT;
|
||||
}
|
||||
|
||||
cluster.setBootstrapBrokers(bootstrapHost + ":" + bootstrapPort);
|
||||
LOG.infov("Redpanda container {0} started. Bootstrap: {1}", containerId, cluster.getBootstrapBrokers());
|
||||
|
||||
// Wait for readiness in a separate thread or return and let the service handle state?
|
||||
// Service should handle the polling to CREATING -> ACTIVE transition.
|
||||
}
|
||||
|
||||
public boolean isReady(MskCluster cluster) {
|
||||
String bootstrap = cluster.getBootstrapBrokers();
|
||||
if (bootstrap == null) return false;
|
||||
|
||||
// We need the admin API to check readiness properly as per design doc (/ready endpoint)
|
||||
// For now, let's derive the admin URL.
|
||||
// In native mode it's localhost:hostAdminPort. In container mode it's containerIp:9644.
|
||||
|
||||
String adminUrl;
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
// We didn't store adminPort in cluster object, let's inspect again or store it.
|
||||
// Let's store it in cluster for simplicity during development.
|
||||
// Actually, let's just inspect the container to find the binding for 9644.
|
||||
var inspect = dockerClient.inspectContainerCmd(cluster.getContainerId()).exec();
|
||||
var bindings = inspect.getNetworkSettings().getPorts().getBindings();
|
||||
var binding = bindings.get(ExposedPort.tcp(ADMIN_PORT));
|
||||
if (binding != null && binding.length > 0) {
|
||||
adminUrl = "http://localhost:" + binding[0].getHostPortSpec() + "/ready";
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
String containerIp = bootstrap.split(":")[0];
|
||||
adminUrl = "http://" + containerIp + ":" + ADMIN_PORT + "/ready";
|
||||
}
|
||||
|
||||
try {
|
||||
HttpURLConnection conn = (HttpURLConnection) URI.create(adminUrl).toURL().openConnection();
|
||||
conn.setRequestMethod("GET");
|
||||
conn.setConnectTimeout(1000);
|
||||
conn.setReadTimeout(1000);
|
||||
return conn.getResponseCode() == 200;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void stopContainer(MskCluster cluster) {
|
||||
if (cluster.getContainerId() == null) return;
|
||||
try {
|
||||
dockerClient.stopContainerCmd(cluster.getContainerId()).withTimeout(5).exec();
|
||||
dockerClient.removeContainerCmd(cluster.getContainerId()).withForce(true).exec();
|
||||
LOG.infov("Redpanda container {0} stopped and removed", cluster.getContainerId());
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to stop Redpanda container {0}: {1}", cluster.getContainerId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static int findFreePort() {
|
||||
try (ServerSocket s = new ServerSocket(0)) {
|
||||
s.setReuseAddress(true);
|
||||
return s.getLocalPort();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Could not find a free port for Redpanda", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package io.github.hectorvent.floci.services.msk.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public enum ClusterState {
|
||||
@JsonProperty("ACTIVE")
|
||||
ACTIVE,
|
||||
@JsonProperty("CREATING")
|
||||
CREATING,
|
||||
@JsonProperty("DELETING")
|
||||
DELETING,
|
||||
@JsonProperty("FAILED")
|
||||
FAILED,
|
||||
@JsonProperty("HEALING")
|
||||
HEALING,
|
||||
@JsonProperty("MAINTENANCE")
|
||||
MAINTENANCE,
|
||||
@JsonProperty("REBOOTING_BROKER")
|
||||
REBOOTING_BROKER,
|
||||
@JsonProperty("UPDATING")
|
||||
UPDATING
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package io.github.hectorvent.floci.services.msk.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public class MskCluster {
|
||||
|
||||
@JsonProperty("clusterArn")
|
||||
private String clusterArn;
|
||||
|
||||
@JsonProperty("clusterName")
|
||||
private String clusterName;
|
||||
|
||||
@JsonProperty("state")
|
||||
private ClusterState state;
|
||||
|
||||
@JsonProperty("creationTime")
|
||||
private Instant creationTime;
|
||||
|
||||
@JsonProperty("currentVersion")
|
||||
private String currentVersion;
|
||||
|
||||
@JsonProperty("numberOfBrokerNodes")
|
||||
private int numberOfBrokerNodes;
|
||||
|
||||
@JsonProperty("tags")
|
||||
private Map<String, String> tags;
|
||||
|
||||
@JsonProperty("zookeeperConnectString")
|
||||
private String zookeeperConnectString;
|
||||
|
||||
// Internal field, not directly in AWS response but needed for GetBootstrapBrokers
|
||||
private String bootstrapBrokers;
|
||||
|
||||
// Docker container ID for mock=false
|
||||
private String containerId;
|
||||
|
||||
public MskCluster() {}
|
||||
|
||||
public MskCluster(String clusterArn, String clusterName) {
|
||||
this.clusterArn = clusterArn;
|
||||
this.clusterName = clusterName;
|
||||
this.state = ClusterState.CREATING;
|
||||
this.creationTime = Instant.now();
|
||||
this.currentVersion = "K3V6I1"; // Example version
|
||||
this.numberOfBrokerNodes = 1;
|
||||
this.zookeeperConnectString = "localhost:2181"; // Mock ZK
|
||||
}
|
||||
|
||||
public String getClusterArn() { return clusterArn; }
|
||||
public void setClusterArn(String clusterArn) { this.clusterArn = clusterArn; }
|
||||
|
||||
public String getClusterName() { return clusterName; }
|
||||
public void setClusterName(String clusterName) { this.clusterName = clusterName; }
|
||||
|
||||
public ClusterState getState() { return state; }
|
||||
public void setState(ClusterState state) { this.state = state; }
|
||||
|
||||
public Instant getCreationTime() { return creationTime; }
|
||||
public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }
|
||||
|
||||
public String getCurrentVersion() { return currentVersion; }
|
||||
public void setCurrentVersion(String currentVersion) { this.currentVersion = currentVersion; }
|
||||
|
||||
public int getNumberOfBrokerNodes() { return numberOfBrokerNodes; }
|
||||
public void setNumberOfBrokerNodes(int numberOfBrokerNodes) { this.numberOfBrokerNodes = numberOfBrokerNodes; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
|
||||
public String getZookeeperConnectString() { return zookeeperConnectString; }
|
||||
public void setZookeeperConnectString(String zookeeperConnectString) { this.zookeeperConnectString = zookeeperConnectString; }
|
||||
|
||||
public String getBootstrapBrokers() { return bootstrapBrokers; }
|
||||
public void setBootstrapBrokers(String bootstrapBrokers) { this.bootstrapBrokers = bootstrapBrokers; }
|
||||
|
||||
public String getContainerId() { return containerId; }
|
||||
public void setContainerId(String containerId) { this.containerId = containerId; }
|
||||
}
|
||||
+33
-1
@@ -10,10 +10,12 @@ import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.CreateContainerResponse;
|
||||
import com.github.dockerjava.api.model.Bind;
|
||||
import com.github.dockerjava.api.model.ExposedPort;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.HostConfig;
|
||||
import com.github.dockerjava.api.model.Ports;
|
||||
import com.github.dockerjava.api.model.Volume;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -21,6 +23,7 @@ import org.jboss.logging.Logger;
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
@@ -70,7 +73,37 @@ public class RdsContainerManager {
|
||||
|
||||
int enginePort = engine.defaultPort();
|
||||
|
||||
String hostPersistentPath = config.storage().hostPersistentPath();
|
||||
boolean isVolume = !hostPersistentPath.startsWith("/") && !hostPersistentPath.startsWith(".");
|
||||
|
||||
HostConfig hostConfig = buildHostConfig(enginePort);
|
||||
List<String> envVars = buildEnvVars(engine, masterUsername, masterPassword, dbName);
|
||||
|
||||
if (isVolume) {
|
||||
String internalMountPath = "/app/data";
|
||||
hostConfig.withBinds(new Bind(hostPersistentPath, new Volume(internalMountPath)));
|
||||
String dataPath = internalMountPath + "/rds/" + instanceId;
|
||||
if (engine == DatabaseEngine.POSTGRES) {
|
||||
envVars.add("PGDATA=" + dataPath);
|
||||
} else {
|
||||
// MySQL / MariaDB typically use /var/lib/mysql
|
||||
// For volume mode, we can't easily remount a subpath to /var/lib/mysql
|
||||
// but we can try to change the engine's data dir via CMD if needed.
|
||||
// For now, let's use Bind for directory mode and warn for Volume mode if not Postgres.
|
||||
LOG.warnv("Volume-based persistence for RDS engine {0} is currently only optimized for POSTGRES. Using default non-persistent path.", engine);
|
||||
}
|
||||
} else {
|
||||
String dataPath = Path.of(config.storage().persistentPath(), "rds", instanceId).toAbsolutePath().toString();
|
||||
try {
|
||||
java.nio.file.Files.createDirectories(Path.of(dataPath));
|
||||
String hostDataPath = Path.of(hostPersistentPath, "rds", instanceId).toAbsolutePath().toString();
|
||||
String target = (engine == DatabaseEngine.POSTGRES) ? "/var/lib/postgresql/data" : "/var/lib/mysql";
|
||||
hostConfig.withBinds(new Bind(hostDataPath, new Volume(target)));
|
||||
} catch (IOException e) {
|
||||
LOG.errorv("Failed to create RDS data directory: {0}", dataPath, e);
|
||||
}
|
||||
}
|
||||
|
||||
String containerName = "floci-rds-" + instanceId;
|
||||
|
||||
config.services().rds().dockerNetwork()
|
||||
@@ -90,7 +123,6 @@ public class RdsContainerManager {
|
||||
// No existing container — normal path
|
||||
}
|
||||
|
||||
List<String> envVars = buildEnvVars(engine, masterUsername, masterPassword, dbName);
|
||||
List<String> cmd = buildContainerCmd(engine);
|
||||
|
||||
var createCmd = dockerClient.createContainerCmd(image)
|
||||
|
||||
Reference in new issue
Block a user