devrig 0.30.0

Local development orchestrator
Documentation
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
use anyhow::{bail, Result};
use chrono::Utc;
use std::collections::BTreeMap;
use std::path::Path;
use std::time::SystemTime;
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
use tracing::debug;

use crate::config::model::{ClusterDeployConfig, ClusterImageConfig};
use crate::orchestrator::state::ClusterDeployState;

/// Run a subprocess command with optional working directory and environment variable,
/// racing the process against the cancellation token.
async fn run_cmd(
    cmd: &str,
    args: &[&str],
    working_dir: Option<&Path>,
    env: Option<(&str, &Path)>,
    cancel: &CancellationToken,
) -> Result<()> {
    let mut command = Command::new(cmd);
    command.args(args);

    if let Some(dir) = working_dir {
        command.current_dir(dir);
    }

    if let Some((key, value)) = env {
        command.env(key, value);
    }

    let child = command.output();

    let output = tokio::select! {
        result = child => result?,
        _ = cancel.cancelled() => {
            bail!("cancelled");
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "{} {} failed: {}",
            cmd,
            args.first().unwrap_or(&""),
            stderr.trim()
        );
    }

    Ok(())
}

use crate::platform;

/// Build docker build args including `--secret` and `--build-arg` flags.
/// When `no_cache` is true, adds `--no-cache` for a completely fresh build.
fn docker_build_args<'a>(
    tag: &'a str,
    dockerfile: &'a str,
    secret_args: &'a [String],
    build_args: &'a [String],
    no_cache: bool,
) -> Vec<&'a str> {
    let mut args = vec!["build", "-t", tag, "-f", dockerfile];
    if no_cache {
        args.push("--no-cache");
    }
    for secret_arg in secret_args {
        args.push("--secret");
        args.push(secret_arg);
    }
    for build_arg in build_args {
        args.push("--build-arg");
        args.push(build_arg);
    }
    args.push(".");
    args
}

/// Format build_secrets into `--secret` arg values: `id=<key>,src=<expanded_path>`.
fn format_secret_args(build_secrets: &BTreeMap<String, String>) -> Vec<String> {
    build_secrets
        .iter()
        .map(|(id, path)| format!("id={id},src={}", platform::expand_home(path)))
        .collect()
}

/// Format build_args into `key=value` strings, interpolating `{{ cluster.image.<name>.tag }}`
/// references using already-built image tags from `deployed`.
fn format_build_args(
    build_args: &BTreeMap<String, String>,
    deployed: &BTreeMap<String, ClusterDeployState>,
) -> Vec<String> {
    build_args
        .iter()
        .map(|(key, value)| {
            let interpolated = interpolate_image_refs(value, deployed);
            format!("{key}={interpolated}")
        })
        .collect()
}

/// Replace `{{ cluster.image.<name>.tag }}` patterns in a string with actual image tags.
fn interpolate_image_refs(value: &str, deployed: &BTreeMap<String, ClusterDeployState>) -> String {
    let mut result = value.to_string();
    for (name, state) in deployed {
        let pattern = format!("{{{{ cluster.image.{name}.tag }}}}");
        result = result.replace(&pattern, &state.image_tag);
    }
    result
}

/// Build, push (if registry is available), and apply manifests for a cluster deploy entry.
/// Returns the deploy state with the image tag and timestamp.
pub async fn run_deploy(
    name: &str,
    deploy_config: &ClusterDeployConfig,
    registry_port: Option<u16>,
    kubeconfig_path: &Path,
    config_dir: &Path,
    cancel: &CancellationToken,
) -> Result<ClusterDeployState> {
    let context_path = config_dir.join(&deploy_config.context);
    let manifests_path = config_dir.join(&deploy_config.manifests);

    // Build the image tag
    let tag = if let Some(port) = registry_port {
        let timestamp = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)?
            .as_secs();
        format!("localhost:{port}/{name}:{timestamp}")
    } else {
        format!("devrig-{name}:latest")
    };

    // Docker build
    debug!(name, tag, "building image");
    let secret_args = format_secret_args(&deploy_config.build_secrets);
    let args = docker_build_args(&tag, &deploy_config.dockerfile, &secret_args, &[], false);
    run_cmd("docker", &args, Some(&context_path), None, cancel).await?;

    if cancel.is_cancelled() {
        bail!("cancelled");
    }

    // Docker push (only when registry is available)
    if registry_port.is_some() {
        debug!(name, tag, "pushing image");
        run_cmd("docker", &["push", &tag], None, None, cancel).await?;

        if cancel.is_cancelled() {
            bail!("cancelled");
        }
    }

    // kubectl apply
    let manifests_str = manifests_path.to_string_lossy();
    debug!(name, manifests = %manifests_str, "applying manifests");
    run_cmd(
        "kubectl",
        &["apply", "-f", &manifests_str],
        None,
        Some(("KUBECONFIG", kubeconfig_path)),
        cancel,
    )
    .await?;

    Ok(ClusterDeployState {
        image_tag: tag,
        last_deployed: Utc::now(),
    })
}

/// Rebuild: same as run_deploy but also restarts the deployment to pick up the new image.
pub async fn run_rebuild(
    name: &str,
    deploy_config: &ClusterDeployConfig,
    registry_port: Option<u16>,
    kubeconfig_path: &Path,
    config_dir: &Path,
    cancel: &CancellationToken,
) -> Result<()> {
    let context_path = config_dir.join(&deploy_config.context);
    let manifests_path = config_dir.join(&deploy_config.manifests);

    // Build the image tag
    let tag = if let Some(port) = registry_port {
        let timestamp = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)?
            .as_secs();
        format!("localhost:{port}/{name}:{timestamp}")
    } else {
        format!("devrig-{name}:latest")
    };

    // Docker build
    debug!(name, tag, "rebuilding image");
    let secret_args = format_secret_args(&deploy_config.build_secrets);
    let args = docker_build_args(&tag, &deploy_config.dockerfile, &secret_args, &[], false);
    run_cmd("docker", &args, Some(&context_path), None, cancel).await?;

    if cancel.is_cancelled() {
        bail!("cancelled");
    }

    // Docker push (only when registry is available)
    if registry_port.is_some() {
        debug!(name, tag, "pushing image");
        run_cmd("docker", &["push", &tag], None, None, cancel).await?;

        if cancel.is_cancelled() {
            bail!("cancelled");
        }
    }

    // kubectl apply
    let manifests_str = manifests_path.to_string_lossy();
    debug!(name, manifests = %manifests_str, "applying manifests");
    run_cmd(
        "kubectl",
        &["apply", "-f", &manifests_str],
        None,
        Some(("KUBECONFIG", kubeconfig_path)),
        cancel,
    )
    .await?;

    if cancel.is_cancelled() {
        bail!("cancelled");
    }

    // Rollout restart to pick up the new image
    let deployment = format!("deployment/{name}");
    debug!(name, "restarting deployment");
    run_cmd(
        "kubectl",
        &["rollout", "restart", &deployment],
        None,
        Some(("KUBECONFIG", kubeconfig_path)),
        cancel,
    )
    .await?;

    Ok(())
}

/// Build and push an image to the registry without applying any manifests.
/// Used for `[cluster.image.*]` entries that only need the image available.
pub async fn run_image_build(
    name: &str,
    image_config: &ClusterImageConfig,
    registry_port: Option<u16>,
    config_dir: &Path,
    deployed: &BTreeMap<String, ClusterDeployState>,
    cancel: &CancellationToken,
) -> Result<ClusterDeployState> {
    let context_path = config_dir.join(&image_config.context);

    // Build the image tag
    let tag = if let Some(port) = registry_port {
        let timestamp = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)?
            .as_secs();
        format!("localhost:{port}/{name}:{timestamp}")
    } else {
        format!("devrig-{name}:latest")
    };

    // Docker build
    debug!(name, tag, "building image");
    let secret_args = format_secret_args(&image_config.build_secrets);
    let build_args = format_build_args(&image_config.build_args, deployed);
    let args = docker_build_args(&tag, &image_config.dockerfile, &secret_args, &build_args, false);
    run_cmd("docker", &args, Some(&context_path), None, cancel).await?;

    if cancel.is_cancelled() {
        bail!("cancelled");
    }

    // Docker push (only when registry is available)
    if let Some(port) = registry_port {
        debug!(name, tag, "pushing image");
        run_cmd("docker", &["push", &tag], None, None, cancel).await?;

        // Also tag and push as :latest for stable references
        let latest_tag = format!("localhost:{port}/{name}:latest");
        run_cmd("docker", &["tag", &tag, &latest_tag], None, None, cancel).await?;
        run_cmd("docker", &["push", &latest_tag], None, None, cancel).await?;
    }

    Ok(ClusterDeployState {
        image_tag: tag,
        last_deployed: Utc::now(),
    })
}

/// Rebuild an image and push it (no manifests, no rollout restart).
/// Used by the watcher for `[cluster.image.*]` entries with `watch = true`.
pub async fn rebuild_image(
    name: &str,
    image_config: &ClusterImageConfig,
    registry_port: Option<u16>,
    config_dir: &Path,
    deployed: &BTreeMap<String, ClusterDeployState>,
    cancel: &CancellationToken,
) -> Result<()> {
    let context_path = config_dir.join(&image_config.context);

    // Build the image tag
    let tag = if let Some(port) = registry_port {
        let timestamp = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)?
            .as_secs();
        format!("localhost:{port}/{name}:{timestamp}")
    } else {
        format!("devrig-{name}:latest")
    };

    // Docker build
    debug!(name, tag, "rebuilding image");
    let secret_args = format_secret_args(&image_config.build_secrets);
    let build_args = format_build_args(&image_config.build_args, deployed);
    let args = docker_build_args(&tag, &image_config.dockerfile, &secret_args, &build_args, false);
    run_cmd("docker", &args, Some(&context_path), None, cancel).await?;

    if cancel.is_cancelled() {
        bail!("cancelled");
    }

    // Docker push (only when registry is available)
    if let Some(port) = registry_port {
        debug!(name, tag, "pushing image");
        run_cmd("docker", &["push", &tag], None, None, cancel).await?;

        // Also tag and push as :latest for stable references
        let latest_tag = format!("localhost:{port}/{name}:latest");
        run_cmd("docker", &["tag", &tag, &latest_tag], None, None, cancel).await?;
        run_cmd("docker", &["push", &latest_tag], None, None, cancel).await?;
    }

    Ok(())
}

/// Build and push an image with --no-cache for a completely fresh build.
/// Used by `devrig cluster rebuild` for `[cluster.image.*]` entries.
pub async fn fresh_rebuild_image(
    name: &str,
    image_config: &ClusterImageConfig,
    registry_port: u16,
    config_dir: &Path,
    deployed: &BTreeMap<String, ClusterDeployState>,
    cancel: &CancellationToken,
) -> Result<ClusterDeployState> {
    let context_path = config_dir.join(&image_config.context);

    let timestamp = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)?
        .as_secs();
    let tag = format!("localhost:{registry_port}/{name}:{timestamp}");

    // Docker build with --no-cache
    println!("  Building image '{name}' (--no-cache)...");
    debug!(name, tag, "fresh building image with --no-cache");
    let secret_args = format_secret_args(&image_config.build_secrets);
    let build_args = format_build_args(&image_config.build_args, deployed);
    let args = docker_build_args(&tag, &image_config.dockerfile, &secret_args, &build_args, true);
    run_cmd("docker", &args, Some(&context_path), None, cancel).await?;

    if cancel.is_cancelled() {
        bail!("cancelled");
    }

    // Push timestamped tag
    debug!(name, tag, "pushing image");
    run_cmd("docker", &["push", &tag], None, None, cancel).await?;

    // Also tag and push as :latest
    let latest_tag = format!("localhost:{registry_port}/{name}:latest");
    run_cmd("docker", &["tag", &tag, &latest_tag], None, None, cancel).await?;
    run_cmd("docker", &["push", &latest_tag], None, None, cancel).await?;

    println!("  Pushed '{name}' -> {tag}");

    Ok(ClusterDeployState {
        image_tag: tag,
        last_deployed: Utc::now(),
    })
}

/// Build, push (with --no-cache), and optionally apply manifests + rollout restart
/// for a `[cluster.deploy.*]` entry. Used by `devrig cluster rebuild`.
pub async fn fresh_rebuild_deploy(
    name: &str,
    deploy_config: &ClusterDeployConfig,
    registry_port: u16,
    kubeconfig_path: &Path,
    config_dir: &Path,
    apply_manifests: bool,
    cancel: &CancellationToken,
) -> Result<ClusterDeployState> {
    let context_path = config_dir.join(&deploy_config.context);
    let manifests_path = config_dir.join(&deploy_config.manifests);

    let timestamp = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)?
        .as_secs();
    let tag = format!("localhost:{registry_port}/{name}:{timestamp}");

    // Docker build with --no-cache
    println!("  Building deploy '{name}' (--no-cache)...");
    debug!(name, tag, "fresh building deploy image with --no-cache");
    let secret_args = format_secret_args(&deploy_config.build_secrets);
    let args = docker_build_args(&tag, &deploy_config.dockerfile, &secret_args, &[], true);
    run_cmd("docker", &args, Some(&context_path), None, cancel).await?;

    if cancel.is_cancelled() {
        bail!("cancelled");
    }

    // Push timestamped tag
    debug!(name, tag, "pushing image");
    run_cmd("docker", &["push", &tag], None, None, cancel).await?;

    // Also tag and push as :latest
    let latest_tag = format!("localhost:{registry_port}/{name}:latest");
    run_cmd("docker", &["tag", &tag, &latest_tag], None, None, cancel).await?;
    run_cmd("docker", &["push", &latest_tag], None, None, cancel).await?;

    println!("  Pushed '{name}' -> {tag}");

    if apply_manifests {
        // kubectl apply
        let manifests_str = manifests_path.to_string_lossy();
        debug!(name, manifests = %manifests_str, "applying manifests");
        run_cmd(
            "kubectl",
            &["apply", "-f", &manifests_str],
            None,
            Some(("KUBECONFIG", kubeconfig_path)),
            cancel,
        )
        .await?;

        if cancel.is_cancelled() {
            bail!("cancelled");
        }

        // Rollout restart
        let deployment = format!("deployment/{name}");
        debug!(name, "restarting deployment");
        run_cmd(
            "kubectl",
            &["rollout", "restart", &deployment],
            None,
            Some(("KUBECONFIG", kubeconfig_path)),
            cancel,
        )
        .await?;

        println!("  Applied manifests and restarted deployment '{name}'");
    }

    Ok(ClusterDeployState {
        image_tag: tag,
        last_deployed: Utc::now(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;

    #[test]
    fn interpolate_image_refs_replaces_tags() {
        let mut deployed = BTreeMap::new();
        deployed.insert(
            "bloom".to_string(),
            ClusterDeployState {
                image_tag: "localhost:12345/bloom:1700000000".to_string(),
                last_deployed: Utc::now(),
            },
        );

        let result =
            interpolate_image_refs("{{ cluster.image.bloom.tag }}", &deployed);
        assert_eq!(result, "localhost:12345/bloom:1700000000");
    }

    #[test]
    fn interpolate_image_refs_no_match_unchanged() {
        let deployed = BTreeMap::new();
        let result = interpolate_image_refs("some-static-value", &deployed);
        assert_eq!(result, "some-static-value");
    }

    #[test]
    fn format_build_args_interpolates_and_formats() {
        let mut build_args = BTreeMap::new();
        build_args.insert(
            "SERVER_IMAGE".to_string(),
            "{{ cluster.image.bloom.tag }}".to_string(),
        );
        build_args.insert("STATIC_ARG".to_string(), "hello".to_string());

        let mut deployed = BTreeMap::new();
        deployed.insert(
            "bloom".to_string(),
            ClusterDeployState {
                image_tag: "localhost:5000/bloom:123".to_string(),
                last_deployed: Utc::now(),
            },
        );

        let result = format_build_args(&build_args, &deployed);
        assert!(result.contains(&"SERVER_IMAGE=localhost:5000/bloom:123".to_string()));
        assert!(result.contains(&"STATIC_ARG=hello".to_string()));
    }

    #[test]
    fn docker_build_args_includes_build_args() {
        let build_args = vec!["SERVER_IMAGE=foo:latest".to_string()];
        let args = docker_build_args("tag:1", "Dockerfile", &[], &build_args, false);
        assert!(args.contains(&"--build-arg"));
        assert!(args.contains(&"SERVER_IMAGE=foo:latest"));
        assert!(!args.contains(&"--no-cache"));
    }

    #[test]
    fn docker_build_args_includes_no_cache() {
        let args = docker_build_args("tag:1", "Dockerfile", &[], &[], true);
        assert!(args.contains(&"--no-cache"));
    }
}