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