Skip to main content

opencode_cloud_core/docker/
container.rs

1//! Docker container lifecycle management
2//!
3//! This module provides functions to create, start, stop, and remove
4//! Docker containers for the opencode-cloud service.
5
6use super::dockerfile::{IMAGE_NAME_GHCR, IMAGE_TAG_DEFAULT};
7use super::mount::ParsedMount;
8use super::volume::{
9    MOUNT_CACHE, MOUNT_CONFIG, MOUNT_PROJECTS, MOUNT_SESSION, MOUNT_STATE, VOLUME_CACHE,
10    VOLUME_CONFIG, VOLUME_PROJECTS, VOLUME_SESSION, VOLUME_STATE,
11};
12use super::{DockerClient, DockerError};
13use bollard::container::{
14    Config, CreateContainerOptions, RemoveContainerOptions, StartContainerOptions,
15    StopContainerOptions,
16};
17use bollard::service::{
18    HostConfig, Mount, MountPointTypeEnum, MountTypeEnum, PortBinding, PortMap,
19};
20use std::collections::{HashMap, HashSet};
21use tracing::debug;
22
23/// Default container name
24pub const CONTAINER_NAME: &str = "opencode-cloud-sandbox";
25
26/// Default port for opencode web UI
27pub const OPENCODE_WEB_PORT: u16 = 3000;
28
29fn has_env_key(env: &[String], key: &str) -> bool {
30    let prefix = format!("{key}=");
31    env.iter().any(|entry| entry.starts_with(&prefix))
32}
33
34/// Create the opencode container with volume mounts
35///
36/// Does not start the container - use start_container after creation.
37/// Returns the container ID on success.
38///
39/// # Arguments
40/// * `client` - Docker client
41/// * `name` - Container name (defaults to CONTAINER_NAME)
42/// * `image` - Image to use (defaults to IMAGE_NAME_GHCR:IMAGE_TAG_DEFAULT)
43/// * `opencode_web_port` - Port to bind on host for opencode web UI (defaults to OPENCODE_WEB_PORT)
44/// * `env_vars` - Additional environment variables (optional)
45/// * `bind_address` - IP address to bind on host (defaults to "127.0.0.1")
46/// * `cockpit_port` - Port to bind on host for Cockpit (defaults to 9090)
47/// * `cockpit_enabled` - Whether to enable Cockpit port mapping (defaults to false)
48/// * `bind_mounts` - User-defined bind mounts from config and CLI flags (optional)
49#[allow(clippy::too_many_arguments)]
50pub async fn create_container(
51    client: &DockerClient,
52    name: Option<&str>,
53    image: Option<&str>,
54    opencode_web_port: Option<u16>,
55    env_vars: Option<Vec<String>>,
56    bind_address: Option<&str>,
57    cockpit_port: Option<u16>,
58    cockpit_enabled: Option<bool>,
59    bind_mounts: Option<Vec<ParsedMount>>,
60) -> Result<String, DockerError> {
61    let container_name = name.unwrap_or(CONTAINER_NAME);
62    let default_image = format!("{IMAGE_NAME_GHCR}:{IMAGE_TAG_DEFAULT}");
63    let image_name = image.unwrap_or(&default_image);
64    let port = opencode_web_port.unwrap_or(OPENCODE_WEB_PORT);
65    let cockpit_port_val = cockpit_port.unwrap_or(9090);
66    let cockpit_enabled_val = cockpit_enabled.unwrap_or(false);
67
68    debug!(
69        "Creating container {} from image {} with port {} and cockpit_port {} (enabled: {})",
70        container_name, image_name, port, cockpit_port_val, cockpit_enabled_val
71    );
72
73    // Check if container already exists
74    if container_exists(client, container_name).await? {
75        return Err(DockerError::Container(format!(
76            "Container '{container_name}' already exists. Remove it first with 'occ stop --remove' or use a different name."
77        )));
78    }
79
80    // Check if image exists
81    let image_parts: Vec<&str> = image_name.split(':').collect();
82    let (image_repo, image_tag) = if image_parts.len() == 2 {
83        (image_parts[0], image_parts[1])
84    } else {
85        (image_name, "latest")
86    };
87
88    if !super::image::image_exists(client, image_repo, image_tag).await? {
89        return Err(DockerError::Container(format!(
90            "Image '{image_name}' not found. Run 'occ pull' first to download the image."
91        )));
92    }
93
94    let mut bind_targets = HashSet::new();
95    if let Some(ref user_mounts) = bind_mounts {
96        for parsed in user_mounts {
97            bind_targets.insert(parsed.container_path.clone());
98        }
99    }
100
101    // Create volume mounts (skip if overridden by bind mounts)
102    let mut mounts = Vec::new();
103    let mut add_volume_mount = |target: &str, source: &str| {
104        if bind_targets.contains(target) {
105            tracing::trace!(
106                "Skipping volume mount for {} (overridden by bind mount)",
107                target
108            );
109            return;
110        }
111        mounts.push(Mount {
112            target: Some(target.to_string()),
113            source: Some(source.to_string()),
114            typ: Some(MountTypeEnum::VOLUME),
115            read_only: Some(false),
116            ..Default::default()
117        });
118    };
119    add_volume_mount(MOUNT_SESSION, VOLUME_SESSION);
120    add_volume_mount(MOUNT_STATE, VOLUME_STATE);
121    add_volume_mount(MOUNT_CACHE, VOLUME_CACHE);
122    add_volume_mount(MOUNT_PROJECTS, VOLUME_PROJECTS);
123    add_volume_mount(MOUNT_CONFIG, VOLUME_CONFIG);
124
125    // Add user-defined bind mounts from config/CLI
126    if let Some(ref user_mounts) = bind_mounts {
127        for parsed in user_mounts {
128            mounts.push(parsed.to_bollard_mount());
129        }
130    }
131
132    // Create port bindings (default to localhost for security)
133    let bind_addr = bind_address.unwrap_or("127.0.0.1");
134    let mut port_bindings: PortMap = HashMap::new();
135
136    // opencode web port
137    port_bindings.insert(
138        "3000/tcp".to_string(),
139        Some(vec![PortBinding {
140            host_ip: Some(bind_addr.to_string()),
141            host_port: Some(port.to_string()),
142        }]),
143    );
144
145    // Cockpit port (if enabled)
146    // Container always listens on 9090, map to host's configured port
147    if cockpit_enabled_val {
148        port_bindings.insert(
149            "9090/tcp".to_string(),
150            Some(vec![PortBinding {
151                host_ip: Some(bind_addr.to_string()),
152                host_port: Some(cockpit_port_val.to_string()),
153            }]),
154        );
155    }
156
157    // Create exposed ports map
158    let mut exposed_ports = HashMap::new();
159    exposed_ports.insert("3000/tcp".to_string(), HashMap::new());
160    if cockpit_enabled_val {
161        exposed_ports.insert("9090/tcp".to_string(), HashMap::new());
162    }
163
164    // Create host config
165    // When Cockpit is enabled, add systemd-specific settings (requires Linux host)
166    // When Cockpit is disabled, use simpler tini-based config (works everywhere)
167    let host_config = if cockpit_enabled_val {
168        HostConfig {
169            mounts: Some(mounts),
170            port_bindings: Some(port_bindings),
171            auto_remove: Some(false),
172            // CAP_SYS_ADMIN required for systemd cgroup access
173            cap_add: Some(vec!["SYS_ADMIN".to_string()]),
174            // tmpfs for /run, /run/lock, and /tmp (required for systemd)
175            tmpfs: Some(HashMap::from([
176                ("/run".to_string(), "exec".to_string()),
177                ("/run/lock".to_string(), String::new()),
178                ("/tmp".to_string(), String::new()),
179            ])),
180            // cgroup mount (read-write for systemd)
181            binds: Some(vec!["/sys/fs/cgroup:/sys/fs/cgroup:rw".to_string()]),
182            // Use HOST cgroup namespace for systemd compatibility across Linux distros:
183            // - cgroups v2 (Amazon Linux 2023, Fedora 31+, Ubuntu 21.10+, Debian 11+): required
184            // - cgroups v1 (CentOS 7, Ubuntu 18.04, Debian 10): works fine
185            // - Docker Desktop (macOS/Windows VM): works fine
186            // Note: PRIVATE mode is more isolated but causes systemd to exit(255) on cgroups v2.
187            // Since we already use privileged mode, HOST namespace is acceptable.
188            cgroupns_mode: Some(bollard::models::HostConfigCgroupnsModeEnum::HOST),
189            // Privileged mode required for systemd to manage cgroups and system services
190            privileged: Some(true),
191            ..Default::default()
192        }
193    } else {
194        // Simple config for tini mode (works on macOS and Linux)
195        HostConfig {
196            mounts: Some(mounts),
197            port_bindings: Some(port_bindings),
198            auto_remove: Some(false),
199            ..Default::default()
200        }
201    };
202
203    // Build environment variables
204    let mut env = env_vars.unwrap_or_default();
205    if !has_env_key(&env, "XDG_DATA_HOME") {
206        env.push("XDG_DATA_HOME=/home/opencode/.local/share".to_string());
207    }
208    if !has_env_key(&env, "XDG_STATE_HOME") {
209        env.push("XDG_STATE_HOME=/home/opencode/.local/state".to_string());
210    }
211    if !has_env_key(&env, "XDG_CONFIG_HOME") {
212        env.push("XDG_CONFIG_HOME=/home/opencode/.config".to_string());
213    }
214    if !has_env_key(&env, "XDG_CACHE_HOME") {
215        env.push("XDG_CACHE_HOME=/home/opencode/.cache".to_string());
216    }
217    // Add USE_SYSTEMD=1 when Cockpit is enabled to tell entrypoint to use systemd
218    if cockpit_enabled_val && !has_env_key(&env, "USE_SYSTEMD") {
219        env.push("USE_SYSTEMD=1".to_string());
220    }
221    let final_env = if env.is_empty() { None } else { Some(env) };
222
223    // Create container config
224    let config = Config {
225        image: Some(image_name.to_string()),
226        hostname: Some(CONTAINER_NAME.to_string()),
227        working_dir: Some("/home/opencode/workspace".to_string()),
228        exposed_ports: Some(exposed_ports),
229        env: final_env,
230        host_config: Some(host_config),
231        ..Default::default()
232    };
233
234    // Create container
235    let options = CreateContainerOptions {
236        name: container_name,
237        platform: None,
238    };
239
240    let response = client
241        .inner()
242        .create_container(Some(options), config)
243        .await
244        .map_err(|e| {
245            let msg = e.to_string();
246            if msg.contains("port is already allocated") || msg.contains("address already in use") {
247                DockerError::Container(format!(
248                    "Port {port} is already in use. Stop the service using that port or use a different port with --port."
249                ))
250            } else {
251                DockerError::Container(format!("Failed to create container: {e}"))
252            }
253        })?;
254
255    debug!("Container created with ID: {}", response.id);
256    Ok(response.id)
257}
258
259/// Start an existing container
260pub async fn start_container(client: &DockerClient, name: &str) -> Result<(), DockerError> {
261    debug!("Starting container: {}", name);
262
263    client
264        .inner()
265        .start_container(name, None::<StartContainerOptions<String>>)
266        .await
267        .map_err(|e| DockerError::Container(format!("Failed to start container {name}: {e}")))?;
268
269    debug!("Container {} started", name);
270    Ok(())
271}
272
273/// Stop a running container with graceful shutdown
274///
275/// # Arguments
276/// * `client` - Docker client
277/// * `name` - Container name
278/// * `timeout_secs` - Seconds to wait before force kill (default: 10)
279pub async fn stop_container(
280    client: &DockerClient,
281    name: &str,
282    timeout_secs: Option<i64>,
283) -> Result<(), DockerError> {
284    let timeout = timeout_secs.unwrap_or(10);
285    debug!("Stopping container {} with {}s timeout", name, timeout);
286
287    let options = StopContainerOptions { t: timeout };
288
289    client
290        .inner()
291        .stop_container(name, Some(options))
292        .await
293        .map_err(|e| {
294            let msg = e.to_string();
295            // "container already stopped" is not an error
296            if msg.contains("is not running") || msg.contains("304") {
297                debug!("Container {} was already stopped", name);
298                return DockerError::Container(format!("Container '{name}' is not running"));
299            }
300            DockerError::Container(format!("Failed to stop container {name}: {e}"))
301        })?;
302
303    debug!("Container {} stopped", name);
304    Ok(())
305}
306
307/// Remove a container
308///
309/// # Arguments
310/// * `client` - Docker client
311/// * `name` - Container name
312/// * `force` - Remove even if running
313pub async fn remove_container(
314    client: &DockerClient,
315    name: &str,
316    force: bool,
317) -> Result<(), DockerError> {
318    debug!("Removing container {} (force={})", name, force);
319
320    let options = RemoveContainerOptions {
321        force,
322        v: false, // Don't remove volumes
323        link: false,
324    };
325
326    client
327        .inner()
328        .remove_container(name, Some(options))
329        .await
330        .map_err(|e| DockerError::Container(format!("Failed to remove container {name}: {e}")))?;
331
332    debug!("Container {} removed", name);
333    Ok(())
334}
335
336/// Check if container exists
337pub async fn container_exists(client: &DockerClient, name: &str) -> Result<bool, DockerError> {
338    debug!("Checking if container exists: {}", name);
339
340    match client.inner().inspect_container(name, None).await {
341        Ok(_) => Ok(true),
342        Err(bollard::errors::Error::DockerResponseServerError {
343            status_code: 404, ..
344        }) => Ok(false),
345        Err(e) => Err(DockerError::Container(format!(
346            "Failed to inspect container {name}: {e}"
347        ))),
348    }
349}
350
351/// Check if container is running
352pub async fn container_is_running(client: &DockerClient, name: &str) -> Result<bool, DockerError> {
353    debug!("Checking if container is running: {}", name);
354
355    match client.inner().inspect_container(name, None).await {
356        Ok(info) => {
357            let running = info.state.and_then(|s| s.running).unwrap_or(false);
358            Ok(running)
359        }
360        Err(bollard::errors::Error::DockerResponseServerError {
361            status_code: 404, ..
362        }) => Ok(false),
363        Err(e) => Err(DockerError::Container(format!(
364            "Failed to inspect container {name}: {e}"
365        ))),
366    }
367}
368
369/// Get container state (running, stopped, etc.)
370pub async fn container_state(client: &DockerClient, name: &str) -> Result<String, DockerError> {
371    debug!("Getting container state: {}", name);
372
373    match client.inner().inspect_container(name, None).await {
374        Ok(info) => {
375            let state = info
376                .state
377                .and_then(|s| s.status)
378                .map(|s| s.to_string())
379                .unwrap_or_else(|| "unknown".to_string());
380            Ok(state)
381        }
382        Err(bollard::errors::Error::DockerResponseServerError {
383            status_code: 404, ..
384        }) => Err(DockerError::Container(format!(
385            "Container '{name}' not found"
386        ))),
387        Err(e) => Err(DockerError::Container(format!(
388            "Failed to inspect container {name}: {e}"
389        ))),
390    }
391}
392
393/// Container port configuration
394#[derive(Debug, Clone)]
395pub struct ContainerPorts {
396    /// Host port for opencode web UI (mapped from container port 3000)
397    pub opencode_port: Option<u16>,
398    /// Host port for Cockpit (mapped from container port 9090)
399    pub cockpit_port: Option<u16>,
400}
401
402/// A bind mount from an existing container
403#[derive(Debug, Clone)]
404pub struct ContainerBindMount {
405    /// Source path on host
406    pub source: String,
407    /// Target path in container
408    pub target: String,
409    /// Read-only flag
410    pub read_only: bool,
411}
412
413/// Get the port bindings from an existing container
414///
415/// Returns the host ports that the container's internal ports are mapped to.
416/// Returns None for ports that aren't mapped.
417pub async fn get_container_ports(
418    client: &DockerClient,
419    name: &str,
420) -> Result<ContainerPorts, DockerError> {
421    debug!("Getting container ports: {}", name);
422
423    let info = client
424        .inner()
425        .inspect_container(name, None)
426        .await
427        .map_err(|e| DockerError::Container(format!("Failed to inspect container {name}: {e}")))?;
428
429    let port_bindings = info
430        .host_config
431        .and_then(|hc| hc.port_bindings)
432        .unwrap_or_default();
433
434    // Extract opencode port (3000/tcp -> host port)
435    let opencode_port = port_bindings
436        .get("3000/tcp")
437        .and_then(|bindings| bindings.as_ref())
438        .and_then(|bindings| bindings.first())
439        .and_then(|binding| binding.host_port.as_ref())
440        .and_then(|port_str| port_str.parse::<u16>().ok());
441
442    // Extract cockpit port (9090/tcp -> host port)
443    let cockpit_port = port_bindings
444        .get("9090/tcp")
445        .and_then(|bindings| bindings.as_ref())
446        .and_then(|bindings| bindings.first())
447        .and_then(|binding| binding.host_port.as_ref())
448        .and_then(|port_str| port_str.parse::<u16>().ok());
449
450    Ok(ContainerPorts {
451        opencode_port,
452        cockpit_port,
453    })
454}
455
456/// Get bind mounts from an existing container
457///
458/// Returns only user-defined bind mounts (excludes system mounts like cgroup).
459pub async fn get_container_bind_mounts(
460    client: &DockerClient,
461    name: &str,
462) -> Result<Vec<ContainerBindMount>, DockerError> {
463    debug!("Getting container bind mounts: {}", name);
464
465    let info = client
466        .inner()
467        .inspect_container(name, None)
468        .await
469        .map_err(|e| DockerError::Container(format!("Failed to inspect container {name}: {e}")))?;
470
471    let mounts = info.mounts.unwrap_or_default();
472
473    // Filter to only bind mounts, excluding system paths
474    let bind_mounts: Vec<ContainerBindMount> = mounts
475        .iter()
476        .filter(|m| m.typ == Some(MountPointTypeEnum::BIND))
477        .filter(|m| {
478            // Exclude system mounts (cgroup, etc.)
479            let target = m.destination.as_deref().unwrap_or("");
480            !target.starts_with("/sys/")
481        })
482        .map(|m| ContainerBindMount {
483            source: m.source.clone().unwrap_or_default(),
484            target: m.destination.clone().unwrap_or_default(),
485            read_only: m.rw.map(|rw| !rw).unwrap_or(false),
486        })
487        .collect();
488
489    Ok(bind_mounts)
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495
496    #[test]
497    fn container_constants_are_correct() {
498        assert_eq!(CONTAINER_NAME, "opencode-cloud-sandbox");
499        assert_eq!(OPENCODE_WEB_PORT, 3000);
500    }
501
502    #[test]
503    fn default_image_format() {
504        let expected = format!("{IMAGE_NAME_GHCR}:{IMAGE_TAG_DEFAULT}");
505        assert_eq!(expected, "ghcr.io/prizz/opencode-cloud-sandbox:latest");
506    }
507}