Remove MCP backend, entrypoint injection, and docs; add migration shim
Completes the removal begun in the previous commit. Backend: deletes models/mcp_server.rs, storage/mcp_store.rs and commands/mcp_commands.rs, the McpStore on AppState, the four IPC handlers, Project::enabled_mcp_servers, build_mcp_servers_json(), compute_mcp_fingerprint(), the MCP_SERVERS_JSON env injection, the mcp-fingerprint label, and the whole MCP container lifecycle. create_container() and container_needs_recreation() lose their mcp_servers/network_name parameters. Container: entrypoint.sh no longer merges MCP_SERVERS_JSON into ~/.claude.json. MCP_SERVERS_JSON stays in the reserved env blocklist. Security: the Docker socket is no longer auto-mounted for stdio+Docker MCP servers — it now mounts only when allow_docker_access is set. Migration: old containers were created with network_mode=triple-c-net-<projectId> and refuse to start once that network is gone. docker/network.rs becomes docker/legacy_cleanup.rs with label-driven, best-effort removal of leftover MCP containers and the per-project network, called on both delete and recreate. container_needs_recreation() now forces a rebuild for any container carrying a non-empty triple-c.mcp-fingerprint label or attached to a triple-c-net-* network, moving it onto the default bridge. Both can be dropped a release later. Docs: drops the MCP sections from README/HOW-TO-USE/TECHNICAL and adds a short note pointing at Claude Code's native `claude mcp` / `/mcp` / .mcp.json instead. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -8,7 +8,7 @@ use std::collections::HashMap;
|
||||
use sha2::{Sha256, Digest};
|
||||
|
||||
use super::client::get_docker;
|
||||
use crate::models::{Backend, BedrockAuthMethod, ClaudeCodeSettings, ContainerInfo, EnvVar, GlobalAwsSettings, GlobalOllamaSettings, GlobalOpenAiCompatibleSettings, McpServer, McpTransportType, PortMapping, Project, ProjectPath};
|
||||
use crate::models::{Backend, BedrockAuthMethod, ClaudeCodeSettings, ContainerInfo, EnvVar, GlobalAwsSettings, GlobalOllamaSettings, GlobalOpenAiCompatibleSettings, PortMapping, Project, ProjectPath};
|
||||
|
||||
const SCHEDULER_INSTRUCTIONS: &str = r#"## Scheduled Tasks
|
||||
|
||||
@@ -175,6 +175,8 @@ fn build_claude_instructions(
|
||||
/// Sorted alphabetically so order changes do not cause spurious recreation.
|
||||
fn compute_env_fingerprint(custom_env_vars: &[EnvVar]) -> String {
|
||||
let reserved_prefixes = ["ANTHROPIC_", "AWS_", "GIT_", "HOST_", "TRIPLE_C_"];
|
||||
// MCP_SERVERS_JSON is reserved for legacy reasons: the built-in MCP feature was
|
||||
// removed, but the name stays blocked so users cannot hand-set it.
|
||||
let reserved_exact = ["CLAUDE_INSTRUCTIONS", "MCP_SERVERS_JSON", "CLAUDE_CODE_SETTINGS_JSON", "MISSION_CONTROL_ENABLED"];
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
for env_var in custom_env_vars {
|
||||
@@ -476,83 +478,6 @@ fn build_claude_code_settings_json(
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the JSON value for MCP servers config to be injected into ~/.claude.json.
|
||||
/// Produces `{"mcpServers": {"name": {"type": "stdio", ...}, ...}}`.
|
||||
///
|
||||
/// Handles 4 modes:
|
||||
/// - Stdio+Docker: `docker exec -i <mcp-container-name> <command> ...args`
|
||||
/// - Stdio+Manual: `<command> ...args` (existing behavior)
|
||||
/// - HTTP+Docker: `streamableHttp` URL pointing to `http://<mcp-container-name>:<port>/mcp`
|
||||
/// - HTTP+Manual: `streamableHttp` with user-provided URL + headers
|
||||
fn build_mcp_servers_json(servers: &[McpServer]) -> String {
|
||||
let mut mcp_map = serde_json::Map::new();
|
||||
for server in servers {
|
||||
let mut entry = serde_json::Map::new();
|
||||
match server.transport_type {
|
||||
McpTransportType::Stdio => {
|
||||
entry.insert("type".to_string(), serde_json::json!("stdio"));
|
||||
if server.is_docker() {
|
||||
// Stdio+Docker: use `docker exec` to communicate with MCP container
|
||||
entry.insert("command".to_string(), serde_json::json!("docker"));
|
||||
let mut args = vec![
|
||||
"exec".to_string(),
|
||||
"-i".to_string(),
|
||||
server.mcp_container_name(),
|
||||
];
|
||||
if let Some(ref cmd) = server.command {
|
||||
args.push(cmd.clone());
|
||||
}
|
||||
args.extend(server.args.iter().cloned());
|
||||
entry.insert("args".to_string(), serde_json::json!(args));
|
||||
} else {
|
||||
// Stdio+Manual: existing behavior
|
||||
if let Some(ref cmd) = server.command {
|
||||
entry.insert("command".to_string(), serde_json::json!(cmd));
|
||||
}
|
||||
if !server.args.is_empty() {
|
||||
entry.insert("args".to_string(), serde_json::json!(server.args));
|
||||
}
|
||||
}
|
||||
if !server.env.is_empty() {
|
||||
entry.insert("env".to_string(), serde_json::json!(server.env));
|
||||
}
|
||||
}
|
||||
McpTransportType::Http => {
|
||||
entry.insert("type".to_string(), serde_json::json!("streamableHttp"));
|
||||
if server.is_docker() {
|
||||
// HTTP+Docker: point to MCP container by name on the shared network
|
||||
let url = format!(
|
||||
"http://{}:{}/mcp",
|
||||
server.mcp_container_name(),
|
||||
server.effective_container_port()
|
||||
);
|
||||
entry.insert("url".to_string(), serde_json::json!(url));
|
||||
} else {
|
||||
// HTTP+Manual: user-provided URL + headers
|
||||
if let Some(ref url) = server.url {
|
||||
entry.insert("url".to_string(), serde_json::json!(url));
|
||||
}
|
||||
if !server.headers.is_empty() {
|
||||
entry.insert("headers".to_string(), serde_json::json!(server.headers));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mcp_map.insert(server.name.clone(), serde_json::Value::Object(entry));
|
||||
}
|
||||
let wrapper = serde_json::json!({ "mcpServers": mcp_map });
|
||||
serde_json::to_string(&wrapper).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Compute a fingerprint for MCP server configuration so we can detect changes.
|
||||
fn compute_mcp_fingerprint(servers: &[McpServer]) -> String {
|
||||
if servers.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let json = build_mcp_servers_json(servers);
|
||||
sha256_hex(&json)
|
||||
}
|
||||
|
||||
pub async fn find_existing_container(project: &Project) -> Result<Option<String>, String> {
|
||||
let docker = get_docker()?;
|
||||
let container_name = project.container_name();
|
||||
@@ -594,8 +519,6 @@ pub async fn create_container(
|
||||
global_claude_instructions: Option<&str>,
|
||||
global_custom_env_vars: &[EnvVar],
|
||||
timezone: Option<&str>,
|
||||
mcp_servers: &[McpServer],
|
||||
network_name: Option<&str>,
|
||||
global_claude_code_settings: Option<&ClaudeCodeSettings>,
|
||||
default_ssh_key_path: Option<&str>,
|
||||
default_git_user_name: Option<&str>,
|
||||
@@ -795,6 +718,8 @@ pub async fn create_container(
|
||||
// Custom environment variables (global + per-project, project overrides global for same key)
|
||||
let merged_env = merge_custom_env_vars(global_custom_env_vars, &project.custom_env_vars);
|
||||
let reserved_prefixes = ["ANTHROPIC_", "AWS_", "GIT_", "HOST_", "TRIPLE_C_"];
|
||||
// MCP_SERVERS_JSON is reserved for legacy reasons: the built-in MCP feature was
|
||||
// removed, but the name stays blocked so users cannot hand-set it.
|
||||
let reserved_exact = ["CLAUDE_INSTRUCTIONS", "MCP_SERVERS_JSON", "CLAUDE_CODE_SETTINGS_JSON", "MISSION_CONTROL_ENABLED"];
|
||||
for env_var in &merged_env {
|
||||
let key = env_var.key.trim();
|
||||
@@ -838,12 +763,6 @@ pub async fn create_container(
|
||||
env_vars.push(format!("CLAUDE_INSTRUCTIONS={}", instructions));
|
||||
}
|
||||
|
||||
// MCP servers config
|
||||
if !mcp_servers.is_empty() {
|
||||
let mcp_json = build_mcp_servers_json(mcp_servers);
|
||||
env_vars.push(format!("MCP_SERVERS_JSON={}", mcp_json));
|
||||
}
|
||||
|
||||
// Claude Code settings (global + per-project merged)
|
||||
let merged_cc_settings = merge_claude_code_settings(
|
||||
global_claude_code_settings,
|
||||
@@ -964,12 +883,8 @@ pub async fn create_container(
|
||||
}
|
||||
}
|
||||
|
||||
// Docker socket (if allowed, or auto-enabled for stdio+Docker MCP servers)
|
||||
let needs_docker_for_mcp = any_stdio_docker_mcp(mcp_servers);
|
||||
if project.allow_docker_access || needs_docker_for_mcp {
|
||||
if needs_docker_for_mcp && !project.allow_docker_access {
|
||||
log::info!("Auto-enabling Docker socket access for stdio+Docker MCP servers");
|
||||
}
|
||||
// Docker socket (if allowed)
|
||||
if project.allow_docker_access {
|
||||
// On Windows, the named pipe (//./pipe/docker_engine) cannot be
|
||||
// bind-mounted into a Linux container. Docker Desktop exposes the
|
||||
// daemon socket as /var/run/docker.sock for container mounts.
|
||||
@@ -1014,7 +929,6 @@ pub async fn create_container(
|
||||
labels.insert("triple-c.ports-fingerprint".to_string(), compute_ports_fingerprint(&project.port_mappings));
|
||||
labels.insert("triple-c.image".to_string(), image_name.to_string());
|
||||
labels.insert("triple-c.timezone".to_string(), timezone.unwrap_or("").to_string());
|
||||
labels.insert("triple-c.mcp-fingerprint".to_string(), compute_mcp_fingerprint(mcp_servers));
|
||||
labels.insert("triple-c.mission-control".to_string(), project.mission_control_enabled.to_string());
|
||||
labels.insert("triple-c.custom-env-fingerprint".to_string(), custom_env_fingerprint.clone());
|
||||
labels.insert("triple-c.claude-code-settings-fingerprint".to_string(),
|
||||
@@ -1030,8 +944,6 @@ pub async fn create_container(
|
||||
mounts: Some(mounts),
|
||||
port_bindings: if port_bindings.is_empty() { None } else { Some(port_bindings) },
|
||||
init: Some(true),
|
||||
// Connect to project network if specified (for MCP container communication)
|
||||
network_mode: network_name.map(|n| n.to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -1307,7 +1219,6 @@ pub async fn container_needs_recreation(
|
||||
global_claude_instructions: Option<&str>,
|
||||
global_custom_env_vars: &[EnvVar],
|
||||
timezone: Option<&str>,
|
||||
mcp_servers: &[McpServer],
|
||||
global_claude_code_settings: Option<&ClaudeCodeSettings>,
|
||||
default_ssh_key_path: Option<&str>,
|
||||
default_git_user_name: Option<&str>,
|
||||
@@ -1514,11 +1425,29 @@ pub async fn container_needs_recreation(
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
// ── MCP servers fingerprint ─────────────────────────────────────────
|
||||
let expected_mcp_fp = compute_mcp_fingerprint(mcp_servers);
|
||||
let container_mcp_fp = get_label("triple-c.mcp-fingerprint").unwrap_or_default();
|
||||
if container_mcp_fp != expected_mcp_fp {
|
||||
log::info!("MCP servers fingerprint mismatch (container={:?}, expected={:?})", container_mcp_fp, expected_mcp_fp);
|
||||
// ── Legacy MCP migration shim ───────────────────────────────────────
|
||||
// One-release migration for containers created before the built-in MCP
|
||||
// feature was removed. Such containers carry a `triple-c.mcp-fingerprint`
|
||||
// label and/or are attached to the per-project `triple-c-net-<id>` network.
|
||||
// That user-defined network is deleted during cleanup, and a container
|
||||
// whose NetworkMode points at a missing network refuses to start — so force
|
||||
// a recreation to move them onto the default bridge. Containers created by
|
||||
// the current code never carry the label or the network, so this is a no-op
|
||||
// for them and can be dropped a release later.
|
||||
if let Some(fp) = get_label("triple-c.mcp-fingerprint") {
|
||||
if !fp.is_empty() {
|
||||
log::info!("Legacy container carries triple-c.mcp-fingerprint label — recreating without MCP");
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
let legacy_network = info
|
||||
.host_config
|
||||
.as_ref()
|
||||
.and_then(|hc| hc.network_mode.as_deref())
|
||||
.map(|nm| nm.starts_with("triple-c-net-"))
|
||||
.unwrap_or(false);
|
||||
if legacy_network {
|
||||
log::info!("Legacy container attached to a triple-c-net-* network — recreating without MCP");
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
@@ -1590,173 +1519,3 @@ pub async fn list_sibling_containers() -> Result<Vec<ContainerSummary>, String>
|
||||
|
||||
Ok(siblings)
|
||||
}
|
||||
|
||||
// ── MCP Container Lifecycle ─────────────────────────────────────────────
|
||||
|
||||
/// Returns true if any MCP server uses stdio transport with Docker.
|
||||
pub fn any_stdio_docker_mcp(servers: &[McpServer]) -> bool {
|
||||
servers.iter().any(|s| s.is_docker() && s.transport_type == McpTransportType::Stdio)
|
||||
}
|
||||
|
||||
/// Find an existing MCP container by its expected name.
|
||||
pub async fn find_mcp_container(server: &McpServer) -> Result<Option<String>, String> {
|
||||
let docker = get_docker()?;
|
||||
let container_name = server.mcp_container_name();
|
||||
|
||||
let filters: HashMap<String, Vec<String>> = HashMap::from([
|
||||
("name".to_string(), vec![container_name.clone()]),
|
||||
]);
|
||||
|
||||
let containers: Vec<ContainerSummary> = docker
|
||||
.list_containers(Some(ListContainersOptions {
|
||||
all: true,
|
||||
filters,
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
.map_err(|e| format!("Failed to list MCP containers: {}", e))?;
|
||||
|
||||
let expected = format!("/{}", container_name);
|
||||
for c in &containers {
|
||||
if let Some(names) = &c.names {
|
||||
if names.iter().any(|n| n == &expected) {
|
||||
return Ok(c.id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Create a Docker container for an MCP server.
|
||||
pub async fn create_mcp_container(
|
||||
server: &McpServer,
|
||||
network_name: &str,
|
||||
) -> Result<String, String> {
|
||||
let docker = get_docker()?;
|
||||
let container_name = server.mcp_container_name();
|
||||
|
||||
let image = server
|
||||
.docker_image
|
||||
.as_ref()
|
||||
.ok_or_else(|| format!("MCP server '{}' has no docker_image", server.name))?;
|
||||
|
||||
let mut env_vars: Vec<String> = Vec::new();
|
||||
for (k, v) in &server.env {
|
||||
env_vars.push(format!("{}={}", k, v));
|
||||
}
|
||||
|
||||
// Build command + args as Cmd
|
||||
let mut cmd: Vec<String> = Vec::new();
|
||||
if let Some(ref command) = server.command {
|
||||
cmd.push(command.clone());
|
||||
}
|
||||
cmd.extend(server.args.iter().cloned());
|
||||
|
||||
let mut labels = HashMap::new();
|
||||
labels.insert("triple-c.managed".to_string(), "true".to_string());
|
||||
labels.insert("triple-c.mcp-server".to_string(), server.id.clone());
|
||||
|
||||
let host_config = HostConfig {
|
||||
network_mode: Some(network_name.to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let config = Config {
|
||||
image: Some(image.clone()),
|
||||
env: if env_vars.is_empty() { None } else { Some(env_vars) },
|
||||
cmd: if cmd.is_empty() { None } else { Some(cmd) },
|
||||
labels: Some(labels),
|
||||
host_config: Some(host_config),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let options = CreateContainerOptions {
|
||||
name: container_name.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let response = docker
|
||||
.create_container(Some(options), config)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to create MCP container '{}': {}", container_name, e))?;
|
||||
|
||||
log::info!(
|
||||
"Created MCP container {} (image: {}) on network {}",
|
||||
container_name,
|
||||
image,
|
||||
network_name
|
||||
);
|
||||
Ok(response.id)
|
||||
}
|
||||
|
||||
/// Start all Docker-based MCP server containers. Finds or creates each one.
|
||||
pub async fn start_mcp_containers(
|
||||
servers: &[McpServer],
|
||||
network_name: &str,
|
||||
) -> Result<(), String> {
|
||||
for server in servers {
|
||||
if !server.is_docker() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let container_id = if let Some(existing_id) = find_mcp_container(server).await? {
|
||||
log::debug!("Found existing MCP container for '{}'", server.name);
|
||||
existing_id
|
||||
} else {
|
||||
create_mcp_container(server, network_name).await?
|
||||
};
|
||||
|
||||
// Start the container (ignore already-started errors)
|
||||
if let Err(e) = start_container(&container_id).await {
|
||||
let err_str = e.to_string();
|
||||
if err_str.contains("already started") || err_str.contains("304") {
|
||||
log::debug!("MCP container '{}' already running", server.name);
|
||||
} else {
|
||||
return Err(format!(
|
||||
"Failed to start MCP container '{}': {}",
|
||||
server.name, e
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
log::info!("MCP container '{}' started", server.name);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop all Docker-based MCP server containers (best-effort).
|
||||
pub async fn stop_mcp_containers(servers: &[McpServer]) -> Result<(), String> {
|
||||
for server in servers {
|
||||
if !server.is_docker() {
|
||||
continue;
|
||||
}
|
||||
if let Ok(Some(container_id)) = find_mcp_container(server).await {
|
||||
if let Err(e) = stop_container(&container_id).await {
|
||||
log::warn!("Failed to stop MCP container '{}': {}", server.name, e);
|
||||
} else {
|
||||
log::info!("Stopped MCP container '{}'", server.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop and remove all Docker-based MCP server containers (best-effort).
|
||||
pub async fn remove_mcp_containers(servers: &[McpServer]) -> Result<(), String> {
|
||||
for server in servers {
|
||||
if !server.is_docker() {
|
||||
continue;
|
||||
}
|
||||
if let Ok(Some(container_id)) = find_mcp_container(server).await {
|
||||
let _ = stop_container(&container_id).await;
|
||||
if let Err(e) = remove_container(&container_id).await {
|
||||
log::warn!("Failed to remove MCP container '{}': {}", server.name, e);
|
||||
} else {
|
||||
log::info!("Removed MCP container '{}'", server.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! One-release migration shim for the removed built-in MCP feature.
|
||||
//!
|
||||
//! Older releases created a per-project user-defined bridge network
|
||||
//! (`triple-c-net-<projectId>`) plus one container per Docker-backed MCP
|
||||
//! server, and attached the project container to that network. Now that MCP
|
||||
//! support is gone, those leftovers have to be torn down — a container whose
|
||||
//! `NetworkMode` names a network that no longer exists refuses to start, so
|
||||
//! the cleanup is paired with a forced container recreation (see
|
||||
//! `container_needs_recreation`).
|
||||
//!
|
||||
//! Everything here is best-effort: failures are logged and never abort the
|
||||
//! caller, and absent resources are a silent no-op. This module can be deleted
|
||||
//! a release after all users have migrated.
|
||||
|
||||
use bollard::container::{ListContainersOptions, RemoveContainerOptions};
|
||||
use bollard::network::InspectNetworkOptions;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::client::get_docker;
|
||||
|
||||
/// Network name used by the old MCP implementation for a project.
|
||||
fn legacy_network_name(project_id: &str) -> String {
|
||||
format!("triple-c-net-{}", project_id)
|
||||
}
|
||||
|
||||
/// Force-remove every leftover MCP server container.
|
||||
///
|
||||
/// Matched by the `triple-c.mcp-server` label rather than by name, so
|
||||
/// containers survive even if the MCP server definitions they came from are
|
||||
/// already gone from storage. Best-effort: errors are logged and skipped.
|
||||
pub async fn remove_legacy_mcp_containers(project_id: &str) {
|
||||
let docker = match get_docker() {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
log::debug!(
|
||||
"Skipping legacy MCP container cleanup for project {}: {}",
|
||||
project_id,
|
||||
e
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let filters: HashMap<String, Vec<String>> = HashMap::from([(
|
||||
"label".to_string(),
|
||||
vec!["triple-c.mcp-server".to_string()],
|
||||
)]);
|
||||
|
||||
let containers = match docker
|
||||
.list_containers(Some(ListContainersOptions {
|
||||
all: true,
|
||||
filters,
|
||||
..Default::default()
|
||||
}))
|
||||
.await
|
||||
{
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::warn!("Failed to list legacy MCP containers: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
for container in containers {
|
||||
let Some(id) = container.id else { continue };
|
||||
match docker
|
||||
.remove_container(
|
||||
&id,
|
||||
Some(RemoveContainerOptions {
|
||||
force: true,
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => log::info!("Removed legacy MCP container {}", id),
|
||||
Err(e) => log::warn!("Failed to remove legacy MCP container {}: {}", id, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the old per-project Docker network, disconnecting any remaining
|
||||
/// members first (a network with attached endpoints cannot be deleted).
|
||||
///
|
||||
/// Silent no-op when the network does not exist. Best-effort: errors are
|
||||
/// logged and never propagated.
|
||||
pub async fn remove_legacy_project_network(project_id: &str) {
|
||||
let docker = match get_docker() {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
log::debug!(
|
||||
"Skipping legacy network cleanup for project {}: {}",
|
||||
project_id,
|
||||
e
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let network_name = legacy_network_name(project_id);
|
||||
|
||||
// Inspect to discover connected containers; absence means nothing to do.
|
||||
let info = match docker
|
||||
.inspect_network(&network_name, None::<InspectNetworkOptions<String>>)
|
||||
.await
|
||||
{
|
||||
Ok(info) => info,
|
||||
Err(_) => {
|
||||
log::debug!("Legacy network {} not present, nothing to do", network_name);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(containers) = info.containers {
|
||||
for container_id in containers.into_keys() {
|
||||
let disconnect_opts = bollard::network::DisconnectNetworkOptions {
|
||||
container: container_id.clone(),
|
||||
force: true,
|
||||
};
|
||||
if let Err(e) = docker
|
||||
.disconnect_network(&network_name, disconnect_opts)
|
||||
.await
|
||||
{
|
||||
log::warn!(
|
||||
"Failed to disconnect container {} from legacy network {}: {}",
|
||||
container_id,
|
||||
network_name,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match docker.remove_network(&network_name).await {
|
||||
Ok(_) => log::info!("Removed legacy Docker network {}", network_name),
|
||||
Err(e) => log::warn!("Failed to remove legacy network {}: {}", network_name, e),
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ pub mod client;
|
||||
pub mod container;
|
||||
pub mod image;
|
||||
pub mod exec;
|
||||
pub mod network;
|
||||
pub mod legacy_cleanup;
|
||||
pub mod stt;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
@@ -16,4 +16,4 @@ pub use image::*;
|
||||
#[allow(unused_imports)]
|
||||
pub use exec::*;
|
||||
#[allow(unused_imports)]
|
||||
pub use network::*;
|
||||
pub use legacy_cleanup::*;
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
use bollard::network::{CreateNetworkOptions, InspectNetworkOptions};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::client::get_docker;
|
||||
|
||||
/// Network name for a project's MCP containers.
|
||||
fn project_network_name(project_id: &str) -> String {
|
||||
format!("triple-c-net-{}", project_id)
|
||||
}
|
||||
|
||||
/// Ensure a Docker bridge network exists for the project.
|
||||
/// Returns the network name.
|
||||
pub async fn ensure_project_network(project_id: &str) -> Result<String, String> {
|
||||
let docker = get_docker()?;
|
||||
let network_name = project_network_name(project_id);
|
||||
|
||||
// Check if network already exists
|
||||
match docker
|
||||
.inspect_network(&network_name, None::<InspectNetworkOptions<String>>)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
log::debug!("Network {} already exists", network_name);
|
||||
return Ok(network_name);
|
||||
}
|
||||
Err(_) => {
|
||||
// Network doesn't exist, create it
|
||||
}
|
||||
}
|
||||
|
||||
let options = CreateNetworkOptions {
|
||||
name: network_name.clone(),
|
||||
driver: "bridge".to_string(),
|
||||
labels: HashMap::from([
|
||||
("triple-c.managed".to_string(), "true".to_string()),
|
||||
("triple-c.project-id".to_string(), project_id.to_string()),
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
docker
|
||||
.create_network(options)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to create network {}: {}", network_name, e))?;
|
||||
|
||||
log::info!("Created Docker network {}", network_name);
|
||||
Ok(network_name)
|
||||
}
|
||||
|
||||
/// Connect a container to the project network.
|
||||
#[allow(dead_code)]
|
||||
pub async fn connect_container_to_network(
|
||||
container_id: &str,
|
||||
network_name: &str,
|
||||
) -> Result<(), String> {
|
||||
let docker = get_docker()?;
|
||||
|
||||
let config = bollard::network::ConnectNetworkOptions {
|
||||
container: container_id.to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
docker
|
||||
.connect_network(network_name, config)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"Failed to connect container {} to network {}: {}",
|
||||
container_id, network_name, e
|
||||
)
|
||||
})?;
|
||||
|
||||
log::debug!(
|
||||
"Connected container {} to network {}",
|
||||
container_id,
|
||||
network_name
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove the project network (best-effort). Disconnects all containers first.
|
||||
pub async fn remove_project_network(project_id: &str) -> Result<(), String> {
|
||||
let docker = get_docker()?;
|
||||
let network_name = project_network_name(project_id);
|
||||
|
||||
// Inspect to get connected containers
|
||||
let info = match docker
|
||||
.inspect_network(&network_name, None::<InspectNetworkOptions<String>>)
|
||||
.await
|
||||
{
|
||||
Ok(info) => info,
|
||||
Err(_) => {
|
||||
log::debug!(
|
||||
"Network {} not found, nothing to remove",
|
||||
network_name
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
// Disconnect all containers
|
||||
if let Some(containers) = info.containers {
|
||||
for (container_id, _) in containers {
|
||||
let disconnect_opts = bollard::network::DisconnectNetworkOptions {
|
||||
container: container_id.clone(),
|
||||
force: true,
|
||||
};
|
||||
if let Err(e) = docker
|
||||
.disconnect_network(&network_name, disconnect_opts)
|
||||
.await
|
||||
{
|
||||
log::warn!(
|
||||
"Failed to disconnect container {} from network {}: {}",
|
||||
container_id,
|
||||
network_name,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the network
|
||||
match docker.remove_network(&network_name).await {
|
||||
Ok(_) => log::info!("Removed Docker network {}", network_name),
|
||||
Err(e) => log::warn!("Failed to remove network {}: {}", network_name, e),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user