Repository navigation
Project Commands - #5060
Project Commands#5060
Conversation
There was a problem hiding this comment.
Have you thought about of having each of these magically take a *dagger.Client arg? Seems like it could make the DX more seamless, saving 5 lines per function, which in some cases is >50% of the function.
You wouldn't be able to pass different options to each client anymore, but I wonder if we could go down a path where you just don't need to set those options anymore, and it seems like at least some of them could be configured unilaterally across all entrypoints (e.g. log output).
There was a problem hiding this comment.
Yes totally, didn't get to it yet but it should be very easy, dagger.Serve can just construct the client in dagger.Serve and pass it here.
I was also considering whether we might want to do something like have the first param be ctx dagger.Context, which implements the context.Context interface but also has an extra method like .Client(). Just to reduce the number of boilerplate args users need to write.
You wouldn't be able to pass different options to each client anymore, but I wonder if we could go down a path where you just don't need to set those options anymore, and it seems like at least some of them could be configured unilaterally across all entrypoints (e.g. log output).
Yeah I don't think you'd almost ever need to set those, and if you really really want to you still have the escape hatch of creating your own client manually anyways.
There was a problem hiding this comment.
Oh another idea along this vein before I forget, we could also have those dagger.Clients be pre-populated with Pipeline settings that match the name of the entrypoint (including hierarchies of them when invoking subcommands)
There was a problem hiding this comment.
Oh another idea along this vein before I forget, we could also have those
dagger.Clients be pre-populated with Pipeline settings that match the name of the entrypoint (including hierarchies of them when invoking subcommands)
Yes. Please. I love this idea!
There was a problem hiding this comment.
Part of my latest updates today included dagger.Context with a .Client() method. I didn't get around to trying to add a pipeline labels automatically yet, but that should be pretty straightforward.
Also need to think about what the equivalent of this would be in Python. At least the magic pipeline labeling should also work there too, though the need to reduce client creation boilerplate probably doesn't apply.
There was a problem hiding this comment.
Also need to think about what the equivalent of this would be in Python.
May I suggest checking out how airbyte does it? They have a whole entrypoint system built on the Python SDK. Can’t hurt to look at how they pass the client around.
There was a problem hiding this comment.
Also need to think about what the equivalent of this would be in Python. At least the magic pipeline labeling should also work there too, though the need to reduce client creation boilerplate probably doesn't apply.
I can help you there. When I think about doing a limited schema based on CLI, I imagine creating a high level interface that uses typer (like Mage; we're using it for running codegen and extensions schema) and Strawberry underneath.
When you create a Typer app, you can create a context which is shared in subcommands. So a single dagger connection can be established in the beginning, including config, and shared.
Something like this:
import dagger
app = dagger.Project()
@app.command()
async def build(ctx: dagger.Context, foo: str) -> str:
base_image = ctx.client.container().from_("golang:1.20-alpine")
...
@app.command()
async def test(ctx: dagger.Context, bar: str) -> str:
...
if __name__ == "__main__"
app()Or using classes:
import dagger
class Project(dagger.Project):
@dagger.command()
async def build(foo: str) -> str:
base_image = self.client.container().from_("golang:1.20-alpine")
...
@dagger.command()
async def test(bar: str) -> str:
...
app = Project()
if __name__ == "__main__"
app()The last bit of boilerplate can be hidden away in the container runtime, but that implies having a fixed name for this variable:
if __name__ == "__main__"
app()There was a problem hiding this comment.
@helderco I almost missed your comment here, that looks great! I was planning on asking you eventually about whether you'd think it'll make sense to create our own thin layer on top of strawberry to enable more dagger-specific niceties like this (while still being able to re-use strawberry underneath the hood as much as possible), sounds like the answer is yes :-)
There was a problem hiding this comment.
+1 to removing boilerplate if we can!
|
What is the UX for creating the JSON file here? From the examples it looks like it was pre generated. Additionally if the schéma is truly internal, then the use facing commands should either use executables or source files, and generate and cache the JSON on the fly. Additionally the issue of the default target doesn't seem to be addressed. What is the thought there? |
|
@robertu94 Thanks for the comments! I was planning on going point-by-point through the preceding issue today to pick up everything I missed in terms of requirements and suggestions, so apologies if any of my responses here overlap with what you've already suggested. Really appreciate all your feedback on this topic, it's genuinely incredibly helpful to have those overviews of the landscape and pros+cons of each approach!
Yeah dagger.json is leftover from our prototypes a while back. The idea is for it to be primarily read+written through a CLI interface while remaining human readable if you want to inspect it directly. There are some examples of usage in the original PR, but take that all as very preliminary and up in the air. Also, I need to revive the code in that PR as it got moved around and got deleted at some point as we shifted priorities over the last few months. So if you have any suggestions around this approach or ideas on totally different approaches now is the perfect time!
dagger.json actually doesn't hold the schema (at least currently, maybe it should). It holds basic metadata like the name of the project, which language the project is using, etc. It also can hold dependencies this project has on others, but that whole aspect isn't yet needed for just entrypoints; it'll become relevant again when we expand out to support the more generic "extensions" idea. The schema is generated internally (it's a graphql schema file) and actually is cached thanks to the fact that it's generated with a buildkit ExecOp (same mechanism behind That being said, we should make the schema viewable to assist power users and debugging. I added a TODO for supporting that behind a flag. I do also like the idea that dagger.json could hold the generated schema... There is a problem right now in that even trying to list available entrypoints (
Great question, added addressing that to my TODO list in the description. In general I'm seeing two possible routes:
I'm undecided, but if I had to choose at this point I'd probably go with just using Again, very open to any suggestions here! I recall you mentioning this in the other issue too, so I'll pick up your ideas there too when I go through that later today. EDIT: just realized as I read through some of your comments in the other issue there's one more obvious possibility: we could reserve a special entrypoint name like |
c72759c to
cdfe79c
Compare
There was a problem hiding this comment.
Reminder to self to uncomment all these before merging, just needed to reduce noise while I was in a loop of pushing to run GHA workflows
There was a problem hiding this comment.
I was just experimenting with event ingestion here, this target doesn't actually exist anymore. When I finish migrating the provisioning tests to an entrypoint there will be a real example of this since the payload will be needed
There was a problem hiding this comment.
This code for converting go->schema is in dire need of a cleanup. Before merging I'll try to do some basic stuff like splitting it out to multiple files and adding more comments where they are sparse.
In general it could use a bit of a refactorization too, though I will most likely save for a followup. We do need to use both ast parsing and reflection, but the current balance of the two is confusing. It would probably be better to use ast parsing as much as possible and only use reflection where required (ast parsing handles a lot of cases that reflection doesn't, like getting the actual names of function args, and also just generally has fewer quirks related to compiled/optimized code that reflection deals with)
|
@robertu94 @sipsma on the topic of default command (equivalent of the default rule in a Makefile, or default target in Dockerfile): I don’t think we need that feature. neither npm nor mage have it. I don’t think it adds a whole lot in the context of commands; it makes more sense for build tools. Just my 2c. |
|
I love that this brings back the intuitive command-oriented UX of A few notes and questions:
Then to invoke a command: |
|
Can controllers be stacked? I think they should. So for example each SDK could have a controller written in its own language (using an older stable release of itself to avoid bricking 😁), and dagger.json loads them all. The |
|
I think we should adopt the mage (and others) convention for subcommands:
|
|
I think access to host filesystem for each controller should be scoped to the directory that loaded that controller.
|
|
I think |
I've not used either mage or npm extensively, but here is where I think there is some value of providing a default: automated tooling and lower initial learning curve. If there is a default, then there is a something consistent that an IDE, script, or CI "action"/"stage"/"step" to call when integrating with Dagger instead of requiring tooling to ask what are all the available pipelines, and what their arguments may be. This means that integrations with 3rd party tools can be smaller at least initially. As for a what the default is, I would suggest run all defined pipelines. This is semantically equivalent to what the make files generated by meson, CMake, and Autotools do 1. It's also what testing libraries like GTest, Junit, pytest, etc do by default, and I'd argue that dagger's primary intended use case is more like a testing library than Mage or npm. Also I believe npm test runs all tests by default. Footnotes
|
I would hide it from the cli args, and instead just pass the project directory (it's implicit that a dagger project dir must have a dagger.json file at its root). I love the simplicity of this proposal, it's a language agnostic mage and it even feels simpler to scaffold. |
@samalba Yes totally agree, should be a trivial update to make, will do
@shykes Yes agree that "command" seems like the best match now that we have something concrete to look at. In terms of "controller" vs. "entrypoint", I am more ambivalent between the two. I am actually wondering if we even need separate terminology here. Maybe we can just refer to the implementation of the command as a command too? Most of the time I think that would be unambiguous, and in the cases where it isn't, it's easy to say "command implementation" to be clear you are referring to the code implementing the command as opposed to the more abstract "command" you type after As we start generalizing to concepts like artifacts, I feel like we could still just continue that pattern (i.e. you can refer to the "artifact implementation" if the need to disambiguate is strong). That feels like what I would naturally tend to do anyways, but let me know what you think.
Right now However, graphql introspection gives you very low-level information. It has everything you need technically but is not as easy to work with as something more high-level and static. I think giving a higher-level static schema for commands specifically is a great idea. It not only saves work for anyone trying to build interfaces on top of this, it also formalizes the contract (i.e. what is a command, what properties does it have, etc.) in the API itself rather than trying to document the map between graphql introspection and commands, which sounds like a nightmare, both for the person writing the documentation and the people reading the documentation. In terms of the implementation, I actually don't think we even need language-specific SDKs to do extra work for this. They can continue to just convert the code into a more generic graphql schema. Then, we can implement the higher-level static "command schema" in our project API. The advantage there is that we only have to implement it once in dagger's internal project code rather than asking each SDK to generate the command schema. Then, as we expand out to follow ups like artifacts, environments, tests, and eventually full-blown extensions, the SDKs don't need any more updates. They continue to just output generic graphql schemas and we do the conversion to more the more well-defined static schemas in our project API. I'll see how long the rest of the pre-merge cleanups+updates take and how much effort it would be to move to this model (it honestly might implicitly do some of the code cleanup I wanted anyways as a side-effect). Depending on that I'll either update this PR with it or do it in a follow-up ASAP.
Yeah totally agree this needs to be possible, I was putting this in the bucket of "monorepo-related issues" to tackle. One possible model is to use project dependencies as specified in This one is a big enough can of worms in terms of design that I think we should save it for a follow-up issue/discussion after this merging this PR (happy to hear more thoughts in the meantime though of course!)
Also agree, at least in terms of defaults. I think there are cases where you may want to explicitly grant access to something outside that directory (one big one being host unix sockets, which typically aren't going to be in your cwd), but that would need to be a very explicit opt-in on behalf of the caller. There's a very related discussion to be had around getting the env vars of the caller. Should be a way to for callers to explicitly pass them, but giving the command access to them all implicitly is gonna be too big a security hole. I think there's a few possible ways of modeling the explicit passing of other host resources. We could put it in the project API such that command implementations can request them in code: func MyCommand(ctx dagger.Context) error {
// placeholder api
yourSocket, err := ctx.Client().Project().CallerHostSock("/please/give/me/this.sock")
// err is non-nil if it isn't allowed
}Or we could even just make these be required args to the command, e.g.: // We'd need to update our implementation to handle types like dagger.Socket as inputs.
func MyCommand(ctx dagger.Context, yourSocket *dagger.Socket) error {
// use yourSocket...
}Which would mean the caller has to run e.g. Same idea would apply to other host dirs outside the caller's cwd, env vars, etc. I'm not sure which is best yet, but this is another thing which is probably best for a follow-up design discussion to this PR. As it stands, commands just can't access any of this, so we can loosen that up after figuring this all out. (Also going to get back on the rest of the comments around more mage-like syntax and default commands, just sending this batch out first) |
@shykes Have mixed feelings on this. I totally agree on the need for batching commands and positional args. My concerns with the mage-syntax are:
If we keep the space-separated syntax, we could support batching commands by separating by some special delimiter, e.g.
We need to figure out positional args for either syntax we land on. The idea in the back of my head has been to reserve a name func Lint(ctx dagger.Context, args []string, someFlag string)Commands wouldn't have to accept Don't love reserving names, but it feels like an okay tradeoff as long it's kept to a small set (we also currently reserve the name EDIT: Of course, another option here is to just not support positional args and always require a flag. As long as we add support for flags being a list of strings, this may actually be okay for now? |
|
RE: default commands @robertu94 @shykes A lot of considerations here (my own are shifting as I write this all out and think more). I'll also throw in an additional motivation for something akin to this which is that in the current state of this PR you always have to explicitly type a top level command out even if it only exists to accept args and then branch out to subcommands
There's definitely ways of addressing this that don't involve creating the concept of "default command" (and maybe they are preferable) but it feels like if such as concept were to exist it could be the model for solving the above problem, so it's bouncing around in my head with all this too.
There are definitely a lot of cases where this would make perfect sense, but I think there's also a lot where it may not be desired. For our own CI in dagger, it could be nice to run all the tests+lints as the default command, but we will also have commands that push official release images, publish SDK versions, etc. which we don't want to run by default
I do totally see the point here, a default command could enable "config-less" integration with other tools. But, similar to above, the fact that what makes sense as a default command could vary widely from one project to another throws a pretty big wrench into that. I think it may end up being too unstable to rely on just always running the default and instead being more safe to just have a little bit of extra explicitness, at least for now. Another thing that might help clarify the thinking here @robertu94, what we're implementing in this PR is just the first step in a series of related ideas (currently mostly just in discussions amongst the team, should be in writing in the near future). For example, one feature we will likely follow-up with are what we are currently calling "artifacts", which would be the standard Dagger interface for specifying a DAG of containers, files, etc. that a project can build. In the current imagination, a lot of the design may end up very similar to what we're doing with commands, e.g. it may just be that we also support returning func MyBinaryArtifact(ctx dagger.Context, debugSymbols bool) (*dagger.File, error) {
...
}TBD what the CLI for this would look like, but as a placeholder you could imagine maybe I think at that time we would definitely look more closely at re-using conventions from build-specific tools. We will have a lot more leeway to enforce opinions, e.g. maybe we block internet access during the execution of artifact implementations in order to enforce hermeticity of builds and eliminate some of the safety concerns around "I accidentally ran a command that published to prod". There's also talk of formalizing interfaces to deployments, running tests, etc. What we're doing here initially is more of a low-opinion starting place. |
My main concern here is one of "technical marketing". When we explain Dagger, we quickly get to an important feature: it's programmable. To add awesome CI/CD capabilities to your project, you don't write a YAML file or other weird DSL: you write code. My problem is: what word to I use to designate the code to write? On a mobile platform you write an "app"; on Github actions you write a "workflow"; with Make it's just called a "Makefile". My point is that, when explaining how Dagger works and how to use it in very broad strokes, before even getting into the specifics of command vs. artifact vs. test etc... I need a word to fill in the sentence: "To start using Dagger in your project, just choose an SDK and write your project's (blank)". In that specific context ☝️ I think "controller" is a better word than "entrypoint", because it sounds more like a special kind of program that you created with an SDK. But, of course I'm open to discussing it.
Yay! Yes that's exactly right. It should be trivial for any tool to discover and invoke a project's commands, not just the official CLI. That means it should be easy to do those things via the API. |
I agree that how exactly to make use of the stacking is a can of worms. Plenty of fun bikeshedding ahead :).
In short: lots of ways we could use stackable controllers, which we can figure out later. But, I think we should design them to be stackable from the get-go, to keep our options open. |
That's a good question. I know of the Heroku and Mage CLIs. But I don't know how widespread or controversial it is beyond those two. I just asked the Internet, to help figure it out :) If it turns out that using colons is controversial, then that would be a plus for using spaces.
Not necessarily a dealbreaker, but I agree it's a plus for using spaces.
If we stick to spaces (probably the safer choice, unless colons turn out to be incredibly popular), the main benefit is familiarity; so I would be wary of even a little deviation like allowing multiple uses of Looking at the examples, I feel like the answer to batching (assuming we stick to spaces) might be to rely on the shell's job control features:
Skipping the topic of positional args for now. I think it deserves its own issue actually. It's a small but crucial part of our CLI design, and is pretty decoupled from other topics discussed here, and even this particular PR. Awesome conversations! As planned, having a real POC to look at has really unblocked us on so many dimensions of the design. Thanks for getting the ball rolling! |
OK, I am getting good replies to that tweet, and a clearer picture is emerging:
One reply says:
|
I believe that bazel, buck, and pants all use
This is a really good point. I guess I didn't consider this because I assumed that the principle of least privilege (i.e. only CI or a few senior ops people have privileges to push to prod) would prevent the dev from accidentally pushing to prod, but that wouldn't be true in small teams. In this case, the pipeline would "fail" on the image push, and otherwise do all of the "safe things". Similar things would also apply to database migrations, website updates, etc...
I think that is a feature, not a bug. Different projects have different needs. The other default that other tools ( async def default_pipeline(cxt):
with TaskGroup(...) as tg:
tg.start_soon(fedora_pipeline)
tg.start_soon(centos_pipeline)And then you have a config-less default, and a way to ensure that only "safe" things get run as defined by the project.
this is an appealing feature at first blush, but really hard to work around in environments that weren't designed to have this from the beginning. A shocking number of packages need internet access during their configure stage. That said, it is a feature that I look forward to 😄
I've seen several tools do this, and I think it is a reasonable idea.
I like where this is going, but I would need to think about possible footguns and issues. My first thought is getting the error-handling story right, but I really haven't thought more about this. |
Ah sure, that makes total sense... In that context yeah I agree it's helpful to have separate terminology and that "controller" is more descriptive than "entrypoint". I'll think about it some more, but right now I don't have a better suggestion than controller. I don't know entirely why I have this word association with "controller", but some reason I feel like if I was reading documentation and it said e.g. "Now you just need to write the controller code for your project" I would start getting mentally prepared for writing a bunch of complicated boilerplate-y code to integrate with a framework. So if I can think of anything I like better I'll bring it up. But this is highly likely to be very particular to me and also isn't a big deal in the first place since our docs can just have examples right away showing how simple it actually is to eliminate that concern.
Awesome, thank you, incredibly helpful! Mixed opinions of course, but by eye there is a lot more opposition for
Yeah that comparison is spot on I think. Basically, instead of fighting the language, our baseline should be to accept the conventions that exist and only layer on extra niceties later after a lot more consideration and feedback. Shell job concurrency and tools like
The cool thing too is that if a user ends up with a big pile of shell, they should also be able to just refactor to add a new command that implements the same thing, but it will be in the language of their choice with cleaner syntax and better type safety. Then they can just call that from the CLI instead.
Either way, I think that last point about enabling rapid iteration and easy paths to cleaner refactorization ("incremental revolution" 🙂) will be crucial to get right. Once we get there, should probably be a guide for doing exactly that.
All the above being said, these concerns are totally valid too. If we stick with spaces, users will have to contend more often with the rules around wrapping My current synthesis of all of the above is that I'm inclined to continue with spaces for this PR and skip built-in batching support for now.
And if we do end up sticking with spaces after officially releasing this, I think there will still be the option to layer on batching via |
|
Here’s my summary of the “ask the internet about colon-separators” thread:
This makes me wonder if we should follow the same delineation ourselves? Use spaces for our own tool-defined commands, and colons for user-defined commands as programmed in the user’s controller code? |
aluzzardi
left a comment
There was a problem hiding this comment.
Looks awesome.
- Added an unrelated comment about dagger client
- Open question: Would we want to support running multiple targets at once? Without this feature, the only way to achieve parallelism (e.g. running all SDK tests at once) is to rely on CI jobs
- Sometimes it makes sense (expensive tasks are better parallelized)
- Some other times, it would be cheaper/faster to run a bunch of commands on the same job. For instance linting would make a lot of sense to run from a single job (pretty cheap, not CPU bound, tons of cache sharing between engine:lint and sdk:go:lint, etc)
- Could either be CLI-centric (e.g. "multi-do", somehow)
- Or maybe, a simpler/more naive approach is to do this in userland (e.g. define "virtual" targets that just invoke the actual targets)
There was a problem hiding this comment.
for rapid prototyping: you can point to a local path (e.g. uses: .github/actions/dagger) and have that code live in this PR until it matures enough to be split it out, if that helps
There was a problem hiding this comment.
Tried this but I'm not sure if it's working or if something else is bugging out: https://github.com/dagger/dagger/actions/runs/4943782245
Will check again tomorrow. Hopefully it does work because it would be super convenient!
There was a problem hiding this comment.
Out of scope for this PR, but since we're in the process of radically changing the DX, I'm going to put it out there:
dagger.Connect() exists for historical reasons. Those reasons are less and less relevant, maybe we could reconsider having a Client and doing a Connect?
Today:
c, err := dagger.Connect(ctx, <options>)
if err != nil {
panic(err)
}
defer c.Close()
// Do stuff with `c`
c.Container().From(...)Since client options are no longer really needed (LogOutput is kinda deprecated by TUI, Workdir is made absolute by the new Host API), what if client creation was implicit?
// Do stuff with `dagger` directly
dagger.Container().From(...)In the entrypoint case, the call would be:
func (e EngineTargets) Lint(ctx context.Context) (string, error) {
return dagger.Container().
From("golangci/golangci-lint:v1.51").
WithMountedDirectory("/app", e.SrcDir).
WithWorkdir("/app").
WithExec([]string{"golangci-lint", "run", "-v", "--timeout", "5m"}).
Stdout(ctx)
}To make it work, client initialization can happen in two ways:
- Lazy init: There's a singleton client in the library that gets initialized when needed
- Contextual: A pre-init'ed client can be available in context, in which case the SDK blindly re-uses it. This is the path for TUI and extensions, which initialize an external client
/cc @helderco
There was a problem hiding this comment.
Yep this is what I commented on #5060 (comment) 👍
There was a problem hiding this comment.
Yep this is what I commented on #5060 (comment) 👍
I did see that comment, but it was still referencing ctx.client and self.client, not sure if I missed some part?
What I'm suggesting is we don't expose client. SDK can be used "directly" without going through a client (e.g. dagger.Container() instead of client.Container()), SDK initializes a client on-demand.
Somewhat similar to the http library in Go: you can create a http.Client, or you can use http.Get which uses the default client instance under the hood.
There was a problem hiding this comment.
Yeah in my recent pushes I removed ConfigPath and NoExtensions from the engine config (not needed anymore, all the project loading is in the API and done by dagger do using the Go SDK), so those are already gone.
I think this is a great idea, but it will be important to still leave explicit client creation as an option. Mostly just for our own internal needs where we need to, e.g., setup multiple engines and then connect to each of them simultaneously (happens in remotecache tests). That doesn't have to be anything nice-to-use or obvious, just available.
There was a problem hiding this comment.
What I'm suggesting is we don't expose client. SDK can be used "directly" without going through a client (e.g.
dagger.Container()instead ofclient.Container()), SDK initializes a client on-demand.
Oh, right!
It does look nice to be able to declare pipelines without needing to pass the client around, but we’re using “Client” as an alias for “Query”. To expose that in the root dagger import, you’d have to also generate functions for each method in Query (or codegen directly as top level functions).
Most importantly, when would you close the connection?
With Go's http.Get you need to close the response body. With Python's httpx.get it makes a new connection every time. That's why I didn't even want to support it, so we don't have to put warnings like:
Why use a Client?
If you do anything more than experimentation, one-off scripts, or prototypes, then you should use a Client instance.
With the example in #5060 (comment), that's easily managed in app():
app = dagger.Project()
...
app() # manage client instanceThere was a problem hiding this comment.
when would you close the connection?
We could add a dagger.Close(). With entrypoints it can be managed automatically.
Since we don't pass a context around in Python and Node.js, it would have to be the lazy init option.
|
Super excited for this! Also this is a really fun discussion. Finally found time to catch up. @sipsma I'm keen to integrate Progrock into this now that it's merged. I can submit a PR to your branch so it doesn't get in the way or get re: "controller" cc @shykes
FWIW I was about to comment the exact same thing. My mind jumps to Kubernetes CRDs and custom controllers which makes it seem more complicated than it really is. I also don't have a better suggestion yet, other than maybe not having a special word for it strengthens the point that "it's just code," even if it results in clunkier language. But ideally we can find a word that's easy to guess. re: batching & positional args I think it would be really nice if it was easy to mimick this pattern in Bash: #!/usr/bin/env bash
go test "$@"For me this is an important ingredient for really embracing Dagger as your portable dev toolchain, so it can abstract away any complicated setup without getting in the way of running more high fidelity commands just as you might with There have been a lot of times where I want to do e.g. For me, batching is a lower priority than positional args, because as @aluzzardi pointed out:
Personally I'm unlikely to write So my vote would be to support positional args in the common way, where any extra args get passed along, and any flags passed as positional args require re: colon vs. spaces When used in combination with positional args, space-separated command "paths" can make it hard to tell where the command path ends and its args begin: dagger do sdk go test ./foo # am I running 'sdk go' 'test ./foo' or 'sdk go test' './foo'?
dagger do sdk:go:test ./foo # pretty clear that `./foo` is the only argumentOf course, using You could also argue that this is a feature, not a bug. It's kind of nifty that Another option could be dagger do sdk/go/test ./fooOne drawback is it could look like it's running a |
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
This is technically a special ability that's only available to the Go SDK, but I can't think of any harm in granting it. It's very convenient for our own internal uses cases where we want to use the Go SDK in parts of the engine code like the CLI and/or tests. Signed-off-by: Erik Sipsma <[email protected]>
This migrates the ancient project code into the modern world, it now follows the same conventions as the rest of our APIs. It also strips down the API to just what we care about right now, which are commands. Some of the deleted code here will likely need resurrection in the near-ish future (i.e. typescript runtime, support for recursively loading dependencies, etc.), but it's easier to start from a clean base and re-add that as needed. Signed-off-by: Erik Sipsma <[email protected]>
The new approach just has callers load projects, so passing those config options around everywhere was unneeded and confusing. Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
Signed-off-by: Erik Sipsma <[email protected]>
In a mergeable state, with lots of follow-ups to come.
Right now I've tested w/ Go and Python. NodeJS is a TODO.
Features/Demos
If you want to try this yourself, after pulling down this PR you should run
./hack/dev, which will build the newest dagger binary from this branch. You can then use it as./bin/dagger(the examples below just usedaggersince that's what it'll look like in "prod").CLI for CI tasks implemented in Go
Expand
To help iterate on entrypoint features, I've begun migrating Dagger's CI automation to use entrypoints implemented in Go. The progress so far is in the new
ci/directory.The targets are organized in a hierarchy of commands+subcommands, which can be explored from the CLI interface via the
--helpflags.Top-level entrypoint
ci:Available Commandsshows the available targets (engineandsdkso far)cialso takes some top level arguments for--branchand--repowhich the entrypoint implementation uses to pass some global context down to the subcommandsciwon't even need to be explicitly typed in the CLI. It will just be the default target called when invokingdagger do--branchand--repoargs are only needed because entrypoints don't yet have access to the caller's filesystem. They can be removed once that's added (though they are a good example of flags in the meantime)--branch string the name of the branch from the git repo)Including all thedaggerCLI global flags in the output is too noisy, they should probably be removed from this outputHaving to explicitly passdagger.jsonin the path should be replaced with optionally just passing the parent dir (e.g.--project ci/)Subcommands:
There's multiple available and can also be explored with the
--helpflag on any subcommand.Here's an example of executing one:
--debugflag, but they are the plain progress output and thus hard to follow. The real solution here should be to by default display them with our new fancy TUIs (cc @vito)Entrypoint Implementation
All of the targets are implemented in the
ci/directory, which is really just a Go main package plus adagger.jsonwith some minimal metadata.In the same way that Dagger pipelines are "just code", so are entrypoints. You just write some functions and the Dagger SDK automatically converts that into the CLI interface under
dagger do.Basic Example (no subcommands)
Before going into the
cicommand hierachy, here's a starter example where each entrypoint is just a function:Each function will become a command available to
dagger do.Buildbecomes abuildcommand,Testbecomestest, etc.The function's first arg is required to be
dagger.Context. This implements the standardcontext.Contextinterface but also has a.Client()method with a pre-created dagger client to use.Arguments become flags, e.g.
build --foo $MY_FOO_VAL. The firstctx dagger.Contextis excluded from that rule. It's also valid to take no args.Improvements Coming Soon™️:
errorrather than always having to return something elseClientshould be pre-populated withPipelinelabels that match your entrypoint's namedagger do ciimplementation (with subcommands)For Dagger's CI, we want a hierarchy of commands and the ability pass configuration+context from parent commands to subcommands. This doesn't end up complicating the code very much though.
In
ci/main.gowe define the top levelcientrypoint and the subtargets available under it,sdkandengine:CIfunc accepts the--repoand--branchflags we saw before in the--helpoutput. It uses those with the dagger client to create aDirectoryobject, same as any existing pipeline code would.Directorydown to subcommands, so it returns a structCITargetswhich holds configuration that should be propagated.sdkandengineand defined by just adding methods toCITargets.CITargets,sdkandenginehave access to theDirectorycreated byCI(in theSrcDirfield).The implementation of the rest of the targets are split up into separate files in the package. Here's the implementation of Python SDK targets (with some truncation for better readability, full file is in PR):
(s SDKTargets) Pythonmethod defines thepythonsubcommand onsdk.SrcDirreceived from its parent command and create a common base image that will be used across the rest of its subcommands, passed once again just through a struct (PythonTargets)Linttarget is defined as a method onPythonTargets, which reuses config from its parents and actually does the linting."Hello World" Python entrypoint
Expand
Entrypoints will be supported in all of our official Dagger SDKs. Similar to our clients, there is also a common API underneath them all which enables 3rd party implementations of entrypoints, both for different languages and even for languages already supported if different structures/approaches are desired.You can see a very basic but working python example in
demos/python-entrypoints. The targets can be explored with--helpflags and then invoked in the exact same way as the previous examples with Go showed, e.g.The implementation uses the 3rd party
strawberryframework for defining targets and command hierarchies (whereas Go uses some homegrown code).While there are obviously differences between Python and Go, the general idea of how you structure your entrypoints is quite similar between the two and the low level API underneath them both (graphql) is the exact same, making it easy for the dagger CLI to handle both languages equivalently. The caller of entrypoint doesn't need any knowledge of what language they are calling.
Remote Projects with Git URLs
Expand
The previous examples were specifying projects that existed locally (i.e. `--project ci/dagger.json`).There is also support for running projects that exist in a remote Git repository without the need to explicitly pull them down first, e.g.
dagger do --project 'git://github.com/sipsma/dagger.git#entrypoints' --config ci ci sdk go lintThere's a lot of potentially interesting use cases here. For one simple example, users could define builds for their binaries as Dagger entrypoints and then anyone who wanted to install it could just run:
dagger do --project 'git://github.com/org/repo.git#v0.1' install --output-path ~/binWe obviously need a pretty locked-down-by-default security model here, though the fact that entrypoints run in containers help a lot. Access to the caller's host (import/export files, env vars, etc.) will need some form of explicit opt-in, perhaps similar to
docker runactually.Using the--workdirflag here is probably not right as it is already used for something else, it will most likely changeExternal CI integration
Expand
I've done some very preliminary investigation on how this can integrate with external CI systems. Focus was on how much yaml we can convert to code inside and entrypoint and how we can integrate with CI events. There still some POC work left to do here, including converting more of our CI yamls over to entrypoints which will require actual handling of event payloads.dagger do ci --event ${{ toJson(github.event) }} ...dagger.Context(and similar in other languages).dagger-for-githubactioncheckoutaction in your yaml. Besides the benefit of "less yaml" this is also more performant in that the engine directly pulls from Git (including using remote caching) rather than the repo being pulled and then synced as a local dir into the engine. It's rare for that to be a bottleneck, for particularly large repos it can make a meaningful difference.Implementation Notes
Expand
I mostly re-used the pre-existing project+extension code from the previous prototypes. We should take this time to reassess it and update it as needed, but in general I do like being able to use the more generic extension plumbing as the internal, non-user facing foundation for this. It should set us up to quickly add new features like artifacts and eventually full-blown extensions.One example of something to consider is the idea from a while back where invoking extensions could be implemented entirely client side as
Container.WithExecs, which eliminates the need to stitch graphql schemas in the session. This has tradeoffs of course, but worth consideration now before we commit to one implementation or another.The high-level way
dagger doworks is:dagger doreadsdagger.json, uses the project API to query the schema of the project and converts the schema into cobra commands.Descriptionmetadata becomes the cobra usage string, theRunof the command just invokes the extension, etc.TODOs
Cutting off this PR in terms of new features so it doesn't grow too large. Rest of features and cleanups will be in follow ups.
Major follow-ups (in no particular order):
dagger.jsondagger project init(or similar) which generates new command code from templates--(in order to support wrapping other CLI interfaces e.g.go test)--helpoutput even when everything is fully cachedcore/integration/project_test.go, but need a lot more)help(every command gets a--helpflag implicitly). Though I suppose we could consider supporting custom help strings too?:vsMinor follow-ups:
sdk/go/server.go#which requires quoting in shell)