Skip to content

Engine Image - #3647

Merged
sipsma merged 20 commits into
dagger:mainfrom
sipsma:engine
Nov 8, 2022
Merged

sipsma merged 20 commits into
dagger:mainfrom
sipsma:engine

Conversation

@sipsma

@sipsma sipsma commented Nov 2, 2022 •

Copy link
Copy Markdown
Contributor

Tested against Go SDK and Python so far (have since removed the Python related commits from here in order to disentangle).

This is currently a backwards compatible PR. Once all other SDKs (python+nodejs) have been updated with the new docker-image engineconn, we can removed the embedded engineconn from here and get rid of the replace stuff. That will be a follow up though.

Approach

We now build a container image that includes buildkitd and dagger engine binaries. We build it for multiple arches and include binaries for each client OS as needed

  • mage engine:dev will build and run it from your local code in docker just for the os/arch needed to test locally.
  • mage engine:publish will build it for all arch/os combos and push it to a registry (just a placeholder registry until we have set up a real one)
  • mage engine:test builds the local test engine and then runs go test ./... against it

New engineconn implementations

docker-image://<image>

This is going to be the default connector once all is said and done.

This one accepts a ref to an engine image *which must include an pinned @sha256: digest). The SDK runs the image, copies out the dagger-sdk-helper binary for the client os/arch to a local cache dir and then invokes it as a child process

  • The image entrypoint is still just buildkitd, so it's long running still for now
  • The image is run with a name dagger-engine-<id>, where id is from the pinned sha of the image ref
    • if a container is already running with that name, the SDK can safely assume it's the right container and was just already made by a different SDK instance
  • The local helper binaries are also suffixed with -<id> so that they can be re-used safely.
    • Binaries are copied out from the engine container with docker cp to a temporary file in the same cache dir as the final binary. Then we do the rename syscall to atomically swap it to the final binary, which ensures consistent behavior when SDKs are running concurrently.
  • There's also garbage collection of containers and binaries as described here.

docker-container://<container name>

This one is only needed for our testing setup currently. It also only needs an implementation in Go; other SDKs can skip it.

It follows the same idea as docker-image except that:

  1. It doesn't try to docker run anything, it just uses the container it's provided as is
  2. It doesn't try to cache the helper binaries locally, it copies them to a temp file, execs the helper from that and then unlinks the binary so that once the helper exits, its gone from the filesystem
  3. It doesn't do any garbage collection

The mage:startlocal target mentioned above builds the local engine image, loads it into docker and then starts a docker container from it. It finally prints out the env var you need to set to run against that container (export DAGGER_HOST=docker-container://test-dagger-engine)

  • This allows the tests to re-use a persistent volume (so that every rebuild of an engine doesn't cause your tests to lose cache)
  • The container name is prefixed with test- so that it isn't picked up by the garbage collection of the docker-image engineconn

Helper binary interface

This binary is internal only, should only be invoked as a subprocess of the SDK engineconn implementations.

It is it's own main func, completely separate from the existing cloak commands. It is packaged into the engine image at /usr/bin/dagger-sdk-helper-<os>-<arch>

  1. Accepts --workdir and --project the same as other previous commands
  2. Also accepts --remote which tells it how to connect to the remote engine (e.g. docker-container://dagger-engine-abc123)
  3. It writes engine log output to its stderr
  4. It starts by listening on any available ephemeral port on localhost (uses :0 to tell the kernel to find an available one for it). It then writes the port number it found to stdout. This allows sdks to know which port to connect to.
  5. Its stdin is expected to be a pipe from the parent SDK process. This pipe is used as a platform-agnostic way of knowing when the parent process has died (the pipe gets closed), which is a simple way of ensuring the helper binary shutsdown whenever the parent exits.

TODOs:

  • Fix linting errors
  • Fix spurious error log message: accept tcp 127.0.0.1:36089: use of closed network connection shows up because the helper needs to ignore that error on shutdown
  • Extra safety around reading port number from helper binary (timeout and validation of number read)

For follow up PRs:

  1. Fix spurious error log messages from always waiting on buildkitd being ready now, which causes the pre-existing logrus messages to appear more often.
  2. Basic developer docs for building and testing the engine. How to make a change to the core api, test an SDK against it, etc.
  3. E2E testing of new engineconn implementations (including running different SDKs in parallel with one another)
  4. Update engine release step and enginconn implementations with official registry for engine image
    • Also consider pushing to a staging tag or something
  5. Once the above is done, remove embedded engineconn from the Go SDK and default to the docker-image engineconn
    • This also allows us to get rid of the replace statements (and thus update our docs to no longer mention that)
    • It also will allow us to remove the old buildkitd provisioning from the engine itself (though this will in turn require updates to cloak dev unless the playground backend uses a different approach).
  6. Update the rest of the SDKs to use the new provisioner (Python has been implemented and tested, just being handled in separate PR, NodeJS is a TODO).
  7. Consider adding more optimizations in terms of image size (only including one arch, though that will complicate SDK code)
  8. Consider adding checksum verification of helper binaries
  9. Consider getting rid of caching of local helper binaries
    • This simplifies implementations and is less one-way-door-y than caching them, but also increases memory usage (20 MB every time any SDK calls dagger.Connect) and slightly increases startup time of dagger.Connect
  10. Consider including Windows client binaries
    • The limiting factor here is that I don't have a windows machine to test on (and ideally, we'd like automated testing, though we don't have that for macos today and get by)

FAQ

  1. Why put the provisioning logic in the SDKs rather than keeping common logic in the helper?
    1. We don't want to be fully reliant on the helper binary for this forever, so we need to do this eventually anyways. It's not that much logic to put in the SDKs either, so while it's a tradeoff, it seems like the right one.
    2. The architecture is easier to understand and explain this way:
      • This PR: "The SDKs provision an engine by running the engine image in docker. They currently need some engine code to run locally, so they copy an helper binary to a local cache and invoke it as a subprocess to facilitate communication with the remote engine."
      • The other approach: "The SDKs provision an engine by pulling the engine image in docker and copying out a helper binary from it. They then tell that binary which engine image to use, which the binary accepts and uses to run the remote engine image (that contains itself)."
        • Possible to implement, harder to understand and explain.
  2. Why not docker exec the engine binary in the image?
    • Local dirs won't work. -v /:/host almost solves this but doesn't really work on MacOS and has other tradeoffs that make it not worth it.
  3. What's the longer term plan
    • Next step would be to use the same approach but instead of pulling the cloak binary locally, docker exec it in the container image
    • That will require mainly this issue to be resolved (among a few other misc ones)
    • After that, we should try to make the remote engine long-running, possibly putting the router in the same process as buildkitd. That will require more issues, big one being figuring out session related stuff

@aluzzardi

Copy link
Copy Markdown
Contributor

This is awesome -- thanks for making a proof of concept so fast.

Haven't read the code yet, preliminary comments based on the PR description:

Build a container image that contains both buildkitd and the cloak engine (currently called localhost/dagger-engine)

  • Build it for multiple arches
  • Include cloak engine binary for each arch+os combo in each of these images

Minor thing:

@samalba expressed some concern about image size, etc. I was thinking of an alternative (not sure how good it is)

  • Each image contains a single arch+os combo for both binaries
  • SDK pulls (at most) twice:
    • Default platform for the "runner" (buildkitd)
    • It's own platform to copy the binary to the host
  • Go now also does this (it doesn't use the embedded engine). This gives us a path to get rid of the sdk dep on engine and thus the replace directives

🎉

3. When it does this, it tells the local engine binary which image to use (currently via a command line flag, which is confusing but will clean that all up).

Shouldn't the local engine binary already know which image to use (e.g. it's own version)?

  • Shell out to docker run <image ref> cat /usr/bin/cloak-<os>-<arch> and write output to XDG_CACHE_HOME/dagger/cloak-<image sha> (with the standard practice of writing it to a tmp file and then renaming it to the final dest)

nit: rather than cat'ing they could cp directly?

docker run <image ref> --name dagger-runtime && docker cp dagger-runtime [...]

Not that it matters that much actually -- SDK code is a little bit trickier to read from stdout and stream to a file rather than running a one-off cp command (easy in Go with io.Copy, no idea on other langs)

There's a few more details we might add (maybe verify the checksum of the binary, support using a user-specified binary rather than one obtained from the image, etc.), but that's the major stuff.

Especially to continue making this working on dev a breeze.

  • This is why the current implementation has the SDK only obtain the cloak binary, not actually start the remote dagger-engine container too (doing that currently requires flock).

Just a small nit: we might want to use the "future" nomenclature right away and have these 2 binaries:

  • dagger-runner (basically buidlkitd)
  • dagger-engine (the cloak binary)
  • However, this creates sort of a "two-staged bootstrap" between the SDK and the cloak engine binary itself which I really don't like at all. In the next clean-up pass I'll see what, if anything, can be done to simplify this.

Oh, I get why it's cat rather than cp now.

Long term, do we want the SDKs run the engine OCI image themselves (once it's long running and there's no more local process to copy)?

If that's the case -- wouldn't it make sense to rip off the bandaid and do it now?

We can find ways to make it easier -- for instance, our bootstrapper creates a volume. Instead we could just declare a VOLUME in Dockerfile and call it a day.

But there might be a ton of edge cases though -- in which case maybe it's fine to start with this.

@sipsma

sipsma commented Nov 3, 2022

Copy link
Copy Markdown
Contributor Author

SDK pulls (at most) twice:

Yeah I think at least splitting this up by architecture makes sense. I suspect 99% of our users right now are just defaulting to running dagger in their local docker daemon, in which case the architecture will always match.

Splitting also up by OS has some weirdness in terms of breaking the symmetry of the implementation (there's no base buildkitd for darwin), but we definitely can do that too. At that point we may be splitting hairs in terms of performance. I'll see how big the binaries are and go from there.

Shouldn't the local engine binary already know which image to use (e.g. it's own version)?

Yeah, and we could still rely on that, it just ties in to the "two-staged bootstrap" thing I mentioned, which gives me a headache to think about. It's conceptually easier to just have one version that gets passed from sdk->engine, but maybe I'll wake up tomorrow and this will make more sense and not be a big deal. I'll do whatever results in the simplest implementation for now.

nit: rather than cat'ing they could cp directly?

My motivation was that you have to do a docker create first in order to do a docker cp. That in turn means you have to put a docker rm in a defer to make sure the container is cleaned up. But I did that and then when I was running tests I ctrl-C'd the test run and saw afterwards a ton of created containers that never got cleaned up. I guess ctrl-C SIGKILL'd the processes and the defer never ran or something? I was surprised by it, but that's what I saw at the time.

Either way, docker run has the --rm option, which handles all that for us and thus has less code, so I just switched to that. I see what you're saying about it not being as easy in other languages. If cp ends up being easier there, that's totally fine; we can either switch Go back to using that (and handle the cleanup more carefully) or accept differences between the SDK implementations.

Especially to continue making this working on dev a breeze.

Just a small nit: we might want to use the "future" nomenclature right away and have these 2 binaries:

Sounds good on both accounts 👍

Long term, do we want the SDKs run the engine OCI image themselves (once it's long running and there's no more local process to copy)?
If that's the case -- wouldn't it make sense to rip off the bandaid and do it now?

Totally agree and that was my starting point point actually. But then I remembered we used flock to synchronize the provisioning and I found out that flock isn't available in node's stdlib (there's an old package that provides it through use of c++ code, but I saw someone complaining it doesn't work any more and hasn't been updated). I didn't check python yet (but IME python has pretty broad coverage of the whole syscall interface).

I was planning on revisiting this on my next passthroughs of the code. I'll see if we can get the synchronization we want w/out flock or other weirdness while also not making the implementation really complicated.

@sipsma

sipsma commented Nov 3, 2022

Copy link
Copy Markdown
Contributor Author

Here's a fun problem, completely independent of all the stuff about how we distribute/package the helper.

Current world (before introduction of new SDKs and only depend on moby/buildkit image):

  1. When we provision dagger-buildkitd, we check to see if there's an existing container running with the expected configuration. If there is a mismatch in configuration (either image ref or other configs), we replace the existing dagger-buildkitd with the expected one.
    • The replacement uses flock to handle concurrency issues
    • However the lock only lasts during the replacement, not after when solves are actually being sent to buildkitd
    • So, If two clients run on the same machine with different versions and opinions of what the "right" configuration of dagger-buildkitd is, then they can stomp on each other, replacing dagger-buildkitd
  2. The above problem isn't a huge deal since it's a pretty obscure case to be running parallel builds with different versions of our Go SDK

New world (where we support multiple SDKs, such as Go+Python, and depend on our own engine image):

  1. The same situation as before exists, but now it's somewhat worse:
    • It's much easier for two SDKs to be out of sync with each other in terms of which engine configuration is the "right" one. If we don't release SDKs in lockstep and users don't upgrade them all in lockstep, then if they try to use two SDKs on the same machine that disagree, they will stomp all over each other.
  2. It's possible that we may push changes to the engine that are backwards compatible with specific SDK versions. Therefore we should probably pin engine versions to SDK versions and upgrade them in lockstep. This is less straightforward though since it's not like Go where the engine was just an embedded library dependency.

Here's my current thinking in terms of how to tackle some of these problems (and the one place where it breaks down):

  1. Engine "releases" happen independently of SDKs and consist of pushing new layers/tags to our container registry.
  2. SDK dependencies on engine take the form of hardcoded strings for the image SHA of the engine
  3. When an SDK needs to provision an engine
    • It does docker run --name dagger-engine-<sha> -v dagger-engine-<sha>:/var/lib/buildkit <rest of options> <image sha>
    • If the above fails with an error indicating it was already running, then that's cool, we use it as is
    • Use docker cp to get the helper binary out of it (and namespaces the binary in the local cache w/ the SHA)

Pros:

  1. SDKs will always use an engine they are known compatible with (i.e. not :latest and hope for the best)
  2. SDKs that haven't been updated to the same engine dependency won't stop all over each other, replacing each other's dagger-engine

Cons:

  1. Garbage collection - how do we prevent this model from resulting in containers and volumes accumulating forever? How can we safely remove old ones without stomping over older sdks that might still use it?
    • Same question applies to locally cached helper binaries, though that's more of a temporary issue, goes away with remote engine. The above problem doesn't go away with a remote engine.
  2. /var/lib/buildkit state is namespaced by engine release, so caches are invalidated each release
    • This is more mixed; in some cases this may actually be a good thing as there have been several occasions in the past where buildkit was accidentally incompatible with caches from older versions.

Another possible solution: don't care about this. Tell users that all the SDKs on a given machine must be updated to the latest release in order to work. This means that whenever we update the engine we need to update each of our SDKs with the new dependency in lockstep as much as possible.

I might be okay with that in the short term, but in the longer term I think we need a better story than that.

@sipsma

sipsma commented Nov 3, 2022

Copy link
Copy Markdown
Contributor Author

Talked to @aluzzardi about the above issue, there's no great solutions right now but for sake of time I'm just going to go with the "one container per version" approach and have the SDK remove any other engines it sees. Essentially always garbage collect anything besides your own container which you assume is the one and only true latest version. This means that:

  1. When we release a new engine, we should update SDK dependencies on that new engine very close to one another.
  2. Document this for users
  3. Come up with a better plan in the long run

This gives us more time to figure out better approaches and interfaces for solving this problem. It also can be layered on top of fairly easily (with various more "intelligent" garbage collection approaches) if we decide we are willing to pay the complexity cost of that.

@sipsma
sipsma force-pushed the engine branch 8 times, most recently from 7df7d7c to de192af Compare November 7, 2022 18:06
@sipsma sipsma changed the title [WIP] Engine Image Engine Image Nov 7, 2022
@sipsma
sipsma marked this pull request as ready for review November 7, 2022 19:17
Comment thread internal/mage/engine.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I was thinking of standardizing this to sdk:*:publish -- to avoid confusion with releasing (cutting the tag etc)

Comment thread internal/mage/engine.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this won't work on Mac

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It works, just double checked again on my mac directly. engineContainer always uses linux as the base OS (since that's all we support), specifying darwin as an os here only results in darwin helper binaries being include in the image.

Comment thread internal/mage/engine.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this is going to be the dev process going forward right? Start this, export, and do your thing?

What happens to the rest of the CI code that uses the Go SDK? Do we need to do this as well? #3704

nit: Start? Dev?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this is going to be the dev process going forward right? Start this, export, and do your thing?

Yeah this is the baseline. I also included engine:test that does this and then runs all the core/integration tests as a convenience, but in general you can use this target and then export DAGGER_HOST and do whatever you want from there.

What happens to the rest of the CI code that uses the Go SDK? Do we need to do this as well? #3704

Here's what I'm imagining for CI in general, just as a barebones starting place:

  1. For our engine tests, we always build the local engine and run core/integration against that
  2. For each SDK we:
    1. Have a run that runs outside of dagger-in-dagger (i.e. the same ways users will actually run the SDK)
      • This gives us coverage of their provisioner code and verifies they work against their current hardcoded engine dependency (i.e. the image ref+sha they use by default)
    2. Have a run that runs inside dagger-in-dagger, where dagger has been provisioned using the latest engine built from local code
      • This lets us verify the SDKs against the latest engine without having to actually push it to a registry anywhere and without having to implement the extra docker-container engineconn in every SDK (only needed in go).

I want to double check that there's no weird catch 22 cases where we might want to push engine updates that are backwards incompatible w/ SDKs without necessarily having updated the SDKs yet. I think worst case scenario we could make the test runs of SDKs against the latest engine "warning-only" if they fail.

nit: Start? Dev?

Sure I'll change to dev

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to capture discord discussions, the plan will be:

  1. Engine tests will run against main engine only
  2. Each SDK will be tested via dagger-in-dagger against main engine only
  3. There will be separate test suites that exercise the provisioning code of the SDKs.
    • These can run dagger-in-dagger once we have support for mounting a docker socket in. In the meantime they may just be manually executed to start with.
    • These tests will provision main engine which has been pushed to some local registry. This avoids catch 22s of incompatible api changes
  4. When we release an SDK we will also run those provisioner tests except against the actual engine dep in the SDKs, not main. These tests will block the release if failed.

Comment thread internal/mage/engine.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we continue using ./...?

With this change we are not longer testing e.g. ./router/merge_test.go

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh I forgot that there were more tests under router.

Yeah I'll update to do ./... which will also include running the Go SDK tests against latest engine for now. See my other comment for the longer term idea on how to test each SDK. But there's no harm in ./... at the moment.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I'll update to do ./... which will also include running the Go SDK tests against latest engine for now. See my other comment for the longer term idea on how to test each SDK. But there's no harm in ./... at the moment.

Since it's a different go module, ./... doesn't include that

Comment thread internal/mage/engine.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

related to the other question. Should we either:

  • Update all tests using the Go SDK to spin up a local engine. OR
  • Leave as is and let the Go SDK use the embedded Engine (for now)

@aluzzardi aluzzardi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚢

@sipsma
sipsma merged commit 59ae6e0 into dagger:main Nov 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants