rise-deploy 0.15.10

A simple and powerful CLI for deploying containerized applications
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
// BuildKit daemon lifecycle management

use anyhow::{bail, Context, Result};
use sha2::{Digest, Sha256};
use std::fs;
use std::path::Path;
use std::process::Command;
use tracing::{debug, info, warn};

use crate::config::{ContainerCli, ContainerRuntime};

use super::method::{requires_buildkit, BuildMethod};

/// Compute SHA256 hash of a file
pub(crate) fn compute_file_hash(path: &Path) -> Result<String> {
    let contents = fs::read(path).context("Failed to read certificate file")?;
    let mut hasher = Sha256::new();
    hasher.update(&contents);
    let result = hasher.finalize();
    Ok(format!("{:x}", result))
}

/// Compute SHA256 hash of a string
fn compute_string_hash(content: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(content.as_bytes());
    let result = hasher.finalize();
    format!("{:x}", result)
}

/// Generate buildkitd.toml configuration for insecure registries
/// Returns (config_content, config_hash) or None if no insecure registries configured
fn generate_buildkit_config() -> Option<(String, String)> {
    let insecure_registries =
        super::env_var_non_empty("RISE_MANAGED_BUILDKIT_INSECURE_REGISTRIES")?;

    let registries: Vec<&str> = insecure_registries
        .split(',')
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .collect();

    if registries.is_empty() {
        return None;
    }

    let mut config = String::new();
    for registry in registries {
        config.push_str(&format!(
            "[registry.\"{}\"]\n  http = true\n  insecure = true\n\n",
            registry
        ));
    }

    let hash = compute_string_hash(&config);
    Some((config, hash))
}

/// Write buildkitd.toml config to a file and return the path
/// Returns None if no config needed
fn write_buildkit_config() -> Result<Option<std::path::PathBuf>> {
    let Some((config_content, _hash)) = generate_buildkit_config() else {
        return Ok(None);
    };

    // Use ~/.rise/buildkitd.toml for the config file
    let home_dir = dirs::home_dir().context("Failed to determine home directory")?;
    let rise_dir = home_dir.join(".rise");

    // Create .rise directory if it doesn't exist
    fs::create_dir_all(&rise_dir).context("Failed to create .rise directory")?;

    let config_path = rise_dir.join("buildkitd.toml");
    fs::write(&config_path, config_content).context("Failed to write buildkitd.toml")?;

    Ok(Some(config_path))
}

/// Check if a Docker network exists
fn network_exists(container_cli: &str, network_name: &str) -> bool {
    let output = Command::new(container_cli)
        .args(["network", "inspect", network_name])
        .output();

    matches!(output, Ok(output) if output.status.success())
}

/// Create a Docker network if it doesn't exist
fn create_network(container_cli: &str, network_name: &str) -> Result<()> {
    if network_exists(container_cli, network_name) {
        debug!("Network '{}' already exists", network_name);
        return Ok(());
    }

    info!("Creating Docker network '{}'", network_name);
    let status = Command::new(container_cli)
        .args(["network", "create", network_name])
        .status()
        .context("Failed to create network")?;

    if !status.success() {
        bail!("Failed to create network '{}'", network_name);
    }

    info!("Network '{}' created successfully", network_name);
    Ok(())
}

/// Connect a container to a Docker network
fn connect_to_network(container_cli: &str, network_name: &str, container_name: &str) -> Result<()> {
    info!(
        "Connecting container '{}' to network '{}'",
        container_name, network_name
    );

    let status = Command::new(container_cli)
        .args(["network", "connect", network_name, container_name])
        .status()
        .context("Failed to connect to network")?;

    if !status.success() {
        bail!(
            "Failed to connect container '{}' to network '{}'",
            container_name,
            network_name
        );
    }

    info!(
        "Container '{}' connected to network '{}' successfully",
        container_name, network_name
    );
    Ok(())
}

/// Get network label from container
fn get_network_label_from_container(container_cli: &str, daemon_name: &str) -> Option<String> {
    let output = Command::new(container_cli)
        .args([
            "inspect",
            "--format",
            "{{index .Config.Labels \"rise.network_name\"}}",
            daemon_name,
        ])
        .output()
        .ok()?;

    if output.status.success() {
        let label_value = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if !label_value.is_empty() && label_value != "<no value>" {
            return Some(label_value);
        }
    }

    None
}

/// Get config hash label from container
fn get_config_hash_label_from_container(container_cli: &str, daemon_name: &str) -> Option<String> {
    let output = Command::new(container_cli)
        .args([
            "inspect",
            "--format",
            "{{index .Config.Labels \"rise.config_hash\"}}",
            daemon_name,
        ])
        .output()
        .ok()?;

    if output.status.success() {
        let label_value = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if !label_value.is_empty() && label_value != "<no value>" {
            return Some(label_value);
        }
    }

    None
}

/// Represents the state of a BuildKit daemon
#[derive(Debug, PartialEq)]
enum DaemonState {
    /// Daemon has an SSL certificate with the given hash, optional network, and optional config hash
    HasCert(String, Option<String>, Option<String>),
    /// Daemon was created without an SSL certificate, with optional network and optional config hash
    NoCert(Option<String>, Option<String>),
    /// Daemon does not exist
    NotFound,
}

/// Get the current state of the BuildKit daemon
fn get_daemon_state(container_cli: &str, daemon_name: &str) -> DaemonState {
    // Check if daemon exists
    let inspect_status = Command::new(container_cli)
        .args(["inspect", daemon_name])
        .output();

    let Ok(output) = inspect_status else {
        return DaemonState::NotFound;
    };

    if !output.status.success() {
        return DaemonState::NotFound;
    }

    // Get network label if present
    let network_name = get_network_label_from_container(container_cli, daemon_name);

    // Get config hash label if present
    let config_hash = get_config_hash_label_from_container(container_cli, daemon_name);

    // Daemon exists, check for no_ssl_cert label
    let no_cert_output = Command::new(container_cli)
        .args([
            "inspect",
            "--format",
            "{{index .Config.Labels \"rise.no_ssl_cert\"}}",
            daemon_name,
        ])
        .output();

    if let Ok(output) = no_cert_output {
        if output.status.success() {
            let label_value = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if label_value == "true" {
                return DaemonState::NoCert(network_name, config_hash);
            }
        }
    }

    // Check for SSL cert hash label
    let cert_hash_output = Command::new(container_cli)
        .args([
            "inspect",
            "--format",
            "{{index .Config.Labels \"rise.ssl_cert_hash\"}}",
            daemon_name,
        ])
        .output();

    if let Ok(output) = cert_hash_output {
        if output.status.success() {
            let cert_hash = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if !cert_hash.is_empty() {
                return DaemonState::HasCert(cert_hash, network_name, config_hash);
            }
        }
    }

    // Daemon exists but has no labels (old daemon or created externally)
    // Treat as NoCert to avoid assuming anything
    DaemonState::NoCert(network_name, config_hash)
}

/// Stop and remove BuildKit daemon.
///
/// Uses `rm -f` instead of `stop` because Podman does not always clean up
/// `--rm` containers reliably on `stop`, leaving the container name in use.
/// `rm -f` works correctly on both Docker and Podman.
fn stop_buildkit_daemon(container_cli: &ContainerCli, daemon_name: &str) -> Result<()> {
    info!("Stopping existing BuildKit daemon '{}'", daemon_name);

    let status = Command::new(container_cli.command())
        .args(["rm", "-f", daemon_name])
        .status()
        .context("Failed to remove BuildKit daemon")?;

    if !status.success() {
        bail!("Failed to remove BuildKit daemon");
    }

    Ok(())
}

/// Create BuildKit daemon with optional SSL certificate mounted and network connection
/// Returns the BUILDKIT_HOST value to be used with this daemon
fn create_buildkit_daemon(
    container_cli: &ContainerCli,
    daemon_name: &str,
    ssl_cert_file: Option<&Path>,
    network_name: Option<&str>,
) -> Result<String> {
    if let Some(cert_path) = ssl_cert_file {
        info!(
            "Creating managed BuildKit daemon '{}' with SSL certificate: {}",
            daemon_name,
            cert_path.display()
        );
    } else {
        info!(
            "Creating managed BuildKit daemon '{}' without SSL certificate",
            daemon_name
        );
    }

    if let Some(network) = network_name {
        info!("BuildKit daemon will be connected to network '{}'", network);
    }

    let mut cmd = Command::new(container_cli.command());
    cmd.args([
        "run",
        "--privileged",
        "--name",
        daemon_name,
        "--rm",
        "-d",
        "--add-host",
        "host.docker.internal:host-gateway",
    ]);

    // Podman with cgroup v2 does not delegate the memory controller to containers
    // by default, which causes runc (used internally by BuildKit) to fail with:
    //   "can't get final child's PID from pipe: EOF"
    // Using --cgroupns=host lets BuildKit access the host cgroup hierarchy directly.
    if container_cli.runtime() == ContainerRuntime::Podman {
        debug!("Podman detected, adding --cgroupns=host for cgroup v2 compatibility");
        cmd.arg("--cgroupns=host");
    }

    // Add labels and volume mount based on SSL cert presence
    if let Some(cert_path) = ssl_cert_file {
        // Resolve certificate path to absolute path
        let cert_path_abs = if cert_path.is_absolute() {
            cert_path.to_path_buf()
        } else {
            std::env::current_dir()?.join(cert_path)
        };

        let cert_path_abs = cert_path_abs
            .canonicalize()
            .context("Failed to resolve SSL certificate path")?;

        let cert_str = cert_path_abs
            .to_str()
            .context("SSL certificate path contains invalid UTF-8")?;

        // Compute hash of certificate file
        let cert_hash = compute_file_hash(&cert_path_abs)?;

        cmd.arg("--label")
            .arg(format!("rise.ssl_cert_file={}", cert_str))
            .arg("--label")
            .arg(format!("rise.ssl_cert_hash={}", cert_hash))
            .arg("--volume")
            .arg(format!(
                "{}:/etc/ssl/certs/ca-certificates.crt:ro",
                cert_str
            ));
    } else {
        // No SSL cert, add label to track this state
        cmd.arg("--label").arg("rise.no_ssl_cert=true");
    }

    // Add network label if network is specified
    if let Some(network) = network_name {
        cmd.arg("--label")
            .arg(format!("rise.network_name={}", network));
    }

    // Write and mount buildkitd.toml config if insecure registries are configured
    if let Some((_config_content, config_hash)) = generate_buildkit_config() {
        let config_path = write_buildkit_config()?;

        if let Some(config_file) = config_path {
            let config_str = config_file
                .to_str()
                .context("Config file path contains invalid UTF-8")?;

            info!(
                "Mounting BuildKit config with insecure registries: {}",
                config_str
            );

            cmd.arg("--label")
                .arg(format!("rise.config_hash={}", config_hash))
                .arg("--volume")
                .arg(format!("{}:/etc/buildkit/buildkitd.toml:ro", config_str));
        }
    }

    cmd.arg("moby/buildkit");

    let status = cmd.status().context("Failed to start BuildKit daemon")?;

    if !status.success() {
        bail!("Failed to create BuildKit daemon");
    }

    info!("BuildKit daemon '{}' created successfully", daemon_name);

    // Connect to network if specified
    if let Some(network) = network_name {
        create_network(container_cli.command(), network)?;
        connect_to_network(container_cli.command(), network, daemon_name)?;
    }

    // Return BUILDKIT_HOST value for this daemon
    Ok(format!("docker-container://{}", daemon_name))
}

/// Ensure managed BuildKit daemon is running with correct SSL certificate, network, and config
/// Returns the BUILDKIT_HOST value to be used with this daemon
pub(crate) fn ensure_managed_buildkit_daemon(
    ssl_cert_file: Option<&Path>,
    container_cli: &ContainerCli,
) -> Result<String> {
    let daemon_name = "rise-buildkit";

    // Read network configuration from environment
    let network_name = super::env_var_non_empty("RISE_MANAGED_BUILDKIT_NETWORK_NAME");

    // Get expected config hash (None if no insecure registries configured)
    let expected_config_hash = generate_buildkit_config().map(|(_, hash)| hash);

    // Get current daemon state
    let current_state = get_daemon_state(container_cli.command(), daemon_name);

    match (ssl_cert_file, &current_state) {
        // Certificate provided, daemon has matching cert
        (Some(cert_path), DaemonState::HasCert(current_hash, current_network, current_config)) => {
            // Verify hash matches
            let cert_path_abs = cert_path
                .canonicalize()
                .context("Failed to resolve SSL certificate path")?;
            let expected_hash = compute_file_hash(&cert_path_abs)?;

            // Check if network has changed
            let network_changed = &network_name != current_network;

            // Check if config has changed
            let config_changed = &expected_config_hash != current_config;

            if current_hash == &expected_hash && !network_changed && !config_changed {
                debug!(
                    "BuildKit daemon is up-to-date with current SSL_CERT_FILE, network, and config"
                );
                return Ok(format!("docker-container://{}", daemon_name));
            }

            if current_hash != &expected_hash {
                info!("SSL certificate has changed (hash mismatch), recreating daemon");
            } else if network_changed {
                info!("Network configuration has changed, recreating daemon");
            } else if config_changed {
                info!("BuildKit config has changed (insecure registries), recreating daemon");
            }
            stop_buildkit_daemon(container_cli, daemon_name)?;
        }

        // Certificate provided, but daemon has no cert label
        (Some(_), DaemonState::NoCert(current_network, current_config)) => {
            // Check if network has changed
            let network_changed = &network_name != current_network;

            // Check if config has changed
            let config_changed = &expected_config_hash != current_config;

            if network_changed {
                info!("Network configuration has changed, recreating daemon");
            } else if config_changed {
                info!("BuildKit config has changed, recreating daemon");
            } else {
                info!("SSL certificate now available, recreating daemon with certificate");
            }
            stop_buildkit_daemon(container_cli, daemon_name)?;
        }

        // No certificate, daemon has no cert label (matches)
        (None, DaemonState::NoCert(current_network, current_config)) => {
            // Check if network has changed
            let network_changed = &network_name != current_network;

            // Check if config has changed
            let config_changed = &expected_config_hash != current_config;

            if !network_changed && !config_changed {
                debug!("BuildKit daemon is up-to-date (no SSL certificate)");
                return Ok(format!("docker-container://{}", daemon_name));
            }

            if network_changed {
                info!("Network configuration has changed, recreating daemon");
            } else if config_changed {
                info!("BuildKit config has changed (insecure registries), recreating daemon");
            }
            stop_buildkit_daemon(container_cli, daemon_name)?;
        }

        // No certificate, but daemon has cert (mismatch)
        (None, DaemonState::HasCert(_, current_network, current_config)) => {
            // Check if network has changed
            let network_changed = &network_name != current_network;

            // Check if config has changed
            let config_changed = &expected_config_hash != current_config;

            if network_changed && config_changed {
                info!("SSL certificate removed, network and config changed, recreating daemon");
            } else if network_changed {
                info!("SSL certificate removed and network changed, recreating daemon");
            } else if config_changed {
                info!("SSL certificate removed and config changed, recreating daemon");
            } else {
                info!("SSL certificate removed, recreating daemon without certificate");
            }
            stop_buildkit_daemon(container_cli, daemon_name)?;
        }

        // Daemon doesn't exist
        (_, DaemonState::NotFound) => {
            // Will create new daemon below
        }
    }

    // Create new daemon with or without certificate and return its BUILDKIT_HOST
    create_buildkit_daemon(
        container_cli,
        daemon_name,
        ssl_cert_file,
        network_name.as_deref(),
    )
}

/// Ensure buildx builder exists for the given BuildKit daemon
/// Returns the builder name to use
pub(crate) fn ensure_buildx_builder(container_cli: &str, buildkit_host: &str) -> Result<String> {
    let builder_name = "rise-buildkit";

    // Check if builder already exists
    let inspect_status = Command::new(container_cli)
        .args(["buildx", "inspect", builder_name])
        .output();

    match inspect_status {
        Ok(output) if output.status.success() => {
            // Builder exists, check if it's pointing to the correct endpoint
            let inspect_output = String::from_utf8_lossy(&output.stdout);

            // Check if the buildkit_host appears in the inspect output
            // The output contains lines like "Endpoint: docker-container://rise-buildkit"
            if inspect_output.contains(buildkit_host) {
                debug!(
                    "Buildx builder '{}' already exists with correct endpoint",
                    builder_name
                );
                return Ok(builder_name.to_string());
            }

            // Builder exists but points to wrong endpoint, remove and recreate
            info!(
                "Buildx builder '{}' exists but points to different endpoint, recreating",
                builder_name
            );
            let _ = Command::new(container_cli)
                .args(["buildx", "rm", builder_name])
                .status();
        }
        _ => {
            info!(
                "Creating buildx builder '{}' for BuildKit daemon: {}",
                builder_name, buildkit_host
            );
        }
    }

    // Create new builder pointing to the BuildKit daemon
    let status = Command::new(container_cli)
        .args(["buildx", "create", "--name", builder_name, buildkit_host])
        .status()
        .context("Failed to create buildx builder")?;

    if !status.success() {
        bail!("Failed to create buildx builder '{}'", builder_name);
    }

    info!("Buildx builder '{}' created successfully", builder_name);
    Ok(builder_name.to_string())
}

/// Warn user about SSL certificate issues when managed BuildKit is disabled
pub(crate) fn check_ssl_cert_and_warn(method: &BuildMethod, managed_buildkit: bool) {
    if super::env_var_non_empty("SSL_CERT_FILE").is_some()
        && requires_buildkit(method)
        && !managed_buildkit
    {
        warn!(
            "SSL_CERT_FILE is set but managed BuildKit daemon is disabled. \
             Builds may fail with SSL certificate errors in corporate environments."
        );
        warn!("To enable automatic BuildKit daemon management:");
        warn!("  rise build --managed-buildkit ...");
        warn!("Or set environment variable:");
        warn!("  export RISE_MANAGED_BUILDKIT=true");
    }
}