Skip to main content

opencode_cloud_core/docker/
mod.rs

1//! Docker operations module
2//!
3//! This module provides Docker container management functionality including:
4//! - Docker client wrapper with connection handling
5//! - Docker-specific error types
6//! - Embedded Dockerfile for building the opencode image
7//! - Progress reporting for build and pull operations
8//! - Image build and pull operations
9//! - Volume management for persistent storage
10//! - Container lifecycle (create, start, stop, remove)
11//! - Container exec for running commands inside containers
12//! - User management operations (create, delete, lock/unlock users)
13//! - Image update and rollback operations
14
15mod assets;
16mod client;
17pub mod container;
18mod dockerfile;
19mod error;
20pub mod exec;
21mod health;
22pub mod image;
23pub mod mount;
24pub mod profile;
25pub mod progress;
26mod registry;
27pub mod state;
28pub mod update;
29pub mod users;
30mod version;
31pub mod volume;
32
33// Core types
34pub use client::{DockerClient, DockerEndpoint};
35pub use error::DockerError;
36pub use progress::ProgressReporter;
37
38// Health check operations
39pub use health::{
40    ExtendedHealthResponse, HealthError, HealthResponse, check_health, check_health_extended,
41};
42
43// Dockerfile constants
44pub use assets::{ENTRYPOINT_SH, HEALTHCHECK_SH, OPENCODE_CLOUD_BOOTSTRAP_SH};
45pub use dockerfile::{DOCKERFILE, IMAGE_NAME_DOCKERHUB, IMAGE_NAME_GHCR, IMAGE_TAG_DEFAULT};
46
47// Image operations
48pub use image::{build_image, image_exists, pull_image, remove_images_by_name};
49pub use profile::{
50    DockerResourceNames, INSTANCE_LABEL_KEY, SANDBOX_INSTANCE_ENV, active_resource_names,
51    env_instance_id, remap_container_name, remap_image_tag, resource_names_for_instance,
52};
53
54// Update operations
55pub use update::{UpdateResult, has_previous_image, rollback_image, update_image};
56
57// Version detection
58pub use version::{
59    VERSION_LABEL, get_cli_version, get_image_version, get_registry_latest_version,
60    versions_compatible,
61};
62
63// Container exec operations
64pub use exec::{
65    exec_command, exec_command_exit_code, exec_command_with_status, exec_command_with_stdin,
66};
67
68// User management operations
69pub use users::{
70    UserInfo, create_user, delete_user, list_users, lock_user, persist_user, remove_persisted_user,
71    restore_persisted_users, set_user_password, unlock_user, user_exists,
72};
73
74// Volume management
75pub use volume::{
76    MOUNT_CACHE, MOUNT_CONFIG, MOUNT_PROJECTS, MOUNT_SESSION, MOUNT_STATE, MOUNT_USERS,
77    VOLUME_CACHE, VOLUME_CONFIG, VOLUME_NAMES, VOLUME_PROJECTS, VOLUME_SESSION, VOLUME_STATE,
78    VOLUME_USERS, ensure_volumes_exist, remove_all_volumes, remove_volume, volume_exists,
79};
80
81/// Determine whether the Docker host supports systemd-in-container.
82///
83/// Returns true only for Linux hosts that are not Docker Desktop and not rootless.
84pub async fn docker_supports_systemd(client: &DockerClient) -> Result<bool, DockerError> {
85    let info = client.inner().info().await.map_err(DockerError::from)?;
86
87    let os_type = info.os_type.unwrap_or_default();
88    if os_type.to_lowercase() != "linux" {
89        return Ok(false);
90    }
91
92    let operating_system = match info.operating_system {
93        Some(value) => value,
94        None => return Ok(false),
95    };
96    if operating_system.to_lowercase().contains("docker desktop") {
97        return Ok(false);
98    }
99
100    let security_options = match info.security_options {
101        Some(options) => options,
102        None => return Ok(false),
103    };
104    let is_rootless = security_options
105        .iter()
106        .any(|opt| opt.to_lowercase().contains("name=rootless"));
107    if is_rootless {
108        return Ok(false);
109    }
110
111    Ok(true)
112}
113
114// Bind mount parsing and validation
115pub use mount::{MountError, ParsedMount, check_container_path_warning, validate_mount_path};
116
117// Container lifecycle
118pub use container::{
119    CONTAINER_NAME, ContainerBindMount, ContainerPorts, OPENCODE_WEB_PORT, container_exists,
120    container_is_running, container_state, create_container, get_container_bind_mounts,
121    get_container_ports, remove_container, start_container, stop_container,
122};
123
124// Image state tracking
125pub use state::{ImageState, clear_state, get_state_path, load_state, save_state};
126
127/// Full setup: ensure volumes exist, create container if needed, start it
128///
129/// This is the primary entry point for starting the opencode service.
130/// Returns the container ID on success.
131///
132/// # Arguments
133/// * `client` - Docker client
134/// * `opencode_web_port` - Port to bind on host for opencode web UI (defaults to OPENCODE_WEB_PORT)
135/// * `env_vars` - Additional environment variables (optional)
136/// * `bind_address` - IP address to bind on host (defaults to "127.0.0.1")
137/// * `cockpit_port` - Port to bind on host for Cockpit (defaults to 9090)
138/// * `cockpit_enabled` - Whether to enable Cockpit port mapping (defaults to false)
139/// * `systemd_enabled` - Whether to use systemd as init (defaults to false)
140/// * `bind_mounts` - User-defined bind mounts from config and CLI flags (optional)
141#[allow(clippy::too_many_arguments)]
142pub async fn setup_and_start(
143    client: &DockerClient,
144    opencode_web_port: Option<u16>,
145    env_vars: Option<Vec<String>>,
146    bind_address: Option<&str>,
147    cockpit_port: Option<u16>,
148    cockpit_enabled: Option<bool>,
149    systemd_enabled: Option<bool>,
150    bind_mounts: Option<Vec<mount::ParsedMount>>,
151) -> Result<String, DockerError> {
152    let names = active_resource_names();
153
154    // Ensure volumes exist first
155    volume::ensure_volumes_exist(client).await?;
156
157    // Check if container already exists
158    let container_id = if container::container_exists(client, &names.container_name).await? {
159        // Get existing container ID
160        let info = client
161            .inner()
162            .inspect_container(&names.container_name, None)
163            .await
164            .map_err(|e| {
165                DockerError::Container(format!("Failed to inspect existing container: {e}"))
166            })?;
167        info.id.unwrap_or_else(|| names.container_name.to_string())
168    } else {
169        // Create new container
170        container::create_container(
171            client,
172            None,
173            None,
174            opencode_web_port,
175            env_vars,
176            bind_address,
177            cockpit_port,
178            cockpit_enabled,
179            systemd_enabled,
180            bind_mounts,
181        )
182        .await?
183    };
184
185    // Start if not running
186    if !container::container_is_running(client, &names.container_name).await? {
187        container::start_container(client, &names.container_name).await?;
188    }
189
190    // Restore persisted users after the container is running
191    users::restore_persisted_users(client, &names.container_name).await?;
192
193    Ok(container_id)
194}
195
196/// Default graceful shutdown timeout in seconds
197pub const DEFAULT_STOP_TIMEOUT_SECS: i64 = 30;
198
199/// Stop and optionally remove the opencode container
200///
201/// # Arguments
202/// * `client` - Docker client
203/// * `remove` - Also remove the container after stopping
204/// * `timeout_secs` - Graceful shutdown timeout (default: 30 seconds)
205pub async fn stop_service(
206    client: &DockerClient,
207    remove: bool,
208    timeout_secs: Option<i64>,
209) -> Result<(), DockerError> {
210    let names = active_resource_names();
211    let name = names.container_name.as_str();
212    let timeout = timeout_secs.unwrap_or(DEFAULT_STOP_TIMEOUT_SECS);
213
214    // Check if container exists
215    if !container::container_exists(client, name).await? {
216        return Err(DockerError::Container(format!(
217            "Container '{name}' does not exist"
218        )));
219    }
220
221    // Stop if running
222    if container::container_is_running(client, name).await? {
223        container::stop_container(client, name, Some(timeout)).await?;
224    }
225
226    // Remove if requested
227    if remove {
228        container::remove_container(client, name, false).await?;
229    }
230
231    Ok(())
232}