dcd 0.1.9

Docker Compose Deployment tool for remote servers
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
use std::time::Duration;
use tokio::fs;
use tokio::process::Command;
use tokio::time::sleep;

mod common;
use common::{build_dcd_binary, ssh_cmd, start_ssh_server, TestProject};

#[cfg(feature = "integration-tests")]
#[tokio::test]
async fn test_ssh_server() {
    let (container, host_port) = start_ssh_server().await;

    // Try SSH connection with key-based authentication
    let status = ssh_cmd(
        host_port,
        "tests/test_ssh_key",
        "root@127.0.0.1",
        &["echo", "hello"],
    )
    .status()
    .await
    .expect("failed to execute ssh command");
    assert!(status.success(), "SSH command failed");

    // Verify output
    let output = ssh_cmd(
        host_port,
        "tests/test_ssh_key",
        "root@127.0.0.1",
        &["echo", "hello"],
    )
    .output()
    .await
    .expect("failed to execute ssh command");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "hello");

    container.stop().await.unwrap();
}

#[cfg(feature = "integration-tests")]
#[tokio::test]
async fn test_dcd_up() {
    let (container, ssh_port) = start_ssh_server().await;

    // Build the project's binary
    let _dcd_path = build_dcd_binary();

    // Prepare temporary project directory with a simple nginx compose file
    let compose_content = [
        "version: '3'",
        "services:",
        "  nginx:",
        "    image: nginx:alpine",
        "    ports:",
        "      - \"8080:80\"",
    ]
    .join("\n");
    let remote_workdir = "/opt/test_dcd_up";
    let project = TestProject::new(&compose_content, "", remote_workdir).await;

    // Run the DCD up command to deploy nginx
    let target = format!("root@localhost:{}", ssh_port);
    let mut cmd = Command::new(&project.dcd_bin_path);
    cmd.current_dir(&project.project_dir)
        .env("SYSTEM_VAR", "sys_val")
        .args([
            "-f",
            project.compose_path.to_str().unwrap(),
            "-e",
            project.env_path.to_str().unwrap(),
            "-i",
            "test_ssh_key",
            "-w",
            remote_workdir,
            "up",
            "--no-health-check",
            &target,
        ]);
    let output = cmd
        .output()
        .await
        .expect("Failed to execute DCD up command");
    assert!(
        output.status.success(),
        "DCD up command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    // The success message may be logged to stderr or stdout
    assert!(
        stdout.contains("Deployment successful") || stderr.contains("Deployment successful"),
        "Unexpected output:\n--- STDOUT ---\n{}\n--- STDERR ---\n{}",
        stdout,
        stderr
    );

    // Allow some time for Docker Compose to start containers
    sleep(Duration::from_secs(5)).await;

    // Verify nginx container is running via SSH
    let ps_output = ssh_cmd(
        ssh_port,
        "tests/test_ssh_key",
        "root@localhost",
        &["docker", "ps"],
    )
    .output()
    .await
    .expect("Failed to execute SSH docker ps");
    let ps_stdout = String::from_utf8_lossy(&ps_output.stdout);
    assert!(
        ps_stdout.contains("nginx"),
        "Nginx container not found in docker ps output: {}",
        ps_stdout
    );

    // Teardown deployment and verify
    project.destroy(&target, ssh_port, &["nginx"]).await;

    // Stop helper container
    container.stop().await.unwrap();
}

// Test deploying a container with environment variables from .env file, system env, and defaults
#[cfg(feature = "integration-tests")]
#[tokio::test]
async fn test_dcd_up_with_env_and_defaults() {
    let (container, ssh_port) = start_ssh_server().await;

    // Build the project's binary
    let _dcd_path = build_dcd_binary();

    let compose_content = [
        "version: '3'",
        "services:",
        "  test:",
        "    image: busybox:latest",
        "    container_name: test_env",
        "    command: [\"sh\", \"-c\", \"sleep 3600\"]",
        "    environment:",
        "      - FILE_VAR=${FILE_VAR}",
        "      - SYSTEM_VAR=${SYSTEM_VAR}",
        "      - DEFAULT_VAR=${DEFAULT_VAR:-def123}",
    ]
    .join("\n");
    let env_content = "FILE_VAR=file_val\n";
    let remote_workdir = "/opt/test_dcd_up_with_env_and_defaults";
    let project = TestProject::new(&compose_content, env_content, remote_workdir).await;

    // Run the DCD up command with --no-health-check, setting SYSTEM_VAR in environment
    let target = format!("root@localhost:{}", ssh_port);
    let mut cmd = Command::new(&project.dcd_bin_path);
    cmd.current_dir(&project.project_dir)
        .env("SYSTEM_VAR", "sys_val")
        .args([
            "-f",
            project.compose_path.to_str().unwrap(),
            "-e",
            project.env_path.to_str().unwrap(),
            "-i",
            "test_ssh_key",
            "-w",
            remote_workdir,
            "up",
            "--no-health-check",
            &target,
        ]);
    let output = cmd
        .output()
        .await
        .expect("Failed to execute DCD up command");
    assert!(
        output.status.success(),
        "DCD up command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stdout.contains("Deployment successful") || stderr.contains("Deployment successful"),
        "Unexpected output:\n--- STDOUT ---\n{}\n--- STDERR ---\n{}",
        stdout,
        stderr
    );

    // Allow some time for Docker Compose to start containers
    sleep(Duration::from_secs(5)).await;

    // Verify test_env container is running via SSH
    let ps_output = ssh_cmd(
        ssh_port,
        "tests/test_ssh_key",
        "root@localhost",
        &["docker", "ps", "--format", "{{.Names}}"],
    )
    .output()
    .await
    .expect("Failed to execute SSH docker ps");
    let ps_stdout = String::from_utf8_lossy(&ps_output.stdout);
    assert!(
        ps_stdout.lines().any(|name| name.trim() == "test_env"),
        "test_env container not found: {}",
        ps_stdout
    );

    // Verify environment variables inside the container
    let env_output = ssh_cmd(
        ssh_port,
        "tests/test_ssh_key",
        "root@localhost",
        &["docker", "exec", "test_env", "env"],
    )
    .output()
    .await
    .expect("Failed to execute SSH docker exec env");
    let env_stdout = String::from_utf8_lossy(&env_output.stdout);
    assert!(
        env_stdout.contains("FILE_VAR=file_val"),
        "FILE_VAR not set: {}",
        env_stdout
    );
    assert!(
        env_stdout.contains("SYSTEM_VAR=sys_val"),
        "SYSTEM_VAR not set: {}",
        env_stdout
    );
    assert!(
        env_stdout.contains("DEFAULT_VAR=def123"),
        "DEFAULT_VAR default not set: {}",
        env_stdout
    );

    // Teardown deployment and verify
    project.destroy(&target, ssh_port, &["test_env"]).await;

    container.stop().await.unwrap();
}

#[cfg(feature = "integration-tests")]
#[tokio::test]
async fn test_dcd_redeploy_with_changes() {
    let (container, ssh_port) = start_ssh_server().await;
    let _dcd_path = build_dcd_binary(); // Ensure binary is built

    // Initial project setup
    let initial_compose_content = [
        "version: '3'",
        "services:",
        "  service1:",
        "    image: busybox:latest",
        "    container_name: service1_redeploy",
        "    command: [\"sh\", \"-c\", \"sleep 3600\"]",
        "    environment:",
        "      - MY_VAR=${MY_VAR}",
    ]
    .join("\n");
    let initial_env_content = "MY_VAR=initial_value\n";
    let remote_workdir = "/opt/test_dcd_redeploy";
    let project = TestProject::new(
        &initial_compose_content,
        initial_env_content,
        remote_workdir,
    )
    .await;
    let target = format!("root@localhost:{}", ssh_port);

    // --- First Deployment ---
    let mut cmd_up1 = Command::new(&project.dcd_bin_path);
    cmd_up1.current_dir(&project.project_dir).args([
        "-f",
        project.compose_path.to_str().unwrap(),
        "-e",
        project.env_path.to_str().unwrap(),
        "-i",
        "test_ssh_key", // Relative to project_dir
        "-w",
        remote_workdir,
        "up",
        "--no-health-check",
        &target,
    ]);

    let output_up1 = cmd_up1
        .output()
        .await
        .expect("Failed to execute DCD up command (1st deploy)");
    assert!(
        output_up1.status.success(),
        "DCD up command failed (1st deploy): stderr: {}, stdout: {}",
        String::from_utf8_lossy(&output_up1.stderr),
        String::from_utf8_lossy(&output_up1.stdout)
    );
    let stdout_up1 = String::from_utf8_lossy(&output_up1.stdout);
    let stderr_up1 = String::from_utf8_lossy(&output_up1.stderr);
    assert!(
        stdout_up1.contains("Deployment successful")
            || stderr_up1.contains("Deployment successful"),
        "Unexpected output (1st deploy):\n--- STDOUT ---\n{}\n--- STDERR ---\n{}",
        stdout_up1,
        stderr_up1
    );

    sleep(Duration::from_secs(5)).await; // Allow time for containers to start

    // Verify service1 after 1st deploy
    let ps_output1 = ssh_cmd(
        ssh_port,
        "tests/test_ssh_key",
        "root@localhost",
        &["docker", "ps", "--format", "{{.Names}}"],
    )
    .output()
    .await
    .expect("SSH docker ps failed (after 1st deploy)");
    assert!(
        ps_output1.status.success(),
        "SSH docker ps command failed (after 1st deploy)"
    );
    let ps_stdout1 = String::from_utf8_lossy(&ps_output1.stdout);
    assert!(
        ps_stdout1
            .lines()
            .any(|name| name.trim() == "service1_redeploy"),
        "service1_redeploy not found after 1st deploy: {}",
        ps_stdout1
    );

    let env_output1 = ssh_cmd(
        ssh_port,
        "tests/test_ssh_key",
        "root@localhost",
        &["docker", "exec", "service1_redeploy", "env"],
    )
    .output()
    .await
    .expect("SSH docker exec env failed (service1, 1st deploy)");
    assert!(
        env_output1.status.success(),
        "SSH docker exec env command failed (service1, 1st deploy)"
    );
    let env_stdout1 = String::from_utf8_lossy(&env_output1.stdout);
    assert!(
        env_stdout1.contains("MY_VAR=initial_value"),
        "MY_VAR not 'initial_value' in service1 after 1st deploy: {}",
        env_stdout1
    );

    // --- Prepare for Redeployment ---
    // Modify docker-compose.yml: add service2, keep service1
    let updated_compose_content = [
        "version: '3'",
        "services:",
        "  service1:",
        "    image: busybox:latest", // Definition can remain the same or change
        "    container_name: service1_redeploy",
        "    command: [\"sh\", \"-c\", \"sleep 3600\"]",
        "    environment:",
        "      - MY_VAR=${MY_VAR}", // This will pick up the new .env value
        "  service2:",              // Add service2
        "    image: busybox:latest",
        "    container_name: service2_redeploy",
        "    command: [\"sh\", \"-c\", \"sleep 3600\"]",
    ]
    .join("\n");
    fs::write(&project.compose_path, updated_compose_content)
        .await
        .expect("Failed to write updated docker-compose.yml");

    // Modify .env: change MY_VAR
    let updated_env_content = "MY_VAR=updated_value\n";
    fs::write(&project.env_path, updated_env_content)
        .await
        .expect("Failed to write updated .env file");

    // --- Second Deployment (Redeploy) ---
    let mut cmd_up2 = Command::new(&project.dcd_bin_path);
    cmd_up2.current_dir(&project.project_dir).args([
        "-f",
        project.compose_path.to_str().unwrap(), // Use updated compose
        "-e",
        project.env_path.to_str().unwrap(), // Use updated env
        "-i",
        "test_ssh_key",
        "-w",
        remote_workdir,
        "up",
        "--no-health-check",
        &target,
    ]);

    let output_up2 = cmd_up2
        .output()
        .await
        .expect("Failed to execute DCD up command (redeploy)");
    assert!(
        output_up2.status.success(),
        "DCD up command failed (redeploy): stderr: {}, stdout: {}",
        String::from_utf8_lossy(&output_up2.stderr),
        String::from_utf8_lossy(&output_up2.stdout)
    );
    let stdout_up2 = String::from_utf8_lossy(&output_up2.stdout);
    let stderr_up2 = String::from_utf8_lossy(&output_up2.stderr);
    assert!(
        stdout_up2.contains("Deployment successful")
            || stderr_up2.contains("Deployment successful"),
        "Unexpected output (redeploy):\n--- STDOUT ---\n{}\n--- STDERR ---\n{}",
        stdout_up2,
        stderr_up2
    );

    sleep(Duration::from_secs(10)).await;

    // Verify after redeploy
    let ps_output2 = ssh_cmd(
        ssh_port,
        "tests/test_ssh_key",
        "root@localhost",
        &["docker", "ps", "--format", "{{.Names}}"],
    )
    .output()
    .await
    .expect("SSH docker ps failed (after redeploy)");
    assert!(
        ps_output2.status.success(),
        "SSH docker ps command failed (after redeploy)"
    );
    let ps_stdout2 = String::from_utf8_lossy(&ps_output2.stdout);

    // Check service1 (still running, env updated)
    assert!(
        ps_stdout2
            .lines()
            .any(|name| name.trim() == "service1_redeploy"),
        "service1_redeploy not found after redeploy: {}",
        ps_stdout2
    );
    let env_output2_service1 = ssh_cmd(
        ssh_port,
        "tests/test_ssh_key",
        "root@localhost",
        &["docker", "exec", "service1_redeploy", "env"],
    )
    .output()
    .await
    .expect("SSH docker exec env failed (service1, redeploy)");
    assert!(
        env_output2_service1.status.success(),
        "SSH docker exec env command failed (service1, redeploy)"
    );
    let env_stdout2_service1 = String::from_utf8_lossy(&env_output2_service1.stdout);
    assert!(
        env_stdout2_service1.contains("MY_VAR=updated_value"),
        "MY_VAR not 'updated_value' in service1 after redeploy: {}",
        env_stdout2_service1
    );

    // Check service2 (newly added)
    assert!(
        ps_stdout2
            .lines()
            .any(|name| name.trim() == "service2_redeploy"),
        "service2_redeploy not found after redeploy: {}",
        ps_stdout2
    );

    // --- Teardown ---
    project
        .destroy(
            &target,
            ssh_port,
            &["service1_redeploy", "service2_redeploy"],
        )
        .await;

    container.stop().await.unwrap();
}