Skip to content

Embed buildkit #3058

Closed
Closed

Description

@shykes

Currently the setup instructions start with "make sure dagger-buildkit is running". We should remove this dependency on an external buildkit daemon, by embedding buildkit into the cloak binary.

Activity

  1. sipsma commented on Aug 8, 2022

    @sipsma
    Contributor

    Agree that we need to fix that step of the setup instructions and also agree that we in the long-term need to embed buildkit.

    However, in the short-term I think we should fix the setup instructions with the approach described in this issue: #3086

    The problem is that embedding buildkit will also require splitting cloak out into separate client+server binaries. So to be be a bit more detailed on the scope of this:

    • Right now cloak is a single binary that runs the graphql engine and then talks to buildkit (by default the dagger-buildkitd container)
    • The end goal would be that cloak is split into a client and server:
      • Server embeds buildkitd as a library in addition to the graphql engine
      • Client talks to the server over graphql+buildkit APIs.
        • The main reason the client binary needs to exist still is that for things like uploading localdirs to buildkit, it's really hard to reimplement that functionality in every language. Instead, we are going to follow a model where languages like TS get access to that ability by running a local cloak client binary.
        • The client binary is thus sort of like a language agnostic "proxy" to the server. TS code can start the client, send its graphql queries to it, at which point the client binary will forward them to the server (and also handle things like uploading localdirs as needed).

    None of this is incredibly clear yet, so there's still a lot of details to be disambiguated and designs to be made. The above is just a sketch of our current thinking on it.

  2. sipsma commented on Sep 14, 2022

    @sipsma
    Contributor

    @grouville has been making good progress on creating our own buildkitd wrapper (as a subcommand of the cloak binary). I guess we can call that cloakd.

    We are now reaching the point where we'll have to make a decision on how to distribute this since we will no longer be using the moby/buildkit image. I am not 100% sure yet so writing out some options for everyone to consider.

    For now, we're just thinking about how we can have the same experience today where buildkitd isn't running and BUILDKIT_HOST is not set, then it will be automatically spun up for you. In the longer term there's a lot more we can do in terms of making generic "provisioner" concepts, which is worth pondering now but not an immediate implementation goal.


    A - Straightforward Approach

    1. We create a dagger/cloak container image repo, build and push to it whenever we merge into main (via GHA). We use the git version embedded in the cloak binary to choose an image version.
      • We'll want to make sure we build for every architecture we intend to support.
    2. For development (i.e. I locally made a change to the cloakd code and need to test against it), we can run a command that rebuilds and replaces the existing cloakd.
      • I suppose this could even be a subcommand of cloak (cloak provision?), which avoids the need for an external thing like make/mage/etc., but that would probably be hidden for now as it relies on source code being available locally which is kind of unusual and very specific to our development processes (not something every user needs).

    Pros:

    1. Obvious how it works, simple in that respect
    2. More dogfooding opportunities (can push to cloak container image repo using cloak! including w/ multiplatform support which is my current main focus)
    3. The possible use of cloak provision is intriguing in that it could be the entrypoint to the more generic provisioner concept

    Cons:

    1. Requires a little bit of infrastructure management (the image repository) and dealing with building for multiple platforms.

    B - Crazy (almost certainly bad) Idea

    We re-use the idea of the shim and the go codegen plugin; the source code of cloakd is actually embedded into the cloak binary itself. This would enable it to bootstrap cloakd by building it; whereas today we just docker run the moby/buildkit image, we would now docker build the embedded source code and then run the resulting image.

    Pros:

    1. No infrastructure. Only dependency is on docker existing locally to the user, which was already a dependency anyways, so nothing new.
    2. Easy to always build for the right platform since the build happens locally to the user

    Cons:

    1. Weird. It probably works today but feels like it could easily hit hard to deal with cases.
      • I know with go embed you can't embed a subdirectory that has a different go.mod. That wouldn't currently impact us but is plausible to in the future.

    Overall, I'm leaning towards option A. Option B is intriguing but too much risk of breakage in the future. I suppose even in Option A it might be possible to also embed the source code and use it as part of cloak provision, so A is probably the better place to start and we can incorporate the ideas of B in the future if it ever ends up making sense to do so.

  3. marcosnils commented on Sep 15, 2022

    @marcosnils
    Contributor

    👋 thinking about this, I have a question that I'm not sure I understand how we intend to solve with the current approach. cloakd in OSX and Windows requires a special treatment since it won't run natively in the host. Reading your previous comment I understand that we'll have some sort of dagger/cloak image for those scenarios, so docker will still be a hard dependency to start cloakd? or we're planning to follow a similar approach lima is doing to bootstrap the tiny VM environment ourselves "automagically"?

  4. shykes commented on Sep 15, 2022

    @shykes
    ContributorAuthor

    @marcosnils 2 part answer:

    1. there is always a local daemon regardless of OS. this is required for host access. client talks to local engine over graphql.

    2. the local engine may need to provision a 2nd engine on docker, lima, kubernetes, remote ssh etc. This ideally would use pluggable provisioners. local engine talks to remote engine over buildkit/grpc

  5. shykes commented on Sep 15, 2022

    @shykes
    ContributorAuthor

    @sipsma on the topic of persistent vs ephemeral engines. I know there are limitations in how ephemeral a buildkit pro ess can be, because of (basically) unsafe concurrent access to the state dir. However i really would prefer that we spare our users the complexity of provisioning, upgrading and generally worrying about stateful dagger daemons (cloak provision etc). We have been down that road before with docker machine, swarm node management, buildx nodes… It’s best avoided.

    I’m not saying “let’s pretend these technical limitations don’t exist”. But I think we can get creative and abstract away the handling of buildkit state insteatyof dumping it on the user’s shoulders. After all, it’s all cache: there’s no fundamental reason that we need a si gle steteful persistent daemon.

    I don’t have a comete solution but two thoughts to kickoff:

    1. A good model is how ssh lets you reuse the same socket actoss several sessions with ControlMaster: auto. Each session will first look for an existing socket to reuse; and fallback to creating it. This is great because it abstracts away the management team a persistent resource (shared socket) into a stateless UX.

    2. What if each buildkit was ephemeral a d operated in an ephemeral state dir, but imported cache from $HOME/.dagger/cache just before and exported back right after? Assuming we can tweak performance (don’t want to wait 30 seconds before each run) it would allow buildkit daemon to be truly stateless while persisting what actually matters: the cache data.

    One way or the other I strongly believe that we should separate provisioning (install cloak binary) from invoking (run cloak binary for this session)

  6. marcosnils commented on Sep 15, 2022

    @marcosnils
    Contributor
    • there is always a local daemon regardless of OS. this is required for host access. client talks to local engine over graphql.

    got it. It wasn't clear to me from the initial comments on this issue. Specifically given this comment:

    Server embeds buildkitd as a library in addition to the graphql engine

    Reading this sentence I understood that the server side daemon is going to serve both buildkit and the graphql API. It wasn't clear to me that the definitive solution involves having two daemons with splitted responsibility.

  7. shykes commented on Sep 15, 2022

    @shykes
    ContributorAuthor
    • there is always a local daemon regardless of OS. this is required for host access. client talks to local engine over graphql.

    got it. It wasn't clear to me from the initial comments on this issue. Specifically given this comment:

    Server embeds buildkitd as a library in addition to the graphql engine

    Reading this sentence I understood that the server side daemon is going to serve both buildkit and the graphql API. It wasn't clear to me that the definitive solution involves having two daemons with splitted responsibility.

    It’s all one binary: dagger. So yes it’s the same daemon that an serve gql & buildkit. But on a mac you will need two instances of that daemon, one local and one remote.

  8. added this to the Cloak GA milestone on Sep 16, 2022
  9. transferred this issue fromdagger/cloakon Sep 16, 2022
  10. grouville commented on Sep 27, 2022

    @grouville
    Member

    Here is a summary of the current approach explored:

    1. Embed the go compilation of the buildkit image as a go library
    2. Embed the go binary to build the buildkit binary on the host
    3. Statically assemble images with no build
    4. Pluggable provisioner (docker / lima ...) regarding the current installed container tools

    For 1, it doesn't seem possible, as the go compiler is just a main function.
    For 2, it seems possible (exploring), however, the go compiler cannot be statically built without cgo (golang/go#40711). However, I don't think it is that important -> we could embed the binary for each arch in our pipeline (However, the global binary will be huge). This seems to be the most promising long-term build that doesn't rely on any provisioner

    Currently exploring 3) and will start implementing 4) (as backup), but if you have any idea @vito @gerhard, open to ideas

  11. gerhard commented on Sep 27, 2022

    @gerhard
    Contributor

    One of the features that everyone I worked with loved about Concourse CI was the single binary approach. It was just shy of 300MB (so almost as big as Windows '98), but it had absolutely everything built-in, including the CLI. It had Windows, Mac & Linux variants, and it was trivial to run it on any platform. The vast majority of people would run it on Linux because it had proper support for containers. Windows & Mac were storing state in dirs and were not as mature, but they worked and people used them.

    This is the experience that I imagine us having for the new Dagger:

    image

    WDYT @vito?


    If certain features are not supported on a particular platform today, it's OK to return not implemented errors. In terms of the platforms that BuildKit supports, this suggests to me that everything we care about is supported: https://github.com/moby/buildkit/releases/tag/v0.10.4

  12. grouville commented on Sep 27, 2022

    @grouville
    Member

    To keep you all in touch, the second option seems very promising -> embedding the go distributed binary with //go:embed binary. Using below test script:

    package main
    
    import (
    	_ "embed"
    	"fmt"
    	"os"
    	"os/exec"
    )
    
    //go:embed binary
    var f []byte
    
    func main() {
    	_ = os.WriteFile("foobar", f, 0755)
    	defer os.Remove("foobar")
    	out, err := exec.Command("./foobar", "version").CombinedOutput()
    	if err != nil {
    		fmt.Print("ok", err)
    		return
    	}
    	fmt.Printf("Output: %s\n", out)
    }
    

    I am able to play with "foobar", which is the go binary. It would require to have different "embed" go binary for each distribution (in our pipeline), but it seems manageable.

    Next step today:

    • Make a quine out of our source-code (in an elegant way)
    • auto-build my fork of cloak by integrating something like this script.

    Next challenge around that: we currently only build on linux, so managing windows + mac will then become more important

  13. sipsma commented on Sep 27, 2022

    @sipsma
    Contributor

    To keep you all in touch, the second option seems very promising -> embedding the go distributed binary with //go:embed binary.

    I think it will be more than this. Once we actually want to build something with the embedded binary we will also need to have access to a GOROOT (i.e. all the stdlib source code), so that will need to be embedded too I believe.

    Overall, my thinking is that no matter what we will need a provisioner (docker, lima, etc.), right? And so it seems simplest to me to just re-use what we support for provisioners as builders too. So we can embed our source code into our binary but then just use docker build or lima whatever to actually build it. That means that we have no new dependencies or complications on top of the dependencies and complications we need for provisioning/executing daggerd.

    Another option here would be to either A) embed the full golang container image into our binary (which we can then unpack and use locally) or B) import a container image pulling library that allows us to pull and unpack it locally when needed. I'm not sure, but we might be able to get away with a rootless approach here through use of LD_LIBRARY_PATH (that's the safe one, not to be confused with the evil LD_PRELOAD) and thus avoid the need to chroot or setup namespaces, etc.. But this would be more advanced, probably not the right starting place.

    I agree that if we go the route of embedding the go binary and GOROOT it's not the absolute end of the world, but I am quite confident it will eventually be a pretty huge gotcha for anyone building or packaging dagger. One of go's touted benefits is that if you give it the right build arguments it will create a statically linked binary for you. If we go this route, that's just not possible anymore as there will always be this secret link against libc.

  14. grouville commented on Sep 27, 2022

    @grouville
    Member

    Ok, so (2) seems doable BUT isn't the easiest to implement. As seen with @sipsma today I'll implement, for tomorrow, the pluggable provisioner approach to merge the current Buildkit integration into cloak (to avoid parallel work for too long).

    We'll then be able to explore all the other options from there
    Another source of reference: https://github.com/k0sproject/k0s, which has 3 approches (using provisioners), with and without provisioners.

  15. vito commented on Sep 27, 2022

    @vito
    Contributor

    Here's how we tackled this with Concourse:

    In our case we depended on a project called Guardian which was a container runtime more similar to Docker than Buildkit. For reasons not worth explaining here its official releases were published in the cloudfoundry/garden-runc-release repo.

    They simplified things for us by bundling all of their dependencies (e.g. runc, iptables) into a single gdn binary, which is essentially the same approach we took for bundling gdn itself. It was like a Go binary matryoshka doll.

    The 300MB distribution size @gerhard mentions was actually a bit of a special case: we bundled not only the runtime and client CLI but also a dozen or so image rootfses which dramatically inflated the size, especially because they were flat .tgz files with a lot of duplication.

    Most of this is about the Linux amd64 distribution. We supported Darwin and Windows too but they didn't have an external runtime or rootfses to bundle; just the client CLI binaries (same as Linux).

    Buildkit doesn't have an all-in-one binary like gdn; instead it ships a handful of binaries in its distribution:

    ❯ tar tzf buildkit-v0.10.4.linux-amd64.tar.gz
    bin/
    bin/buildctl
    bin/buildkit-qemu-aarch64
    bin/buildkit-qemu-arm
    bin/buildkit-qemu-i386
    bin/buildkit-qemu-mips64
    bin/buildkit-qemu-mips64el
    bin/buildkit-qemu-ppc64le
    bin/buildkit-qemu-riscv64
    bin/buildkit-qemu-s390x
    bin/buildkit-runc
    bin/buildkitd
    

    I don't think this would be particularly hard to deal with though. When we run buildkitd we would just need them on the $PATH.

    Is there a reason I missed to avoid embedding pre-built binaries? It felt pretty simple to maintain. Bundling all of Go (+ $GOROOT) and building from source feels like a lot more moving parts. I'm interested in seeing if it works and has benefits of its own, but I'm a little worried about having to keep in sync with Buildkit's build process since it's not exactly a simple go build:

    CGO_ENABLED=0 xx-go build -ldflags "$(cat /tmp/.ldflags) -extldflags '-static'" -tags "osusergo netgo static_build seccomp ${BUILDKITD_TAGS}" -o /usr/bin/buildkitd ./cmd/buildkitd && \

    (via)

    IMO the safest thing would be to stick as closely to their best-supported distribution as possible. To me that means their Dockerfile and/or .tgz releases. If we want to support forking Buildkit someday I'd argue we should do that by just re-using their build scripts and such in our fork and just becoming "upstream" to ourselves.

    But this is just my $.02c. 🙂

  16. vito commented on Sep 27, 2022

    @vito
    Contributor

    Quick side-note: one weakness to our approach was we left the user responsible for managing the sudo concourse worker command lifecycle. Maybe we could have a "systemd unit" provisioner to make it easier to daemonize. This would only be relevant to a Linux host though.

  17. sipsma commented on Sep 27, 2022

    @sipsma
    Contributor

    @vito

    Thanks for the context there, super interesting and the matryoshka doll idea was particularly delightful :-)

    One thing to clarify, part of what we are doing here is to wrap buildkitd. We aren't considering this a fork because we are still using the same buildkitd codebase, we just are recreating their main func and making it a subcommand of cloak. We're doing the same for buildctl too.

    The main problems we need to solve are:

    1. cloak may need to provision itself on platforms that are different than what it was built for (i.e. cloak on a macbook needs to deploy itself to a linux vm running in docker desktop/lima/etc.).
    2. Like you mentioned, there are more binaries to buildkitd than just buildkitd (runc, emulators, etc.)

    Is there a reason I missed to avoid embedding pre-built binaries?

    For the use case here this would entail embedding cloak and any other required binaries (runc, emulators) for each target platform we may want to support. I suppose runc and emulators could also become subcommands of cloak too, so then that simplifies the problem to cloak embedding cloak binaries for all other platforms.

    My main concern there was the enormous bloat in the binary size, which was one reason why I liked the approach of embedding source code only as much as possible and then re-using our provisioners (docker, lima, etc.) to also do the building. However, I'm realizing that might be a personal bias worth reassessing (I did a lot of IoT stuff in previous jobs where huge binary generally == bad). The fact that @gerhard and other concourse users did not consider 300 MB to be a deal breaker probably indicates that it's not the mortal sin I thought it was.

    If we assume big binary is fine, then yeah it's by far the simplest approach in terms of runtime behavior (build time is a bit complicated, but that's fine obviously).


    I do think that no matter what we need to make all of this pluggable and behind interfaces like:

    1. Builder - give me a cloak binary (or rootfs with binaries) targeting a given platform, hypothetical example implementations:
      • Retrieve an embedded binary/rootfs
      • Download a corresponding binary/rootfs from the internet somewhere (check its hash and all that)
      • Use embedded source code to build cloak using docker build (or various equivalents)
      • Use embedded source code to build cloak using cloak (once we've bootstrapped ourselves sufficiently)
    2. Provisioner - run cloak somewhere, example implementations:
      • docker
      • lima
      • fork/exec (need sudo)
      • embedded rootless container engine
      • k8s
      • CLOAK_HOST env (connect to existing one)

    The thing is today we do already have 2 Provisioner implementations (docker run and BUILDKIT_HOST env), so what we're trying to do now is add our first Builder implementation. I think given that we already have a dependency on docker run in our main current Provisioner, the absolute simplest route is to add a Builder that just uses docker build. No new dependencies.

    I think this is the shortest route to something usable. It may also be desirable in that until we have sufficiently stabilized cloak, it may not be good to bootstrap and use cloak to build cloak (my instinct anyways, low confidence). So even when we want to start embedding binaries in binaries, we will need to build those binaries somehow.docker build is probably an okay solution for enabling that until we've reached the point of being able to use cloak.

    That's why I suggest starting here with docker build+embedded source code, but in such a way that its behind an interface that can have more implementation in the future.

  18. vito commented on Sep 27, 2022

    @vito
    Contributor

    Oops, a correction now that I've checked how Concourse is actually packaged these days: it doesn't do an all-in-one binary anymore, instead it's a big (1.4GB!!!) .tgz that you unpack to /usr/local/concourse that just includes all of its dependencies under bin/ and other dirs. They aren't embedded anymore. The approach is similar in spirit; it's still bundling binaries, but the user manages where they're placed instead of having a self-extracting binary.

    I think we opted to do this because we had a ton of assets to unpack and it was faster to just have the user do it at installation time rather than pay a penalty at runtime.

    One thing to clarify, part of what we are doing here is to wrap buildkitd. We aren't considering this a fork because we are still using the same buildkitd codebase, we just are recreating their main func and making it a subcommand of cloak. We're doing the same for buildctl too.

    Similar for us - concourse worker was just glue for running gdn and registering it as a Concourse worker. But instead of re-implementing main we just ran gdn as a sub-process.

    We originally tried using its code directly, the same as you're proposing, but it was nontrivial to integrate its build into ours. Just shelling out ended up being less of a hassle and meant we could very quickly just bump an asset when it came time for security updates without worrying if any part of the build process or dependencies (replace rules in go.mod etc) had changed.

    My main concern there was the enormous bloat in the binary size, which was one reason why I liked the approach of embedding source code only as much as possible and then re-using our provisioners (docker, lima, etc.) to also do the building. However, I'm realizing that might be a personal bias worth reassessing (I did a lot of IoT stuff in previous jobs where huge binary generally == bad). The fact that @gerhard and other concourse users did not consider 300 MB to be a deal breaker probably indicates that it's not the mortal sin I thought it was.

    Totally fair. We did get a snarky tweet about it. 😆 But yeah it didn't seem to cause any actual issues.

    If we're considering embedding Go itself though, it's not exactly tiny:

    File name Kind OS Arch Size SHA256 Checksum
    go1.19.1.linux-amd64.tar.gz Archive Linux x86-64 142MB acc512fbab4f716a8f97a8b3fbaa9ddd39606a28be6c2515ef7c6c6311acffde

    Maybe parts of it could be stripped out?

    The sum of all binaries in buildkit's .tgz is 111.5MB, which is definitely heftier than I had hoped but it's around the same ballpark. If we remove buildctl (I don't think we need it?) that would save 25M.

    ❯ ls -lh
    total 111M
    -rwxr-xr-x 1 vito users  25M Oct 20  2015 buildctl
    -rwxr-xr-x 1 vito users  38M Oct 20  2015 buildkitd
    -rwxr-xr-x 1 vito users 5.2M Oct 20  2015 buildkit-qemu-aarch64
    -rwxr-xr-x 1 vito users 3.8M Oct 20  2015 buildkit-qemu-arm
    -rwxr-xr-x 1 vito users 2.9M Oct 20  2015 buildkit-qemu-i386
    -rwxr-xr-x 1 vito users 3.3M Oct 20  2015 buildkit-qemu-mips64
    -rwxr-xr-x 1 vito users 3.2M Oct 20  2015 buildkit-qemu-mips64el
    -rwxr-xr-x 1 vito users 3.8M Oct 20  2015 buildkit-qemu-ppc64le
    -rwxr-xr-x 1 vito users 3.4M Oct 20  2015 buildkit-qemu-riscv64
    -rwxr-xr-x 1 vito users 2.9M Oct 20  2015 buildkit-qemu-s390x
    -rwxr-xr-x 1 vito users  20M Oct 20  2015 buildkit-runc
    

    This would definitely start to add up if we start bundling each supported platform/architecture. Maybe we could have a "netboot" version that lazily downloads the appropriate package as needed? We'd still want a batteries-included version for behind-the-firewall though...


    +1 to the builder/provisioner ideas. I think those are important primitives to have around so we can stay nimble and adjust as we encounter new deployment schemes.

  19. shykes commented on Oct 20, 2022

    @shykes
    ContributorAuthor

    I am closing this issue because, although the need to bundle buildkit still exists, our preferred solution is no longer to bundle everything in the same binary. Rather, we should aim to make the Dagger Engine a fully server-side component (instead of the current mix of client-side API router and server-side solver (aka buildkit) - then bundle it all into an OCI image. We should start fresh and discuss this new approach in a new issue.

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

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions