Skip to content

TestContainerWithUnixSocket fails when run directly on macos host #4073

Closed

Description

@sipsma

This requires running go test directly on macos (not dagger-in-dagger):

sipsma@Eriks-MBP-2 dagger % go test -v -count=1 -run TestContainerWithUnixSocket $(pwd)/core/integration
=== RUN   TestContainerWithUnixSocket
#1 resolve image config for docker.io/library/golang:1.18.2-alpine
#1 DONE 0.6s

#2 mkfile /main.go
#2 CACHED

#3 mkdir /meta
#3 CACHED

#4 docker-image://docker.io/library/golang:1.18.2-alpine
#4 resolve docker.io/library/golang:1.18.2-alpine
#4 resolve docker.io/library/golang:1.18.2-alpine 0.2s done
#4 CACHED

#5 go run /src/main.go /tmp/test.sock hello
#5 0.199 panic: EOF
#5 0.199
#5 0.199 goroutine 1 [running]:
#5 0.199 main.main()
#5 0.199     /src/main.go:31 +0x274
    container_test.go:2575:
            Error Trace:    /Users/sipsma/dagger/core/integration/container_test.go:2575
            Error:          Received unexpected error:
                            input:1: container.from.withMountedFile.withUnixSocket.withExec.stdout process "go run /src/main.go /tmp/test.sock hello" did not complete successfully: exit code: 1
                            
                            Please visit https://dagger.io/help#go for troubleshooting guidance.
            Test:           TestContainerWithUnixSocket
--- FAIL: TestContainerWithUnixSocket (2.08s)
FAIL
FAIL    github.com/dagger/dagger/core/integration    2.248s
FAIL

The same test passes when run directly on Linux.

Notably, the container only fails once it tries to read from the unix socket (this line), it can connect and write to it successfully, so it's not completely broken.

Also, when I instead run this test case on macos directly, it passes:

func TestContainerWithUnixSocket(t *testing.T) {
        ctx := context.Background()
        c, err := dagger.Connect(ctx, dagger.WithLogOutput(os.Stdout))
        require.NoError(t, err)

        dockerSock := c.Host().UnixSocket("/var/run/docker.sock")

        out, err := c.Container().
                From("docker").
                WithUnixSocket("/var/run/docker.sock", dockerSock).
                WithExec([]string{"docker", "ps", "-a"}).
                Stdout(ctx)
        require.NoError(t, err)
        require.Contains(t, out, "CONTAINER ID")
}

Based on that my best guess is that there's some subtle difference in unix socket behavior on macos vs linux and the loop in the original test case of accept, copy, close doesn't quite work for some reason. And then it works using the docker.sock because docker probably has code to properly handle the difference.

However, that's very much pure speculation, needs investigation.

Activity

  1. added
    kind/bug
    area/engine
    on Dec 1, 2022
  2. sipsma commented on Dec 1, 2022

    @sipsma
    ContributorAuthor
  3. sipsma commented on Dec 1, 2022

    @sipsma
    ContributorAuthor

    Also @vito, I just remembered you also added that TestGitSSHAuthSock test case. That passes totally fine on my mac w/out modification, so I suppose that increases the liklihood of it being specific to that other test case somehow

  4. sipsma commented on Dec 3, 2022

    @sipsma
    ContributorAuthor

    (posting a message already sent on discord earlier)

    I am not sure whether this is actually related or not, may be a total red herring, but it seems somewhat similar: I found that provisioning of the engine-session binary inside a dagger exec w/ the host's docker sock mounted doesn't work. Whenever an SDK runs the provisioning, the docker run --rm --entrypoint /bin/cat <image> /usr/bin/dagger-engine-session succeeds (exits w/ code 0) but the actual binary is always an empty file.

    I also verified that if I run an exec where I do the same command from a shell (with > /tmp/engine-session) I get the same behavior.

    The reason this seems similar is that it could be explain by the docker cli getting an unexpected early EOF while reading from the docker unix socket, which is exactly the failure seen in the test case mentioned here.

    This isn't a huge deal because we plan on changing the provisioning to download the CLI in the very near future, but still kind of odd. Again, could be completely unrelated to this issue, but mentioning in case it gives any debugging clues.

  5. GeorgeMac commented on Dec 16, 2022

    @GeorgeMac
    Contributor

    Just chiming in to say that I have experienced this in a project I work on 👋

    We have a test suite using testcontainers-go. I was experimenting with dagger for our CI pipeline.
    When I attempt to run our entire test suite, it fails when starting containers.
    I have used this feature (WithUnixSocket) in an attempt to get docker connectivity into my test.

    However, ultimately, this fails with failed to create container (I think this is coming out of testcontainers).
    That said, I see the container starting when I do docker ps.

    As you said @sipsma, it appears to be writing something, but down a one-way street.

    Unlikely this is useful, but this is where I am experimenting https://github.com/flipt-io/flipt/compare/gm/dagger-experiment?expand=1#diff-9eb02ca4f9553591bbf647feac8cbf2a35edcb53e9d9c62dddd87689d6e699e4R9-R16

    Oh, I am using Docker Desktop on MacOS.

  6. jpadams commented on Dec 21, 2022

    @jpadams
    Contributor

    Seeing this issue on Mac M1

    This works: "stdout": "Linux\n"

    dagger --debug query <<EOF
    query hello {
      container {
        from(address: "cimg/base:2022.12") {
          withUnixSocket(
            path: "/var/run/docker.sock"
            source: "eyJob3N0X3BhdGgiOiIvdmFyL3J1bi9kb2NrZXIuc29jayJ9Cg=="
          ) {
            withUser(name: "root") {
              withExec(args: ["bash", "-c", "uname"]) {
                stdout
                stderr
                defaultArgs
              }
            }
          }
        }
      }
    }
    EOF
    

    but these both work and produce expected output:

    dagger query --debug <<EOF
      query query {
        container {
          from(address: "alpine") {
            withExec(args: ["apk", "add", "docker-cli"]) {
              withUnixSocket(
                path: "/var/run/docker.sock"
                source: "eyJob3N0X3BhdGgiOiIvdmFyL3J1bi9kb2NrZXIuc29jayJ9Cg=="
              ) {
                withExec(args: ["docker", "--debug", "ps"]) {
                  stdout
                }
              }
            }
          }
        }
      }
    EOF
    
    dagger query --debug <<EOF
      query query {
        container {
          from(address: "alpine") {
            withExec(args: ["apk", "add", "docker-cli"]) {
              withUnixSocket(
                path: "/var/run/docker.sock"
                source: "eyJob3N0X3BhdGgiOiIvdmFyL3J1bi9kb2NrZXIuc29jayJ9Cg=="
              ) {
                withExec(args: ["docker", "--debug", "images"]) {
                  stdout
                }
              }
            }
          }
        }
      }
    

    these both seem to run, but don't produce any output (watch out for caching on subsequent runs with first one, change the sleep interval as needed to re-run):

    query hello {
      container {
        from(address: "cimg/base:2022.12") {
          withUnixSocket(
            path: "/var/run/docker.sock"
            source: "eyJob3N0X3BhdGgiOiIvdmFyL3J1bi9kb2NrZXIuc29jayJ9Cg=="
          ) {
            withUser(name: "root") {
              withExec(args: ["bash", "-c", "docker run alpine sleep 30s"]) {
                stdout
                stderr
                defaultArgs
              }
            }
          }
        }
      }
    }
    EOF
    
    dagger --debug query <<EOF
    query hello {
      container {
        from(address: "cimg/base:2022.12") {
          withUnixSocket(
            path: "/var/run/docker.sock"
            source: "eyJob3N0X3BhdGgiOiIvdmFyL3J1bi9kb2NrZXIuc29jayJ9Cg=="
          ) {
            withUser(name: "root") {
              withExec(args: ["docker", "run", "hello-world"]) {
                stdout
                stderr
                defaultArgs
              }
            }
          }
        }
      }
    }
    EOF
    
  7. sipsma commented on Dec 21, 2022

    @sipsma
    ContributorAuthor

    I did a bit more debugging by modifying the socket proxy code to print all the contents it reads+writes on the host side socket.

    From that I also managed to actually get the output to work if I made it so Close calls to that socket are ignored. I then added a stack trace print to that close call and found that it was getting called here: https://github.com/moby/buildkit/blob/c0e38e194c276a6e619e17a5ee7158e5bf55f5bf/session/sshforward/copy.go#L23

    Code with all the debug prints and ignore of close: sipsma@05f6a8e

    The fact that if I ignore the Close calls everything works as expected suggests to me that the err returned by stream.RecvMsg is safe to ignore in this case, so I think this might require a fix upstream in buildkit.

    I need to dig a bit more to understand why stream.RecvMsg gets an error first though.

    My initial hunch is that after the HTTP upgrade (see debug logs below), then client-side (docker cli running in container) is closing its side of the connection to indicate it will only be reading from here on out, not writing. But then that gets converted into a generic EOF in the grpc stream and the code presumes the whole stream is closed even though it just means the client won't be writing anymore data.

    • This is a complete guess though, needs validation.

    Used a slightly modified version of @jpadams snippets (thanks!):

    ./hack/dev ./bin/dagger query --debug <<EOF
      query {
        container {
          from(address: "alpine") {
            withExec(args: ["apk", "add", "docker-cli"]) {
              withUnixSocket(
                path: "/var/run/docker.sock"
                source: "eyJob3N0X3BhdGgiOiIvdmFyL3J1bi9kb2NrZXIuc29jayJ9Cg=="
              ) { withEnvVariable(name: "rand", value: "$RANDOM") {
                withExec(args: ["docker", "run", "hello-world"]) {
                  stdout
                  stderr
                }}
              }
            }
          }
        }
      }
    EOF
    

    Output when running with the debug output and ignore of close:

    #1 resolve image config for docker.io/library/alpine:latest
    #1 DONE 1.1s
    
    #2 mkdir /meta
    #2 CACHED
    
    #3 docker-image://docker.io/library/alpine:latest
    #3 resolve docker.io/library/alpine:latest
    #3 resolve docker.io/library/alpine:latest 0.2s done
    #3 DONE 0.2s
    
    #4 apk add docker-cli
    #4 CACHED
    
    #5 docker run hello-world
    1 FORWARDAGENT
    1 WRITE: HEAD /_ping HTTP/1.1
    Host: docker
    User-Agent: Docker-Client/20.10.21 (linux)
    
    
    1 READ: HTTP/1.1 200 OK
    Api-Version: 1.41
    Cache-Control: no-cache, no-store, must-revalidate
    Content-Length: 0
    Content-Type: text/plain; charset=utf-8
    Docker-Experimental: false
    Ostype: linux
    Pragma: no-cache
    Server: Docker/20.10.21 (linux)
    Date: Wed, 21 Dec 2022 18:42:38 GMT
    
    
    1 WRITE: POST /v1.41/containers/create HTTP/1.1
    Host: docker
    User-Agent: Docker-Client/20.10.21 (linux)
    Content-Length: 1518
    Content-Type: application/json
    
    {"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":true,"AttachStderr":true,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"hello-world","Volumes":{},"WorkingDir":"","Entrypoint":null,"OnBuild":
    null,"Labels":{},"HostConfig":{"Binds":null,"ContainerIDFile":"","LogConfig":{"Type":"","Config":{}},"NetworkMode":"default","PortBindings":{},"RestartPolicy":{"Name":"no","MaximumRetryCount":0},"AutoRemove":false,"VolumeDriver":"","VolumesFrom":null
    ,"CapAdd":null,"CapDrop":null,"CgroupnsMode":"","Dns":[],"DnsOptions":[],"DnsSearch":[],"ExtraHosts":null,"GroupAdd":null,"IpcMode":"","Cgroup":"","Links":null,"OomScoreAdj":0,"PidMode":"","Privileged":false,"PublishAllPorts":false,"ReadonlyRootfs":f
    alse,"SecurityOpt":null,"UTSMode":"","UsernsMode":"","ShmSize":0,"ConsoleSize":[0,0],"Isolation":"","CpuShares":0,"Memory":0,"NanoCpus":0,"CgroupParent":"","BlkioWeight":0,"BlkioWeightDevice":[],"BlkioDeviceReadBps":null,"BlkioDeviceWriteBps":null,"B
    lkioDeviceReadIOps":null,"BlkioDeviceWriteIOps":null,"CpuPeriod":0,"CpuQuota":0,"CpuRealtimePeriod":0,"CpuRealtimeRuntime":0,"CpusetCpus":"","CpusetMems":"","Devices":[],"DeviceCgroupRules":null,"DeviceRequests":null,"KernelMemory":0,"KernelMemoryTCP
    ":0,"MemoryReservation":0,"MemorySwap":0,"MemorySwappiness":-1,"OomKillDisable":false,"PidsLimit":0,"Ulimits":null,"CpuCount":0,"CpuPercent":0,"IOMaximumIOps":0,"IOMaximumBandwidth":0,"MaskedPaths":null,"ReadonlyPaths":null},"NetworkingConfig":{"Endp
    ointsConfig":{}}}
    
    1 READ: HTTP/1.1 201 Created
    Api-Version: 1.41
    Content-Type: application/json
    Docker-Experimental: false
    Ostype: linux
    Server: Docker/20.10.21 (linux)
    Date: Wed, 21 Dec 2022 18:42:38 GMT
    Content-Length: 88
    
    {"Id":"eac429ce9184b3d78ef0f0fc47c60c3f615d5fa54d2619c8f617897bfdba8740","Warnings":[]}
    
    2 FORWARDAGENT
    2 WRITE: POST /v1.41/containers/eac429ce9184b3d78ef0f0fc47c60c3f615d5fa54d2619c8f617897bfdba8740/attach?stderr=1&stdout=1&stream=1 HTTP/1.1
    Host: 
    User-Agent: Docker-Client/20.10.21 (linux)
    Content-Length: 0
    Connection: Upgrade
    Content-Type: text/plain
    Upgrade: tcp
    
    
    2 READ: HTTP/1.1 101 UPGRADED
    Content-Type: application/vnd.docker.raw-stream
    Connection: Upgrade
    Upgrade: tcp
    
    
    1 WRITE: POST /v1.41/containers/eac429ce9184b3d78ef0f0fc47c60c3f615d5fa54d2619c8f617897bfdba8740/wait?condition=next-exit HTTP/1.1
    Host: docker
    User-Agent: Docker-Client/20.10.21 (linux)
    Content-Length: 0
    Content-Type: text/plain
    
    
    2 CLOSE
    1 READ: HTTP/1.1 200 OK
    Api-Version: 1.41
    Content-Type: application/json
    Docker-Experimental: false
    Ostype: linux
    Server: Docker/20.10.21 (linux)
    Date: Wed, 21 Dec 2022 18:42:38 GMT
    Transfer-Encoding: chunked
    
    
    3 FORWARDAGENT
    3 WRITE: POST /v1.41/containers/eac429ce9184b3d78ef0f0fc47c60c3f615d5fa54d2619c8f617897bfdba8740/start HTTP/1.1
    Host: docker
    User-Agent: Docker-Client/20.10.21 (linux)
    Content-Length: 0
    Content-Type: text/plain
    
    
    2 READ: )
    Hello from Docker!
    This message shows that your installation appears to be working correctly.
    
    To generate this message, Docker took the following steps:
     1. The Docker client contacted the Docker daemon.
     2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
        (arm64v8)
     3. The Docker daemon created a new container from that image which runs the
        executable that produces the output you are currently reading.
     4. The Docker daemon streamed that output to the Docker client, which sent it
        to your terminal.
    
    To try something more ambitious, you can run an Ubuntu container with:
     $ docker run -it ubuntu bash
    
    Share images, automate workflows, and more with a free Docker ID:
     https://hub.docker.com/
    
    For more examples and ideas, visit:
     https://docs.docker.com/get-started/
    
    
    #5 0.527 
    #5 0.527 Hello from Docker!
    #5 0.527 This message shows that your installation appears to be working correctly.
    #5 0.527 
    #5 0.527 To generate this message, Docker took the following steps:
    #5 0.527  1. The Docker client contacted the Docker daemon.
    #5 0.527  2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    #5 0.527     (arm64v8)
    #5 0.527  3. The Docker daemon created a new container from that image which runs the
    #5 0.527     executable that produces the output you are currently reading.
    #5 0.527  4. The Docker daemon streamed that output to the Docker client, which sent it
    #5 0.527     to your terminal.
    #5 0.527 
    #5 0.527 To try something more ambitious, you can run an Ubuntu container with:
    #5 0.527  $ docker run -it ubuntu bash
    #5 0.527 
    #5 0.527 Share images, automate workflows, and more with a free Docker ID:
    #5 0.527  https://hub.docker.com/
    #5 0.527 
    #5 0.527 For more examples and ideas, visit:
    #5 0.527  https://docs.docker.com/get-started/
    #5 0.527 
    3 READ: HTTP/1.1 204 No Content
    Api-Version: 1.41
    Docker-Experimental: false
    Ostype: linux
    Server: Docker/20.10.21 (linux)
    Date: Wed, 21 Dec 2022 18:42:39 GMT
    
    
    2 READ ERROR: EOF
    2 FORWARDAGENT DONE
    1 READ: 1e
    {"Error":null,"StatusCode":0}
    
    0
    
    
    1 CLOSE
    3 CLOSE
    #5 DONE 0.7s
    {
        "container": {
            "from": {
                "withExec": {
                    "withUnixSocket": {
                        "withEnvVariable": {
                            "withExec": {
                                "stderr": "",
                                "stdout": "\nHello from Docker!\nThis message shows that your installation appears to be working correctly.\n\nTo generate this message, Docker took the following steps:\n 1. The Docker client contacted the Docker daemon.\
    n 2. The Docker daemon pulled the \"hello-world\" image from the Docker Hub.\n    (arm64v8)\n 3. The Docker daemon created a new container from that image which runs the\n    executable that produces the output you are currently reading.\n 4. The Doc
    ker daemon streamed that output to the Docker client, which sent it\n    to your terminal.\n\nTo try something more ambitious, you can run an Ubuntu container with:\n $ docker run -it ubuntu bash\n\nShare images, automate workflows, and more with a f
    ree Docker ID:\n https://hub.docker.com/\n\nFor more examples and ideas, visit:\n https://docs.docker.com/get-started/\n\n"
                            }
                        }
                    }
                }
            }
        }
    }
    

    cc @vito @marcosnils

  8. sipsma commented on Dec 21, 2022

    @sipsma
    ContributorAuthor

    Found the relevant grpc docs, confirmed that the client can close the send side but still want to use the recv side. Opened a fix upstream here: moby/buildkit#3431

  9. marcosnils commented on Dec 21, 2022

    @marcosnils
    Contributor

    🎉 great!

  10. sipsma commented on Jan 4, 2023

    @sipsma
    ContributorAuthor

    This will be picked up and fixed when we update to the new buildkit release: #4293

  11. sipsma commented on Jan 4, 2023

    @sipsma
    ContributorAuthor

    That upstream fix wasn't in v0.11-rc3 so still need to wait for the official release or another rc, but in the meantime I double checked and confirmed that the docker run case works now on macos when using buildkit from my upstream commit.

    That's good because it is an actual real world use case we care about and it works now. However when I try the test case this issue was originally created for, I am still getting the same EOF as before sadly.

    I dug in a bit and it seems to be a completely different issue even though it seemed similar to the docker run case. I found that on macos we never even make it past this line where the macos buildkit client is trying to connect to the locally created unix socket. We also never make it past the accept call in the actual test case code (though we do successfully make it past the listen call outside the goroutine).

    This makes me suspect once again that there's just something about macos that is different than linux in terms of how you setup listening on a unix socket. I have other higher priority things to get to so cutting this off here for the moment since it seems the real-world use case is working now at least.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/enginekind/bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions