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 client;
16pub mod container;
17mod dockerfile;
18mod error;
19pub mod exec;
20mod health;
21pub mod image;
22pub mod mount;
23pub mod progress;
24pub mod state;
25pub mod update;
26pub mod users;
27mod version;
28pub mod volume;
29
30// Core types
31pub use client::DockerClient;
32pub use error::DockerError;
33pub use progress::ProgressReporter;
34
35// Health check operations
36pub use health::{
37    ExtendedHealthResponse, HealthError, HealthResponse, check_health, check_health_extended,
38};
39
40// Dockerfile constants
41pub use dockerfile::{DOCKERFILE, IMAGE_NAME_DOCKERHUB, IMAGE_NAME_GHCR, IMAGE_TAG_DEFAULT};
42
43// Image operations
44pub use image::{build_image, image_exists, pull_image};
45
46// Update operations
47pub use update::{UpdateResult, has_previous_image, rollback_image, update_image};
48
49// Version detection
50pub use version::{VERSION_LABEL, get_cli_version, get_image_version, versions_compatible};
51
52// Container exec operations
53pub use exec::{exec_command, exec_command_exit_code, exec_command_with_stdin};
54
55// User management operations
56pub use users::{
57    UserInfo, create_user, delete_user, list_users, lock_user, persist_user, remove_persisted_user,
58    restore_persisted_users, set_user_password, unlock_user, user_exists,
59};
60
61// Volume management
62pub use volume::{
63    MOUNT_CACHE, MOUNT_CONFIG, MOUNT_PROJECTS, MOUNT_SESSION, MOUNT_STATE, MOUNT_USERS,
64    VOLUME_CACHE, VOLUME_CONFIG, VOLUME_NAMES, VOLUME_PROJECTS, VOLUME_SESSION, VOLUME_STATE,
65    VOLUME_USERS, ensure_volumes_exist, remove_all_volumes, remove_volume, volume_exists,
66};
67
68// Bind mount parsing and validation
69pub use mount::{MountError, ParsedMount, check_container_path_warning, validate_mount_path};
70
71// Container lifecycle
72pub use container::{
73    CONTAINER_NAME, ContainerBindMount, ContainerPorts, OPENCODE_WEB_PORT, container_exists,
74    container_is_running, container_state, create_container, get_container_bind_mounts,
75    get_container_ports, remove_container, start_container, stop_container,
76};
77
78// Image state tracking
79pub use state::{ImageState, clear_state, get_state_path, load_state, save_state};
80
81/// Full setup: ensure volumes exist, create container if needed, start it
82///
83/// This is the primary entry point for starting the opencode service.
84/// Returns the container ID on success.
85///
86/// # Arguments
87/// * `client` - Docker client
88/// * `opencode_web_port` - Port to bind on host for opencode web UI (defaults to OPENCODE_WEB_PORT)
89/// * `env_vars` - Additional environment variables (optional)
90/// * `bind_address` - IP address to bind on host (defaults to "127.0.0.1")
91/// * `cockpit_port` - Port to bind on host for Cockpit (defaults to 9090)
92/// * `cockpit_enabled` - Whether to enable Cockpit port mapping (defaults to true)
93/// * `bind_mounts` - User-defined bind mounts from config and CLI flags (optional)
94pub async fn setup_and_start(
95    client: &DockerClient,
96    opencode_web_port: Option<u16>,
97    env_vars: Option<Vec<String>>,
98    bind_address: Option<&str>,
99    cockpit_port: Option<u16>,
100    cockpit_enabled: Option<bool>,
101    bind_mounts: Option<Vec<mount::ParsedMount>>,
102) -> Result<String, DockerError> {
103    // Ensure volumes exist first
104    volume::ensure_volumes_exist(client).await?;
105
106    // Check if container already exists
107    let container_id = if container::container_exists(client, container::CONTAINER_NAME).await? {
108        // Get existing container ID
109        let info = client
110            .inner()
111            .inspect_container(container::CONTAINER_NAME, None)
112            .await
113            .map_err(|e| {
114                DockerError::Container(format!("Failed to inspect existing container: {e}"))
115            })?;
116        info.id
117            .unwrap_or_else(|| container::CONTAINER_NAME.to_string())
118    } else {
119        // Create new container
120        container::create_container(
121            client,
122            None,
123            None,
124            opencode_web_port,
125            env_vars,
126            bind_address,
127            cockpit_port,
128            cockpit_enabled,
129            bind_mounts,
130        )
131        .await?
132    };
133
134    // Start if not running
135    if !container::container_is_running(client, container::CONTAINER_NAME).await? {
136        container::start_container(client, container::CONTAINER_NAME).await?;
137    }
138
139    // Restore persisted users after the container is running
140    users::restore_persisted_users(client, container::CONTAINER_NAME).await?;
141
142    Ok(container_id)
143}
144
145/// Default graceful shutdown timeout in seconds
146pub const DEFAULT_STOP_TIMEOUT_SECS: i64 = 30;
147
148/// Stop and optionally remove the opencode container
149///
150/// # Arguments
151/// * `client` - Docker client
152/// * `remove` - Also remove the container after stopping
153/// * `timeout_secs` - Graceful shutdown timeout (default: 30 seconds)
154pub async fn stop_service(
155    client: &DockerClient,
156    remove: bool,
157    timeout_secs: Option<i64>,
158) -> Result<(), DockerError> {
159    let name = container::CONTAINER_NAME;
160    let timeout = timeout_secs.unwrap_or(DEFAULT_STOP_TIMEOUT_SECS);
161
162    // Check if container exists
163    if !container::container_exists(client, name).await? {
164        return Err(DockerError::Container(format!(
165            "Container '{name}' does not exist"
166        )));
167    }
168
169    // Stop if running
170    if container::container_is_running(client, name).await? {
171        container::stop_container(client, name, Some(timeout)).await?;
172    }
173
174    // Remove if requested
175    if remove {
176        container::remove_container(client, name, false).await?;
177    }
178
179    Ok(())
180}