1# Test for cntr tool
2{
3 system ? builtins.currentSystem,
4 config ? { },
5 pkgs ? import ../.. { inherit system config; },
6 lib ? pkgs.lib,
7}:
8
9let
10 inherit (import ../lib/testing-python.nix { inherit system pkgs; }) makeTest;
11
12 mkOCITest =
13 backend:
14 makeTest {
15 name = "cntr-${backend}";
16
17 meta = {
18 maintainers = with lib.maintainers; [
19 sorki
20 mic92
21 ];
22 };
23
24 nodes = {
25 ${backend} =
26 { pkgs, ... }:
27 {
28 environment.systemPackages = [ pkgs.cntr ];
29 virtualisation.oci-containers = {
30 inherit backend;
31 containers.nginx = {
32 image = "nginx-container";
33 imageStream = pkgs.dockerTools.examples.nginxStream;
34 ports = [ "8181:80" ];
35 };
36 };
37 };
38 };
39
40 testScript = ''
41 start_all()
42 ${backend}.wait_for_unit("${backend}-nginx.service")
43 ${backend}.wait_for_open_port(8181)
44 # For some reason, the cntr command hangs when run without the &.
45 # As such, we have to do some messy things to ensure we check the exitcode and output in a race-condition-safe manner
46 ${backend}.execute(
47 "(cntr attach -t ${backend} nginx sh -- -c 'curl localhost | grep Hello' > /tmp/result; echo $? > /tmp/exitcode; touch /tmp/done) &"
48 )
49
50 ${backend}.wait_for_file("/tmp/done")
51 assert "0" == ${backend}.succeed("cat /tmp/exitcode").strip(), "non-zero exit code"
52 assert "Hello" in ${backend}.succeed("cat /tmp/result"), "no greeting in output"
53 '';
54 };
55
56 mkContainersTest = makeTest {
57 name = "cntr-containers";
58
59 meta = with pkgs.lib.maintainers; {
60 maintainers = [
61 sorki
62 mic92
63 ];
64 };
65
66 nodes.machine =
67 { lib, ... }:
68 {
69 environment.systemPackages = [ pkgs.cntr ];
70 containers.test = {
71 autoStart = true;
72 privateNetwork = true;
73 hostAddress = "172.16.0.1";
74 localAddress = "172.16.0.2";
75 config = { };
76 };
77 };
78
79 testScript = ''
80 machine.start()
81 machine.wait_for_unit("container@test.service")
82 # I haven't observed the same hanging behaviour in this version as in the OCI version which necessetates this messy invocation, but it's probably better to be safe than sorry and use it here as well
83 machine.execute(
84 "(cntr attach test sh -- -c 'ping -c5 172.16.0.1'; echo $? > /tmp/exitcode; touch /tmp/done) &"
85 )
86
87 machine.wait_for_file("/tmp/done")
88 assert "0" == machine.succeed("cat /tmp/exitcode").strip(), "non-zero exit code"
89 '';
90 };
91in
92{
93 nixos-container = mkContainersTest;
94}
95// (lib.foldl' (attrs: backend: attrs // { ${backend} = mkOCITest backend; }) { } [
96 "docker"
97 "podman"
98])