Skip to content

Support for async execs. - #2214

Merged
sipsma merged 1 commit into
dagger:mainfrom
sipsma:async-task
May 2, 2022
Merged

sipsma merged 1 commit into
dagger:mainfrom
sipsma:async-task

Conversation

@sipsma

@sipsma sipsma commented Apr 16, 2022 •

Copy link
Copy Markdown
Contributor

This adds a new task type called AsyncExec which has a similar interface
as Exec, but unblocks once the exec has started rather than waiting for
it to complete. A separate type, StopAsyncExec, can be used to stop it
explicitly. If it isn't stopped, then it will be killed once the dagger
client shutsdown.

This is intended for creating ephemeral services used by other tasks in
the DAG, such as a DB against which tests can be run in different tasks.

AsyncExecs cannot output state and any state they create while running
will be thrown away once the DAG finishes executing. The only exception
is if they use a shared cache mount, in which case state will be applied
to the cache mount and accessible by other Execs, async or not.

There is currently an issue with Buildkit where if the dagger client
exits ungracefully without running cleanups, then the container will
leak and keep running in Buildkit. There is also no way for a subsequent
client to query what containers are running and delete any leaked ones,
so the only remedy in this case would be restarting buildkitd. This is
an issue that needs to be fixed Buildkit-side.

Signed-off-by: Erik Sipsma [email protected]

@sipsma

sipsma commented Apr 16, 2022 •

Copy link
Copy Markdown
Contributor Author

I wanted to open this open quickly (hence the draft) because I want to double check if the way I'm setting up an explicit dependency is actually sound:

dagger.#Plan & {
 	actions: {
 		test: {
 			image: core.#Pull & {
 				source: "alpine:3.15"
 			}

 			asyncExec: core.#AsyncExec & {
 				input: image.output
 				args: [
 					"sleep", "30",
 				]
 			}

 			sleep: core.#Exec & {
 				input: image.output
 				args: [
 					"sh", "-c",
 					#"""
 						echo taking a quick nap
 						sleep 1
 						"""#,
 				]
 				always: true
 			}

 			stop: core.#StopAsyncExec & {
 				exec: asyncExec
 				_dep: sleep
 			}
 		}
 	}
 }

Above you can see the explicit dependency set on the line _dep: sleep. It results in the stop action waiting for the sleep action to finish before running.

The thing is, _dep is not a field I have defined in #StopAsyncExec. In fact, this seems to work with any private field, i.e. you could write _foobar: sleep and get the same end effect of creating an explicit cue/flow dependency but without interfering with anything else. The only requirement is that it's _private.

I feel like I'm missing something because it seems too easy, but it does work at least in this case AFAICT. I also tested briefly and found it worked for setting up multiple deps like _dep: [sleepA, sleepB]. It's additionally nice in that there's no chance of conflicts because any hidden fields in #StopAsyncExec won't be visible and thus can't conflict with the hidden field in the struct being unified with.

My question is if this can be a solution to the problem of setting up explicit dependencies in general? Or (more likely) am I missing something that prevents us from using this everywhere.

@jlongtine

Copy link
Copy Markdown
Contributor

@sipsma This should work! But it does have some caveats. If stop weren't a CUE task, but rather an "action" or similar, this would not work. The big issue with explicit dependencies in general is that they only work CUE task <-> CUE task. And thus, when we have higher level actions such as build: docker.#Build, we can't depend on that field.

@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.

This is awesome -- thank you.

Left a minor comment, otherwise code LGTM

Pinging @helderco / @shykes for CUE API review

Comment thread plan/task/exec.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.

random suggestion: if it helps avoiding duplicating code, we could do something like:

Register("Exec", func() Task { return &execTask{} })
Register("AsyncExec", func() Task { return &execTask{async: true} })

And then use the same task for both sync and async

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.

In this case it won't help more as all the deduplication already happens via the parseCommon func called by both methods, but that's a good idea in general to take advantage of struct params when helpful

@helderco

Copy link
Copy Markdown
Contributor

Instead of a separate AsyncExec, can we have an async: bool field in the normal Exec?

@sipsma

sipsma commented Apr 19, 2022

Copy link
Copy Markdown
Contributor Author

Instead of a separate AsyncExec, can we have an async: bool field in the normal Exec?

I think this is possible but I went with the separate types because even though there is a lot of overlap between the two, there are fields and requirements that are mutually exclusive to one or the other, e.g.:

  1. normal Exec supports output, but AsyncExec doesn't
  2. AsyncExec can be stopped by StopAsyncExec, but a normal Exec can't.
  3. AsyncExec inherently runs as though always is true (its results can never be cached)
  4. AsyncExec can support spawning exec'ing processes inside the container at arbitrary points after the start (not implemented yet).
  5. AsyncExec can support plugging arbitrary streams into the stdio of the process, even the client's tty (not implemented yet)
  6. AsyncExec doesn't support secret env vars right now (the underlying mechanism just wasn't implemented in Buildkit yet).

If we made async a bool field we could enforce all those requirements in the task implementation, but I guess that would be a runtime assertion whereas defining them as separate cue types is a "compile-time assertion" (in a way). It also might be more confusing to users.

Let me know if you disagree of if there's a way of approaching this with cue that I'm not aware of.

@helderco

Copy link
Copy Markdown
Contributor

I see. My problem is that we have a lot of definitions on top of core.#Exec (e.g., docker.#Run, bash.#Run, etc....). We want to encourage importing from universe.dagger.io not dagger.io/dagger/core, so just wondering about duplication in the higher lever packages.

@sipsma

sipsma commented Apr 19, 2022 •

Copy link
Copy Markdown
Contributor Author

I see. My problem is that we have a lot of definitions on top of core.#Exec (e.g., docker.#Run, bash.#Run, etc....). We want to encourage importing from universe.dagger.io not dagger.io/dagger/core, so just wondering about duplication in the higher lever packages.

Ah sure, I can see the concern. The thing is, if we go with the async: bool field here then presumably we will also have similar async: bool fields for all the higher-level packages, so those packages will also have the same differences between sync and async execs as the lower-level tasks in core. But at that point I'm not sure how we could enforce the various requirements (like that bash.#Run can't have an output set if async: true) because it won't be a task implemented in go.

So even though I see the ugliness of having to maintain things like bash.#Run and bash.#AsyncRun, I'm wondering if it's nonetheless cleaner than maintaining the implementation of bash.#Run w/ async: false and the implementation of bash.#Run w/ async: true. Again though, I'm still in the learning phase when it comes to cue, so let me know if there's a clean way of dealing with this type of issue.

EDIT: Actually, I just remembered the if statement in cue and tried it out quickly to see if it's possible to conditionally define fields based on the value of another one. Worked in my very quick test, I'll go see if we can use this for uniting sync+async Exec while retaining type safety. Will update

@sipsma

sipsma commented Apr 19, 2022

Copy link
Copy Markdown
Contributor Author

@helderco I tried out combining the two types using async: bool and cue if statements. It almost works perfectly but does have some downsides in certain cases. One example is that if you have another cue type that specifically needs an exec with a certain async value (i.e. StopExec requires that it's provided one with async: true), then that can only be checked at runtime unless the user explicitly sets the async value.

In practice, this means that if you accidentally try to stop an Exec where async has defaulted to false, you won't get an error until after the sync exec has finished executing. This is as opposed to maintaining a separate Exec and AsyncExec where that type of user-error is always caught immediately on invoking dagger do.

In terms of higher-level packages, I actually don't think having separate Exec and AsyncExec definitions means we necessarily have to have separate docker.#Run and docker.#AsyncRun types. That would be an option, but we could also choose to instead support an async: bool flag in those packages and use if statements to switch between the two underlying definitions from core. In that sense, I guess keeping the types separate in core gives us the most flexibility for both approaches in higher-level packages.

@helderco

Copy link
Copy Markdown
Contributor

we could also choose to instead support an async: bool flag in those packages and use if statements to switch between the two underlying definitions from core

Yes, that was my second thought in case doing it in core isn't ideal.

@sipsma
sipsma force-pushed the async-task branch 3 times, most recently from 856ba8b to 9e87ead Compare April 19, 2022 23:20
@sipsma
sipsma marked this pull request as ready for review April 19, 2022 23:20
@sipsma
sipsma requested review from a team, helderco and shykes as code owners April 19, 2022 23:20
@sipsma

sipsma commented Apr 29, 2022

Copy link
Copy Markdown
Contributor Author

Pinging @helderco / @shykes for CUE API review

Re-pinging. Realize our main focus right now is elsewhere, but this new feature would be quite useful for some other things we are working on, such as being able to test complex workflows involving cache import/export (as described here). If we want to put this on hold I understand too though and can just use it in my fork for now.

@shykes shykes 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.

Thanks for the ping @sipsma

  1. I agree this feature is much needed!

  2. CUE API seems fine. I feel obligated to ask whether you considered making it a special case of #Exec since it has so many fields in common.

  3. How exactly will we define "async" to developers, and explain when to use one versus the other?

  4. Developers will ask: "why can't I kill a synchronous exec?" What will we answer?

  5. Any thoughts on how we might integrate this in docker?

Thanks!

@shykes

shykes commented Apr 29, 2022

Copy link
Copy Markdown
Contributor

(I just realized my point 2. has been addressed in earlier comments)

Comment thread pkg/dagger.io/dagger/core/exec.cue 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.

Not necessary, but we could use another (probably hidden) definition to pull out the commonalities between #Exec and #AsyncExec.

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.

Yeah I actually did that in an earlier revision but backtracked because I felt like it made it more difficult to know all the fields in each definition; you had to jump between the main def and the hidden separate one. No clear right answer though so let me know if you disagree.

@jlongtine

Copy link
Copy Markdown
Contributor

Also, just wanted to note that I'm excited to have this! It'll unblock the changelog.com config that's been in stasis for while longer than I'd like.

@sipsma

sipsma commented Apr 29, 2022

Copy link
Copy Markdown
Contributor Author

How exactly will we define "async" to developers, and explain when to use one versus the other?

Here's a first shot, can expand in documentation followups to this PR:

AsyncExec should be used for "sidecar" services and fixtures that assist the execution of other tasks in an action. Whereas an Exec is used to run synchronous commands with cache-able outputs, such as building code or executing a test, an AsyncExec has no FS output consumable by other tasks. Additionally, it will be considered "completed" once it has started successfully rather than blocking until it exits. It can be stopped using the StopAsyncExec task if needed; otherwise it will be stopped when the current plan finishes.

Example use cases include:

  1. Running a database that's used by test cases running in other tasks
  2. Running a daemon that synchronizes the state of a shared cache mount with some external backend

Developers will ask: "why can't I kill a synchronous exec?" What will we answer?

The output of a synchronous Exec task can be cached and is thus expected to be a function of its own definition and inputs, which serve as its cache identity. Allowing arbitrary other tasks to terminate an Exec at any time would mean that the output the Exec is strongly determined by something other than its own definition and inputs, thus making it unsafe to cache.

^^ This kind of ignores more subtleties to the issue here. BuildKit/Dagger doesn't actually force an ExecOp/Exec to be 100% hermetic, it tries to strike a balance between hermeticity and usability. This is why you can talk to the internet, tell the time, read from /dev/random, etc. The problem is that allowing async killing of an ExecOp would be such a huge violation of hermeticity that it's not worth enabling. We could document these subtleties too, though it might be too much detail for just the AsyncExec docs.


Any thoughts on how we might integrate this in docker?

I mean on the most basic level we can obviously make a type that accepts a docker.Image as the input rather than just FS. Other than that I don't currently see much else that would make sense to specially integrate, but would have to think about it more.

@shykes

shykes commented May 2, 2022 •

Copy link
Copy Markdown
Contributor

Thanks for the details @sipsma . I think calling them #Start and #Stop might be more intuitive for developers and aligned with your explanation. wdyt?

Wrappers would be docker.#Start and docker.#Stop, which matches the docker terminology as well.

@sipsma
sipsma force-pushed the async-task branch 3 times, most recently from 9bb891b to aea314e Compare May 2, 2022 19:40
This adds a new task type called Start which has a similar interface
as Exec, but unblocks once the exec has started rather than waiting for
it to complete. A separate type, Stop, can be used to stop it
explicitly. If it isn't stopped, then it will be killed once the dagger
client shutsdown.

This is intended for creating ephemeral services used by other tasks in
the DAG, such as a DB against which tests can be run in different tasks.

Start cannot output state and any state they create while running
will be thrown away once the DAG finishes executing. The only exception
is if they use a shared cache mount, in which case state will be applied
to the cache mount and accessible by other Execs, async or not.

There is currently an issue with Buildkit where if the dagger client
exits ungracefully without running cleanups, then the container will
leak and keep running in Buildkit. There is also no way for a subsequent
client to query what containers are running and delete any leaked ones,
so the only remedy in this case would be restarting buildkitd. This is
an issue that needs to be fixed Buildkit-side.

Signed-off-by: Erik Sipsma <[email protected]>
@sipsma

sipsma commented May 2, 2022

Copy link
Copy Markdown
Contributor Author

I think calling them #Start and #Stop might be more intuitive for developers and aligned with your explanation. wdyt?

Yeah I like that, updated with it. I would actually argue that along these same lines #Run might be a better name than #Exec, but that's probably best left as a different issue (and also not a big deal anyways).

@jlongtine jlongtine 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.

LGTM! :shipit:

I'd love to chat some more about networking (single node to start) with this sometime soon!

@helderco helderco 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.

LGTM! 🚀

@sipsma
sipsma merged commit 4fc38da into dagger:main May 2, 2022
@marcosnils

marcosnils commented May 3, 2022 •

Copy link
Copy Markdown
Contributor

👋 arriving a bit late to the party here.

I love this feature and it's a great work indeed, congrats @sipsma!.

Looking at the conversation the following comment raised my attention:

it will be considered "completed" once it has started successfully rather than blocking until it exits

I'll bring a past experience that probably @shykes @samalba and @aluzzardi remember from the docker-compose early days about service dependency healthyness. The situation pretty much summarizes to this:

What happens if my async task starts but it shortly exists due to a transitory error? Dagger is going to mark the action as completed but then my tests are going to fail (or hang forever) because the async task exited with an error without me knowing about it.

I believe it's worth challenging this UX to see if we can do better than docker-compose this time to avoid going through the same service dependency/healthiness limbo we experienced with compose.

ref: https://docs.docker.com/compose/compose-file/compose-file-v3/#healthcheck

@shykes

shykes commented May 3, 2022 •

Copy link
Copy Markdown
Contributor

I agree that healthchecks is an important part of the DX for this. We should take responsibility for it, and not consider the feature completed until that dimension is successful. I love this.

In terms of implementation, I want to make sure we keep all our options open. In particular, the more can be done in pure CUE, as opposed to hardcoded in the engine, the better.

I think compose was not able to fully solve the problem, precisely because it doesn't have the luxury of a programmable platform: the only way for docker healthchecks to work in every application, is to implement everything in the core. We have the luxury of not doing that.

@marcosnils

Copy link
Copy Markdown
Contributor

and not consider the feature completed until that dimension is successful. I love this.

agree. I'll create an issue to track this. It'd be great to catalog / group it under the async exec epic? cc @mircubed

In terms of implementation, I want to make sure we keep all our options open. In particular, the more can be done in pure CUE, as opposed to hardcoded in the engine, the better.

+1. I haven't fully processed the current implementation yet, I'll take a close look tomorrow 🙏

I think compose was not able to fully solve the problem, precisely because it doesn't have the luxury of a programmable platform: the only way for docker healthchecks to work in every application, is to implement everything in the core. We have the luxury of not doing that.

good point. I'm eager to see how we could compose (cuack) async execs with high level actions that already include their "curated" healthchecks out of the box. That'd be awesome!

@shykes

shykes commented May 3, 2022

Copy link
Copy Markdown
Contributor

By the way, another dimension which I am equally excited about is networking, more specifically client side proxying. In theory you can already hack together a compose equivalent with the current version, but at at a cost which I consider to be too high: losing magical infrastructure independence. There is only one reliable portable way to expose a port from a Dagger container to the outside world, and that is through a client proxy. Implementing that will have major, MAJOR implications for Dagger as a platform.

@sipsma

sipsma commented May 3, 2022

Copy link
Copy Markdown
Contributor Author

Yeah I agree healthchecks are an important higher-level construct. Right now you'd implement them as a separate task that has a dependency on the async exec starting successfully. Then, instead of having other tasks put their dependency directly on the core.#Start, you'd have them put their dependency on the separate healthcheck task.

I'd argue that this is the right approach vs. trying to put something specifically inside the core.#Start definition. It gives the most flexibility for higher level packages outside of core. Those higher-level packages can wrap the core.#Start and whatever healthcheck task they want into one single definition that's used together, so the end users aren't exposed to any of the underlying complexity.

@sipsma

sipsma commented May 3, 2022

Copy link
Copy Markdown
Contributor Author

By the way, another dimension which I am equally excited about is networking, more specifically client side proxying

Just to double check, do you mean that the dagger client (i.e. whatever is running dagger do) would listen on the port and then forward any incoming traffic to the container listening on the port? Makes sense if so. I have been thinking more about the case of just containers talking to each other so far, hadn't thought about the "outside world" yet...

@shykes

shykes commented May 3, 2022

Copy link
Copy Markdown
Contributor

Yeah I agree healthchecks are an important higher-level construct. Right now you'd implement them as a separate task that has a dependency on the async exec starting successfully. Then, instead of having other tasks put their dependency directly on the core.#Start, you'd have them put their dependency on the separate healthcheck task.

I'd argue that this is the right approach vs. trying to put something specifically inside the core.#Start definition. It gives the most flexibility for higher level packages outside of core. Those higher-level packages can wrap the core.#Start and whatever healthcheck task they want into one single definition that's used together, so the end users aren't exposed to any of the underlying complexity.

I agree :)

@shykes

shykes commented May 3, 2022

Copy link
Copy Markdown
Contributor

By the way, another dimension which I am equally excited about is networking, more specifically client side proxying

Just to double check, do you mean that the dagger client (i.e. whatever is running dagger do) would listen on the port and then forward any incoming traffic to the container listening on the port? Makes sense if so.

Yes 👍

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.

6 participants