zlayer-agent 0.11.11

Container runtime agent using libcontainer/youki
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
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
//! Docker runtime integration tests
//!
//! These tests verify the `DockerRuntime` implementation against a real Docker daemon.
//! Tests are gated behind the `docker` feature and will be skipped if Docker is not available.
//!
//! # Requirements
//! - Docker daemon must be running
//! - The `docker` feature must be enabled
//!
//! # Running
//! ```bash
//! cargo test -p zlayer-agent --features docker -- --nocapture
//! ```

#![cfg(feature = "docker")]

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use zlayer_agent::runtimes::DockerRuntime;
use zlayer_agent::{ContainerId, ContainerState, Runtime};
use zlayer_spec::{
    CommandSpec, ErrorsSpec, HealthCheck, HealthSpec, ImageSpec, InitSpec, NodeMode, PullPolicy,
    ResourceType, ResourcesSpec, ScaleSpec, ServiceNetworkSpec, ServiceSpec, ServiceType,
};

// =============================================================================
// Test Configuration
// =============================================================================

/// Test image - alpine is small and fast to pull
const TEST_IMAGE: &str = "alpine:latest";

/// Timeout for operations that might take a while (like pulling images)
const LONG_TIMEOUT: Duration = Duration::from_secs(120);

/// Timeout for quick operations
const SHORT_TIMEOUT: Duration = Duration::from_secs(30);

// =============================================================================
// Helper Functions
// =============================================================================

/// Attempt to connect to Docker. Returns None if Docker is not available.
async fn skip_if_no_docker() -> Option<DockerRuntime> {
    DockerRuntime::new(None).await.ok()
}

/// Generate a unique container name with random suffix to avoid conflicts
fn unique_container_name(prefix: &str) -> String {
    use rand::Rng;
    let suffix: u32 = rand::rng().random_range(10000..99999);
    #[allow(clippy::cast_possible_truncation)]
    let timestamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64
        % 1_000_000;
    format!("test-{prefix}-{timestamp}-{suffix}")
}

/// Create a `ContainerId` with a unique service name
fn unique_container_id(prefix: &str) -> ContainerId {
    ContainerId {
        service: unique_container_name(prefix),
        replica: 1,
    }
}

/// Create a minimal `ServiceSpec` for testing
fn create_test_spec(image: &str) -> ServiceSpec {
    ServiceSpec {
        rtype: ResourceType::Service,
        schedule: None,
        image: ImageSpec {
            name: image.parse().expect("valid image reference"),
            pull_policy: PullPolicy::IfNotPresent,
        },
        resources: ResourcesSpec::default(),
        env: HashMap::new(),
        command: CommandSpec::default(),
        network: ServiceNetworkSpec::default(),
        endpoints: vec![],
        scale: ScaleSpec::default(),
        depends: vec![],
        health: HealthSpec {
            start_grace: None,
            interval: None,
            timeout: None,
            retries: 3,
            check: HealthCheck::Tcp { port: 0 },
        },
        init: InitSpec::default(),
        errors: ErrorsSpec::default(),
        lifecycle: zlayer_spec::LifecycleSpec::default(),
        devices: vec![],
        storage: vec![],
        port_mappings: vec![],
        capabilities: vec![],
        cap_drop: vec![],
        privileged: false,
        node_mode: NodeMode::default(),
        node_selector: None,
        service_type: ServiceType::default(),
        wasm: None,
        logs: None,
        host_network: false,
        hostname: None,
        dns: Vec::new(),
        extra_hosts: Vec::new(),
        restart_policy: None,
        labels: HashMap::new(),
        user: None,
        stop_signal: None,
        stop_grace_period: None,
        sysctls: HashMap::new(),
        ulimits: HashMap::new(),
        security_opt: Vec::new(),
        pid_mode: None,
        ipc_mode: None,
        network_mode: zlayer_spec::NetworkMode::default(),
        extra_groups: Vec::new(),
        read_only_root_fs: false,
        init_container: None,
        platform: None,
        tty: false,
        stdin_open: false,
        userns_mode: None,
        cgroup_parent: None,
        expose: Vec::new(),
    }
}

/// Create a `ServiceSpec` with a command that outputs to stdout and exits
fn create_echo_spec(message: &str) -> ServiceSpec {
    let mut spec = create_test_spec(TEST_IMAGE);
    spec.command = CommandSpec {
        entrypoint: None,
        args: Some(vec![
            "sh".to_string(),
            "-c".to_string(),
            format!("echo '{}'", message),
        ]),
        workdir: None,
    };
    spec
}

/// Create a `ServiceSpec` that sleeps for the specified number of seconds
fn create_sleep_spec(seconds: u32) -> ServiceSpec {
    let mut spec = create_test_spec(TEST_IMAGE);
    spec.command = CommandSpec {
        entrypoint: None,
        args: Some(vec!["sleep".to_string(), seconds.to_string()]),
        workdir: None,
    };
    spec
}

/// RAII guard that ensures container cleanup even on test failure
struct ContainerGuard {
    runtime: Arc<DockerRuntime>,
    id: ContainerId,
}

impl ContainerGuard {
    fn new(runtime: Arc<DockerRuntime>, id: ContainerId) -> Self {
        Self { runtime, id }
    }
}

impl Drop for ContainerGuard {
    fn drop(&mut self) {
        let runtime = self.runtime.clone();
        let id = self.id.clone();

        // Use tokio::task::block_in_place to run async cleanup in drop
        // This ensures cleanup happens even if the test panics
        if let Ok(handle) = tokio::runtime::Handle::try_current() {
            handle.spawn(async move {
                // Try to stop the container (ignore errors - it might already be stopped)
                let _ = runtime.stop_container(&id, Duration::from_secs(5)).await;
                // Force remove the container
                let _ = runtime.remove_container(&id).await;
            });
        }
    }
}

/// Wait for a container to reach the expected state
async fn wait_for_state(
    runtime: &DockerRuntime,
    id: &ContainerId,
    expected: ContainerState,
    timeout: Duration,
) -> Result<ContainerState, String> {
    let start = std::time::Instant::now();
    let poll_interval = Duration::from_millis(100);

    while start.elapsed() < timeout {
        match runtime.container_state(id).await {
            Ok(state) => {
                // For Exited state, match the variant regardless of exit code
                match (&state, &expected) {
                    (ContainerState::Exited { .. }, ContainerState::Exited { .. }) => {
                        return Ok(state);
                    }
                    _ if state == expected => return Ok(state),
                    _ => {}
                }
            }
            Err(e) => {
                // Container might not exist yet, keep waiting
                if start.elapsed() > Duration::from_secs(5) {
                    return Err(format!("Error getting container state: {e}"));
                }
            }
        }
        tokio::time::sleep(poll_interval).await;
    }

    Err(format!(
        "Timeout waiting for container {id:?} to reach state {expected:?}"
    ))
}

// =============================================================================
// Tests
// =============================================================================

/// Test that we can connect to the Docker daemon
#[tokio::test]
async fn test_docker_connection() {
    let Some(_runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };

    // If we get here, connection was successful
    println!("Successfully connected to Docker daemon");
}

/// Test pulling an image with default policy (`IfNotPresent`)
#[tokio::test]
async fn test_pull_image() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };

    println!("Pulling image: {TEST_IMAGE}");

    let result = tokio::time::timeout(LONG_TIMEOUT, runtime.pull_image(TEST_IMAGE)).await;

    match result {
        Ok(Ok(())) => println!("Image pulled successfully"),
        Ok(Err(e)) => panic!("Failed to pull image: {e}"),
        Err(e) => panic!("Timeout pulling image: {e}"),
    }
}

/// Test that `IfNotPresent` policy skips pulling when image exists
#[tokio::test]
async fn test_pull_image_if_not_present() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };

    // First, ensure the image exists by pulling it
    println!("Ensuring image exists: {TEST_IMAGE}");
    let _ = tokio::time::timeout(LONG_TIMEOUT, runtime.pull_image(TEST_IMAGE)).await;

    // Now pull with IfNotPresent - this should be instant since image exists
    println!("Testing IfNotPresent policy (should skip pull)");
    let start = std::time::Instant::now();

    let result = tokio::time::timeout(
        SHORT_TIMEOUT,
        runtime.pull_image_with_policy(TEST_IMAGE, PullPolicy::IfNotPresent, None),
    )
    .await;

    let elapsed = start.elapsed();
    println!("IfNotPresent pull completed in {elapsed:?}");

    match result {
        Ok(Ok(())) => {
            // Should complete quickly since image is already present
            assert!(
                elapsed < Duration::from_secs(5),
                "IfNotPresent should be fast for existing images"
            );
            println!("IfNotPresent correctly skipped pull");
        }
        Ok(Err(e)) => panic!("Failed with IfNotPresent policy: {e}"),
        Err(e) => panic!("Timeout with IfNotPresent policy: {e}"),
    }
}

/// Test complete container lifecycle: create -> start -> get state -> stop -> remove
#[tokio::test]
async fn test_container_lifecycle() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };
    let runtime = Arc::new(runtime);

    // Ensure image is available
    let _ = tokio::time::timeout(LONG_TIMEOUT, runtime.pull_image(TEST_IMAGE)).await;

    let id = unique_container_id("lifecycle");
    let spec = create_sleep_spec(300); // Sleep for 5 minutes (we'll stop it early)

    // Setup cleanup guard
    let _guard = ContainerGuard::new(runtime.clone(), id.clone());

    // 1. Create container
    println!("Creating container: {}", id.service);
    let create_result = runtime.create_container(&id, &spec).await;
    assert!(
        create_result.is_ok(),
        "Failed to create container: {create_result:?}"
    );

    // 2. Verify container exists and is in Pending state
    let state = runtime.container_state(&id).await;
    assert!(state.is_ok(), "Failed to get container state: {state:?}");
    assert_eq!(
        state.unwrap(),
        ContainerState::Pending,
        "Container should be Pending after create"
    );

    // 3. Start container
    println!("Starting container: {}", id.service);
    let start_result = runtime.start_container(&id).await;
    assert!(
        start_result.is_ok(),
        "Failed to start container: {start_result:?}"
    );

    // 4. Wait for Running state
    let wait_result = wait_for_state(&runtime, &id, ContainerState::Running, SHORT_TIMEOUT).await;
    assert!(
        wait_result.is_ok(),
        "Container did not reach Running state: {}",
        wait_result.unwrap_err()
    );
    println!("Container is running");

    // 5. Stop container
    println!("Stopping container: {}", id.service);
    let stop_result = runtime.stop_container(&id, Duration::from_secs(10)).await;
    assert!(
        stop_result.is_ok(),
        "Failed to stop container: {stop_result:?}"
    );

    // 6. Verify container is stopped (Exited state)
    let state = runtime.container_state(&id).await;
    assert!(state.is_ok(), "Failed to get container state after stop");
    match state.unwrap() {
        ContainerState::Exited { code } => {
            println!("Container exited with code: {code}");
        }
        other => panic!("Expected Exited state, got: {other:?}"),
    }

    // 7. Remove container
    println!("Removing container: {}", id.service);
    let remove_result = runtime.remove_container(&id).await;
    assert!(
        remove_result.is_ok(),
        "Failed to remove container: {remove_result:?}"
    );

    // 8. Verify container is gone
    let state = runtime.container_state(&id).await;
    assert!(state.is_err(), "Container should not exist after removal");
    println!("Container successfully removed");
}

/// Test container logs retrieval
#[tokio::test]
async fn test_container_logs() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };
    let runtime = Arc::new(runtime);

    // Ensure image is available
    let _ = tokio::time::timeout(LONG_TIMEOUT, runtime.pull_image(TEST_IMAGE)).await;

    let id = unique_container_id("logs");
    let test_message = "Hello from ZLayer Docker test!";
    let spec = create_echo_spec(test_message);

    // Setup cleanup guard
    let _guard = ContainerGuard::new(runtime.clone(), id.clone());

    // Create and start container
    println!("Creating container that outputs: {test_message}");
    runtime
        .create_container(&id, &spec)
        .await
        .expect("Failed to create container");
    runtime
        .start_container(&id)
        .await
        .expect("Failed to start container");

    // Wait for container to exit (it will exit quickly after echoing)
    let _ = wait_for_state(
        &runtime,
        &id,
        ContainerState::Exited { code: 0 },
        SHORT_TIMEOUT,
    )
    .await;

    // Get logs
    println!("Retrieving container logs");
    let logs = runtime
        .container_logs(&id, 100)
        .await
        .expect("Failed to get logs");

    let logs_text: String = logs
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join("\n");
    println!("Logs: {logs_text}");
    assert!(
        logs.iter().any(|e| e.message.contains(test_message)),
        "Logs should contain the test message"
    );

    // Also test get_logs (returns Vec<LogEntry>)
    let log_lines = runtime
        .get_logs(&id)
        .await
        .expect("Failed to get log lines");
    println!("Log lines: {log_lines:?}");
    assert!(
        log_lines
            .iter()
            .any(|entry| entry.message.contains(test_message)),
        "Log lines should contain the test message"
    );
}

/// Test executing a command inside a running container
#[tokio::test]
async fn test_container_exec() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };
    let runtime = Arc::new(runtime);

    // Ensure image is available
    let _ = tokio::time::timeout(LONG_TIMEOUT, runtime.pull_image(TEST_IMAGE)).await;

    let id = unique_container_id("exec");
    let spec = create_sleep_spec(300); // Long-running container

    // Setup cleanup guard
    let _guard = ContainerGuard::new(runtime.clone(), id.clone());

    // Create and start container
    println!("Creating long-running container for exec test");
    runtime
        .create_container(&id, &spec)
        .await
        .expect("Failed to create container");
    runtime
        .start_container(&id)
        .await
        .expect("Failed to start container");

    // Wait for container to be running
    wait_for_state(&runtime, &id, ContainerState::Running, SHORT_TIMEOUT)
        .await
        .expect("Container did not start");

    // Execute a command
    println!("Executing command inside container");
    let cmd = vec!["echo".to_string(), "exec test output".to_string()];
    let (exit_code, stdout, stderr) = runtime.exec(&id, &cmd).await.expect("Failed to exec");

    println!("Exec result - exit_code: {exit_code}, stdout: {stdout}, stderr: {stderr}");

    assert_eq!(exit_code, 0, "Exec should succeed with exit code 0");
    assert!(
        stdout.contains("exec test output"),
        "Stdout should contain the echoed message"
    );

    // Test a command that writes to stderr
    println!("Testing command that writes to stderr");
    let cmd = vec![
        "sh".to_string(),
        "-c".to_string(),
        "echo 'stderr output' >&2".to_string(),
    ];
    let (exit_code, stdout, stderr) = runtime.exec(&id, &cmd).await.expect("Failed to exec");

    println!("Stderr exec - exit_code: {exit_code}, stdout: '{stdout}', stderr: '{stderr}'");
    assert_eq!(exit_code, 0, "Exec should succeed");
    assert!(
        stderr.contains("stderr output"),
        "Stderr should contain the error output"
    );

    // Test a command that fails
    println!("Testing command that fails");
    let cmd = vec!["sh".to_string(), "-c".to_string(), "exit 42".to_string()];
    let (exit_code, _, _) = runtime.exec(&id, &cmd).await.expect("Failed to exec");

    assert_eq!(exit_code, 42, "Exec should return the expected exit code");
}

/// Test getting container resource statistics
#[tokio::test]
async fn test_container_stats() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };
    let runtime = Arc::new(runtime);

    // Ensure image is available
    let _ = tokio::time::timeout(LONG_TIMEOUT, runtime.pull_image(TEST_IMAGE)).await;

    let id = unique_container_id("stats");
    let spec = create_sleep_spec(300); // Long-running container

    // Setup cleanup guard
    let _guard = ContainerGuard::new(runtime.clone(), id.clone());

    // Create and start container
    println!("Creating container for stats test");
    runtime
        .create_container(&id, &spec)
        .await
        .expect("Failed to create container");
    runtime
        .start_container(&id)
        .await
        .expect("Failed to start container");

    // Wait for container to be running
    wait_for_state(&runtime, &id, ContainerState::Running, SHORT_TIMEOUT)
        .await
        .expect("Container did not start");

    // Give it a moment to accumulate some stats
    tokio::time::sleep(Duration::from_secs(1)).await;

    // Get stats
    println!("Getting container stats");
    let stats = runtime
        .get_container_stats(&id)
        .await
        .expect("Failed to get stats");

    println!(
        "Container stats - CPU usage: {} usec, Memory: {} bytes, Memory limit: {} bytes",
        stats.cpu_usage_usec, stats.memory_bytes, stats.memory_limit
    );

    // Verify stats are reasonable (memory should be > 0 for a running container)
    assert!(
        stats.memory_bytes > 0,
        "Memory usage should be greater than 0"
    );
    assert!(
        stats.memory_limit > 0,
        "Memory limit should be greater than 0"
    );
}

/// Test waiting for a container to exit with exit code 0
#[tokio::test]
async fn test_wait_container_success() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };
    let runtime = Arc::new(runtime);

    // Ensure image is available
    let _ = tokio::time::timeout(LONG_TIMEOUT, runtime.pull_image(TEST_IMAGE)).await;

    let id = unique_container_id("wait-success");
    let _guard = ContainerGuard::new(runtime.clone(), id.clone());

    let mut spec = create_test_spec(TEST_IMAGE);
    spec.command = CommandSpec {
        entrypoint: None,
        args: Some(vec![
            "sh".to_string(),
            "-c".to_string(),
            "sleep 1 && exit 0".to_string(),
        ]),
        workdir: None,
    };

    println!("Testing wait_container with exit code 0");
    runtime
        .create_container(&id, &spec)
        .await
        .expect("Failed to create container");
    runtime
        .start_container(&id)
        .await
        .expect("Failed to start container");

    let exit_code = tokio::time::timeout(SHORT_TIMEOUT, runtime.wait_container(&id))
        .await
        .expect("Timeout waiting for container")
        .expect("Failed to wait for container");

    println!("Container exited with code: {exit_code}");
    assert_eq!(exit_code, 0, "Expected exit code 0");
}

/// Test waiting for a container to exit with non-zero exit code
#[tokio::test]
async fn test_wait_container_failure() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };
    let runtime = Arc::new(runtime);

    // Ensure image is available
    let _ = tokio::time::timeout(LONG_TIMEOUT, runtime.pull_image(TEST_IMAGE)).await;

    let id = unique_container_id("wait-nonzero");
    let _guard = ContainerGuard::new(runtime.clone(), id.clone());

    // Use exactly the same spec as the success test, but with exit 42
    let mut spec = create_test_spec(TEST_IMAGE);
    spec.command = CommandSpec {
        entrypoint: None,
        args: Some(vec![
            "sh".to_string(),
            "-c".to_string(),
            "sleep 2 && exit 42".to_string(),
        ]),
        workdir: None,
    };

    println!("Creating and starting container for exit code 42 test");
    println!("Container ID: {id:?}");

    runtime
        .create_container(&id, &spec)
        .await
        .expect("Failed to create container");

    runtime
        .start_container(&id)
        .await
        .expect("Failed to start container");

    // Check container is running
    let state = runtime
        .container_state(&id)
        .await
        .expect("Failed to get state after start");
    println!("State after start: {state:?}");

    // Wait for container using container_state polling as a workaround
    // if the wait_container API is unreliable
    println!("Waiting for container to exit...");
    let exit_code = loop {
        let state = runtime
            .container_state(&id)
            .await
            .expect("Failed to get state");
        match state {
            ContainerState::Exited { code } => {
                break code;
            }
            ContainerState::Running => {
                tokio::time::sleep(Duration::from_millis(100)).await;
            }
            other => {
                panic!("Unexpected state: {other:?}");
            }
        }
    };

    println!("Container exited with code: {exit_code}");
    assert_eq!(exit_code, 42, "Expected exit code 42");
}

/// Test waiting for a container that runs briefly
#[tokio::test]
async fn test_wait_container_timing() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };
    let runtime = Arc::new(runtime);

    // Ensure image is available
    let _ = tokio::time::timeout(LONG_TIMEOUT, runtime.pull_image(TEST_IMAGE)).await;

    let id = unique_container_id("wait-brief");
    let _guard = ContainerGuard::new(runtime.clone(), id.clone());

    let mut spec = create_test_spec(TEST_IMAGE);
    spec.command = CommandSpec {
        entrypoint: None,
        args: Some(vec!["sleep".to_string(), "1".to_string()]),
        workdir: None,
    };

    println!("Testing wait_container with brief sleep");
    runtime
        .create_container(&id, &spec)
        .await
        .expect("Failed to create container");
    runtime
        .start_container(&id)
        .await
        .expect("Failed to start container");

    let start = std::time::Instant::now();
    let exit_code = tokio::time::timeout(SHORT_TIMEOUT, runtime.wait_container(&id))
        .await
        .expect("Timeout waiting for container")
        .expect("Failed to wait for container");
    let elapsed = start.elapsed();

    println!("Container exited with code {exit_code} after {elapsed:?}");
    assert_eq!(exit_code, 0, "Expected exit code 0");
    assert!(
        elapsed >= Duration::from_millis(900),
        "Should have waited at least ~1 second"
    );
}

/// Test that multiple containers can be managed concurrently
#[tokio::test]
async fn test_concurrent_containers() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };
    let runtime = Arc::new(runtime);

    // Ensure image is available
    let _ = tokio::time::timeout(LONG_TIMEOUT, runtime.pull_image(TEST_IMAGE)).await;

    let container_count = 3;
    let mut guards = Vec::new();
    let mut ids = Vec::new();

    // Create multiple containers concurrently
    println!("Creating {container_count} containers concurrently");
    let mut create_handles = Vec::new();

    for i in 0..container_count {
        let runtime_clone = runtime.clone();
        let id = unique_container_id(&format!("concurrent-{i}"));
        let spec = create_sleep_spec(300);
        let id_clone = id.clone();

        ids.push(id.clone());
        guards.push(ContainerGuard::new(runtime.clone(), id));

        create_handles.push(tokio::spawn(async move {
            runtime_clone.create_container(&id_clone, &spec).await
        }));
    }

    // Wait for all creates to complete
    for handle in create_handles {
        let result = handle.await.expect("Task panicked");
        assert!(result.is_ok(), "Failed to create container: {result:?}");
    }

    // Start all containers concurrently
    println!("Starting {container_count} containers concurrently");
    let mut start_handles = Vec::new();

    for id in &ids {
        let runtime_clone = runtime.clone();
        let id_clone = id.clone();

        start_handles.push(tokio::spawn(async move {
            runtime_clone.start_container(&id_clone).await
        }));
    }

    for handle in start_handles {
        let result = handle.await.expect("Task panicked");
        assert!(result.is_ok(), "Failed to start container: {result:?}");
    }

    // Verify all are running
    for id in &ids {
        let state = runtime
            .container_state(id)
            .await
            .expect("Failed to get state");
        assert_eq!(
            state,
            ContainerState::Running,
            "Container {} should be running",
            id.service
        );
    }

    println!("All {container_count} containers are running");

    // Stop all containers concurrently
    println!("Stopping {container_count} containers concurrently");
    let mut stop_handles = Vec::new();

    for id in &ids {
        let runtime_clone = runtime.clone();
        let id_clone = id.clone();

        stop_handles.push(tokio::spawn(async move {
            runtime_clone
                .stop_container(&id_clone, Duration::from_secs(10))
                .await
        }));
    }

    for handle in stop_handles {
        let result = handle.await.expect("Task panicked");
        assert!(result.is_ok(), "Failed to stop container: {result:?}");
    }

    println!("All containers stopped successfully");
}

/// Test that removing a non-existent container succeeds (idempotent)
#[tokio::test]
async fn test_remove_nonexistent_container() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };

    let id = unique_container_id("nonexistent");

    println!(
        "Attempting to remove non-existent container: {}",
        id.service
    );
    let result = runtime.remove_container(&id).await;

    // Remove should succeed for non-existent containers (force: true handles this)
    // Or it might return NotFound - both are acceptable
    match result {
        Ok(()) => println!("Remove succeeded (idempotent behavior)"),
        Err(e) => println!("Remove returned error (also acceptable): {e}"),
    }
}

/// Test that getting state of non-existent container returns `NotFound` error
#[tokio::test]
async fn test_state_nonexistent_container() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };

    let id = unique_container_id("ghost");

    println!("Getting state of non-existent container: {}", id.service);
    let result = runtime.container_state(&id).await;

    assert!(result.is_err(), "Should fail for non-existent container");
    println!("Got expected error: {:?}", result.unwrap_err());
}

/// Test pull with Never policy (should not pull)
#[tokio::test]
async fn test_pull_never_policy() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };

    // Use an image that definitely doesn't exist locally
    let nonexistent_image = "this-image-definitely-does-not-exist:never";

    println!("Testing Never pull policy with non-existent image");
    let result = runtime
        .pull_image_with_policy(nonexistent_image, PullPolicy::Never, None)
        .await;

    // Never policy should return Ok immediately without pulling
    assert!(
        result.is_ok(),
        "Never policy should succeed without pulling: {result:?}"
    );
    println!("Never policy correctly skipped pull attempt");
}

/// Test pull with Always policy
#[tokio::test]
async fn test_pull_always_policy() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };

    println!("Testing Always pull policy");
    let result = tokio::time::timeout(
        LONG_TIMEOUT,
        runtime.pull_image_with_policy(TEST_IMAGE, PullPolicy::Always, None),
    )
    .await;

    match result {
        Ok(Ok(())) => println!("Always policy pulled successfully"),
        Ok(Err(e)) => panic!("Failed with Always policy: {e}"),
        Err(e) => panic!("Timeout with Always policy: {e}"),
    }
}

/// Test container with environment variables
#[tokio::test]
async fn test_container_with_env() {
    let Some(runtime) = skip_if_no_docker().await else {
        eprintln!("Skipping test: Docker not available");
        return;
    };
    let runtime = Arc::new(runtime);

    // Ensure image is available
    let _ = tokio::time::timeout(LONG_TIMEOUT, runtime.pull_image(TEST_IMAGE)).await;

    let id = unique_container_id("env");
    let mut spec = create_test_spec(TEST_IMAGE);

    // Add environment variables
    spec.env
        .insert("TEST_VAR".to_string(), "test_value".to_string());
    spec.env
        .insert("ANOTHER_VAR".to_string(), "another_value".to_string());

    // Command that prints env vars
    spec.command = CommandSpec {
        entrypoint: None,
        args: Some(vec!["sh".to_string(), "-c".to_string(), "env".to_string()]),
        workdir: None,
    };

    let _guard = ContainerGuard::new(runtime.clone(), id.clone());

    println!("Creating container with environment variables");
    runtime
        .create_container(&id, &spec)
        .await
        .expect("Failed to create container");
    runtime
        .start_container(&id)
        .await
        .expect("Failed to start container");

    // Wait for container to exit
    let _ = wait_for_state(
        &runtime,
        &id,
        ContainerState::Exited { code: 0 },
        SHORT_TIMEOUT,
    )
    .await;

    // Get logs and verify env vars
    let logs = runtime
        .container_logs(&id, 100)
        .await
        .expect("Failed to get logs");

    let logs_text: String = logs
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join("\n");
    println!("Container output:\n{logs_text}");
    assert!(
        logs.iter()
            .any(|e| e.message.contains("TEST_VAR=test_value")),
        "Logs should contain TEST_VAR"
    );
    assert!(
        logs.iter()
            .any(|e| e.message.contains("ANOTHER_VAR=another_value")),
        "Logs should contain ANOTHER_VAR"
    );
}