Skip to content

Project Commands - #5060

Merged
sipsma merged 21 commits into
dagger:mainfrom
sipsma:entrypoints
May 17, 2023
Merged

sipsma merged 21 commits into
dagger:mainfrom
sipsma:entrypoints

Conversation

@sipsma

@sipsma sipsma commented May 1, 2023 •

Copy link
Copy Markdown
Contributor

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 use dagger since 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 --help flags.

Top-level entrypoint ci:

$ dagger do --config ./ci ci --help
Loading+installing project (use --debug to track progress)...
Running command "ci"...

Command ci - Dagger CI targets

Available Subcommands:
  ci:engine           Dagger Engine targets
  ci:engine:lint      Lint the Dagger engine code
  ci:sdk              Dagger SDK targets
  ci:sdk:go           Dagger Go SDK targets
  ci:sdk:go:lint      Lint the Dagger Go SDK
  ci:sdk:nodejs       Dagger Nodejs SDK targets
  ci:sdk:nodejs:lint  Lint the Nodejs SDK
  ci:sdk:python       Dagger Python SDK targets
  ci:sdk:python:lint  Lint the Dagger Python SDK

Flags:
  --branch  
  --repo
  • Available Commands shows the available targets (engine and sdk so far)
  • ci also takes some top level arguments for --branch and --repo which the entrypoint implementation uses to pass some global context down to the subcommands
  • Improvements Coming Soon™️
    • Once default targets are implemented, ci won't even need to be explicitly typed in the CLI. It will just be the default target called when invoking dagger do
    • The --branch and --repo args 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)
    • Support for doc strings on arguments needs to be added (e.g. --branch string the name of the branch from the git repo)
    • Including all the dagger CLI global flags in the output is too noisy, they should probably be removed from this output
    • Having to explicitly pass dagger.json in 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 --help flag on any subcommand.

Here's an example of executing one:

$ dagger do --config ./ci ci:sdk:go:lint --repo github.com/dagger/dagger --branch main
Loading+installing project (use --debug to track progress)...
Running command "lint"...
level=info msg="[config_reader] Config search paths: [./ /app/sdk/go /app/sdk /app / /root]"
level=info msg="[config_reader] Used config file ../../.golangci.yml"
level=info msg="[lintersdb] Active 27 linters: [bodyclose depguard dogsled dupl exportloopref goconst gocritic gocyclo gofmt goimports goprintffuncname gosec gosimple govet ineffassign misspell nakedret prealloc revive rowserrcheck staticcheck stylec
heck typecheck unconvert unparam unused whitespace]"
level=info msg="[loader] Go packages loading at mode 575 (compiled_files|deps|exports_file|files|imports|name|types_sizes) took 6.012650031s"
level=info msg="[runner/filename_unadjuster] Pre-built 0 adjustments in 3.092193ms"
level=info msg="[linters_context/goanalysis] analyzers took 6.246671394s with top 10 stages: buildir: 3.220857137s, the_only_name: 1.504856241s, inspect: 249.091197ms, printf: 139.582094ms, fact_deprecated: 131.045815ms, ctrlflow: 130.746273ms, buildssa: 102.183487ms, nilness: 89.524337ms, fact_purity: 75.107843ms, typedness: 57.541827ms"
level=warning msg="[linters_context] rowserrcheck is disabled because of generics. You can track the evolution of the generics support by following the https://github.com/golangci/golangci-lint/issues/2649."
level=info msg="[runner] Issues before processing: 63, after processing: 0"
level=info msg="[runner] Processors filtering stat (out/in): path_prettifier: 63/63, cgo: 63/63, autogenerated_exclude: 57/63, identifier_marker: 57/57, exclude-rules: 5/57, filename_unadjuster: 63/63, exclude: 57/57, nolint: 0/5, skip_files: 63/63, skip_dirs: 63/63"
level=info msg="[runner] processing took 2.151097ms with stages: exclude-rules: 859.257µs, identifier_marker: 562.88µs, nolint: 393.962µs, autogenerated_exclude: 171.501µs, path_prettifier: 131.709µs, skip_dirs: 24.417µs, cgo: 3.291µs, filename_unadjuster: 1.375µs, max_same_issues: 500ns, uniq_by_line: 417ns, skip_files: 334ns, diff: 292ns, exclude: 250ns, source_code: 249ns, severity-rules: 207ns, max_from_linter: 124ns, max_per_file_from_linter: 84ns, sort_results: 83ns, path_prefixer: 83ns, path_shortener: 82ns"
level=info msg="[runner] linters took 3.22365722s with stages: goanalysis_metalinter: 3.221435368s, rowserrcheck: 6.833µs"
level=info msg="File cache stats: 16 entries of total size 121.5KiB"
level=info msg="Memory: 94 samples, avg is 145.9MB, max is 448.5MB"
level=info msg="Execution took 9.245905833s"
  • Improvements Coming Soon™️
    • By default, no progress logs are shown, which can result in a long awkward silence as the command executes. You can enable them with the --debug flag, 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 a dagger.json with 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 ci command hierachy, here's a starter example where each entrypoint is just a function:

func main() {
	// provide all the entrypoints you want here
	dagger.Serve(
		Build,
		Test,
	)
}

// Doc string for my build
func Build(ctx dagger.Context, foo string) (string, error) {
	baseImage := ctx.Client().Container().From("golang:1.20-alpine")
	// ...
}

// Doc string for my test
func Test(ctx dagger.Context, bar string) (string, error) {
	// ...
}

Each function will become a command available to dagger do. Build becomes a build command, Test becomes test, etc.

The function's first arg is required to be dagger.Context. This implements the standard context.Context interface 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 first ctx dagger.Context is excluded from that rule. It's also valid to take no args.

Improvements Coming Soon™️:

  • Support for more input types besides strings. Will just be primitive types like integers and possibly lists/maps of those (for now...)
  • Support for just returning error rather than always having to return something else
  • The dagger Client should be pre-populated with Pipeline labels that match your entrypoint's name

dagger do ci implementation (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.go we define the top level ci entrypoint and the subtargets available under it, sdk and engine:

func main() {
	dagger.Serve(CI)
}

func CI(ctx dagger.Context, repo, branch string) (CITargets, error) {
	return CITargets{
		SrcDir: ctx.Client().Git(repo).Branch(branch).Tree(),
	}, nil
}

type CITargets struct {
	SrcDir *dagger.Directory
}

// Dagger SDK targets
func (t CITargets) SDK(ctx dagger.Context) (SDKTargets, error) {
	return SDKTargets(t), nil
}

type SDKTargets struct {
	SrcDir *dagger.Directory
}

// Dagger Engine targets
func (t CITargets) Engine(ctx dagger.Context) (EngineTargets, error) {
	return EngineTargets(t), nil
}

type EngineTargets struct {
	SrcDir *dagger.Directory
}
  • The CI func accepts the --repo and --branch flags we saw before in the --help output. It uses those with the dagger client to create a Directory object, same as any existing pipeline code would.
  • It needs to pass that Directory down to subcommands, so it returns a struct CITargets which holds configuration that should be propagated.
    • The subcommands, sdk and engine and defined by just adding methods to CITargets.
    • Rules for how methods are converted to commands in the CLI are the same as the plain funcs in the previous starter example
    • Due to the fact that they are methods on CITargets, sdk and engine have access to the Directory created by CI (in the SrcDir field).
      • In this case, the subcommands just pass that configuration down to their own subcommands; splitting them up here is more for organizational purposes.
    • The structs passed from parent->child commands don't show up in the CLI interface. They are purely used in the implementation.
    • These structs can be named arbitrarily and the only requirement for their fields is that they are json serializable.

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):

type PythonTargets struct {
        // configuration for targets
	RepoSrcDir *dagger.Directory
	SDKSrcDir  *dagger.Directory
	Base       *dagger.Container
}

func (s SDKTargets) Python(ctx dagger.Context) (PythonTargets, error) {
	const (
		path          = "/root/.local/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
		venv          = "/opt/venv"
		appDir        = "sdk/python"
		pythonVersion = "3.11"
	)
	sdkSrcDir := s.SrcDir.Directory(appDir)

	// We mirror the same dir structure from the repo because of the
	// relative paths in ruff (for docs linting).
	mountPath := fmt.Sprintf("/%s", appDir)

	base := ctx.Client().Container().
		From(fmt.Sprintf("python:%s-alpine", pythonVersion)).
		WithEnvVariable("PATH", path).
		WithExec([]string{"apk", "add", "-U", "--no-cache", "gcc", "musl-dev", "libffi-dev"}).
		WithExec([]string{"pip", "install", "--user", "poetry==1.3.1", "poetry-dynamic-versioning"}).
		WithExec([]string{"python", "-m", "venv", venv}).
		WithEnvVariable("VIRTUAL_ENV", venv).
		WithEnvVariable("PATH", fmt.Sprintf("%s/bin:%s", venv, path)).
		WithEnvVariable("POETRY_VIRTUALENVS_CREATE", "false").
  
       <rest of code...>

	return Python{
		SDKSrcDir:  sdkSrcDir,
		RepoSrcDir: s.SrcDir,
		Base:       deps,
	}, nil
}

// Lint the Dagger Python SDK
func (p PythonTargets) Lint(ctx dagger.Context) (string, error) {
	// TODO: pipeline should be automatically set
	c := ctx.Client().Pipeline("sdk").Pipeline("python").Pipeline("lint")

	eg, gctx := errgroup.WithContext(ctx)

	var poeLintOut string
	eg.Go(func() error {
		var err error
		poeLintOut, err = p.Base.
			WithExec([]string{"poe", "lint"}).
			Stdout(gctx)
		return err
	})

	<rest of code...>

	return strings.Join([]string{
		poeLintOut,
		poeLintDocsOut,
	}, "\n"), eg.Wait()
}
  • The (s SDKTargets) Python method defines the python subcommand on sdk.
    • In this case, it doesn't take any args (though it could if desired)
    • But it does do some work to take the SrcDir received 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)
  • Then the final Lint target is defined as a method on PythonTargets, 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 --help flags and then invoked in the exact same way as the previous examples with Go showed, e.g.

$ dagger do -c demos/python-entrypoints hello:say --msg friendo
Loading+installing project (use --debug to track progress)...
Running command "hello:say"...
Hello friendo!

The implementation uses the 3rd party strawberry framework 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 lint

There'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 ~/bin

We 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 run actually.

  • Improvements Coming Soon™️
    • The command is too verbose right now, need some sugar to enable more compactness in common cases
    • Using the --workdir flag here is probably not right as it is already used for something else, it will most likely change

External 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.
  1. CI Event payload handling
    • It's already possible to invoke an entrypoint with an event payload, e.g. dagger do ci --event ${{ toJson(github.event) }} ...
    • That technically unblocks a lot of use cases, but leaves a lot of onus on the user parse the payload
    • This may be okay for now, but we could also add a lot of sugar here in follow ups. We could go all the way up to defining a common format for CI events that we automagically pass to your entrypoint in the dagger.Context (and similar in other languages).
    • There are many possible intermediate options too. Will save any of those implementations for follow-ups
  2. What can't be converted to an entrypoint (yet)
    • Automatic distribution of an entrypoints execution to separate machines (i.e. still need multiple GHA jobs if you want that)
    • Direct execution on Windows/MacOS hosts ("direct execution" as is not cheating by executing inside docker/colima on macos, which is just a Linux VM)
  3. Sugar via the dagger-for-github action
    • In the spirit of converting as much yaml->dagger as possible, I did a very quick trial of what an updated version would look like here (not published to marketplace, just used in my tests)
      • It has to do a checkout and install go in order to build the CLI, but the final prod version would just download a released CLI
    • So far, the only real magic this has added (besides installing the dagger CLI) is automatically setting up your project to use a git:// URL based on the env vars set by GHA (here)
      • This does let you eliminate use of the checkout action 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 do works is:

  1. The code-to-schema implementation takes your code and converts it into a graphql schema. This schema is totally internal, users do not need to be aware of it.
    • For Go, this is the custom code we already wrote (with some new tweaks+refactoring)
    • For Python, this is just the 3rd party strawberry library
  2. dagger do reads dagger.json, uses the project API to query the schema of the project and converts the schema into cobra commands.
    • Graphql Description metadata becomes the cobra usage string, the Run of 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):

  1. Support for passing and/or accessing host resources
  2. dagger.json
    • Re-add cli for querying/updating it
    • Add dagger project init (or similar) which generates new command code from templates
  3. To enable monorepo-type use cases, support loading hierarchies of projects (possibly of different languages) and being able to invoke commands from all of them in a single unified interface
  4. Update our dagger-for-github action to with built-in support for invoking entrypoints with minimal yaml
    • Related: create examples of commands accepting + using CI event payloads
  5. Improve Python DX (as @helderco suggested here)
  6. Add support for Typescript commands
  7. Revisit topic of "default" command - lots of discussion here but no conclusion yet
  8. TUI and logging integration
    • Integrate w/ nested sessions that command implementations use
    • Magic (e.g. ideas listed here)
  9. Support more primitive types as inputs/outputs of commands besides just string
  10. Support for required vs. optional args (and possibly default values for optional args)
  11. Support for positional args, including the use case @vito mentioned of being able to accept values that look like flags after a -- (in order to support wrapping other CLI interfaces e.g. go test)
  12. Consider builtin support for batching commands. There are differing opinions on how strongly this is needed, if at all.
  13. Optimize latency of loading and invoking a cached project
    • It's a few seconds right now to see --help output even when everything is fully cached
  14. Finish migration of Dagger's CI to commands
  15. Add support for invoking commands to the Project API (currently it only supports reading the metadata of the command/flag structure and invocation has to happen over a raw graphql query)
  16. Bikeshed new Project API
  17. Documentation
  18. Cleanup and consolidate the various paths and configs for them (workdir, project root, project config) as discussed here
  19. Add more tests (there's a measly one in core/integration/project_test.go, but need a lot more)
  20. Better errors. Lots here, a few cases worth not forgetting:
  • can't have an arg named help (every command gets a --help flag implicitly). Though I suppose we could consider supporting custom help strings too?
  1. Close on : vs

Minor follow-ups:

  1. Go-specific
    1. Support for help docs on arguments
    2. Fix bug in go codegen around lists of objects
    3. Refactor sdk/go/server.go
      • Goal should be that only AST parsing happens when figuring out the schema. After that, schema is cached.
      • Then, when it comes time to actually invoke, we rely only on reflection. And in longer term, if reflection is too slow we could even optimize further by actually generating code based on the schema that wraps user functions and enables calling them with no reflection. But TBD if that's actually needed
  2. Automatically set pipeline labels on dagger clients given to commands
  3. Figure out a better syntax for specifying git project in the CLI (too verbose right now, also uses a # which requires quoting in shell)

Comment thread demos/entrypoints/main.go Outdated
Comment on lines 32 to 37

@vito vito May 1, 2023 •

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.

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

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.

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.

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 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)

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.

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!

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.

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.

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.

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.

@helderco helderco May 8, 2023 •

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.

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()

@sipsma sipsma May 9, 2023 •

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.

@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 :-)

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.

+1 to removing boilerplate if we can!

@robertu94

Copy link
Copy Markdown

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?

@sipsma

sipsma commented May 3, 2023 •

Copy link
Copy Markdown
Contributor Author

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

What is the UX for creating the JSON file here? From the examples it looks like it was pre generated.

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!

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.

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 WithExec in our core APIs).

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 (dagger do --help) takes a few seconds even when its cached in buildkit. I'd like to see if we can reduce that latency, but caching in dagger.json rather than just buildkit actually may even simpler + more effective. Added a note about this to the description

Additionally the issue of the default target doesn't seem to be addressed. What is the thought there?

Great question, added addressing that to my TODO list in the description.

In general I'm seeing two possible routes:

  1. Configure this in dagger.json
  2. Configure this in your entrypoint code itself
    • The exact form this would take depends heavily on the language.
    • If the SDK language has some built-in notion of default methods or functions, that's the preferred route
    • After that, features like @annotations, decorators, etc. seem like the next best approach
    • And for languages like Go that don't have anything like that, we'll just have to use whatever we have left.
      • For Go specifically, there are conventions around "pragmas" that can annotate functions, but they are essentially just comments with a special syntax. That's probably the best route here unfortunately.

I'm undecided, but if I had to choose at this point I'd probably go with just using dagger.json for this since it's so simple and language agnostic. There'd probably be a subcommand along the lines of dagger project get-default-entrypoint, dagger project set-default-entrypoint <name of entrypoint>, etc.

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 All that, if set, will be the default. I might actually like that one the most at the moment, especially since it doesn't rule out supporting an override in dagger.json in the future if desired too.

@sipsma
sipsma force-pushed the entrypoints branch 2 times, most recently from c72759c to cdfe79c Compare May 6, 2023 03:37
Comment thread .github/workflows/lint.yml Outdated

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.

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

Comment thread .github/workflows/lint-daggerized.yml Outdated

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.

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

Comment thread sdk/go/server.go Outdated

@sipsma sipsma May 6, 2023 •

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.

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)

@shykes

shykes commented May 6, 2023

Copy link
Copy Markdown
Contributor

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

@shykes

shykes commented May 6, 2023

Copy link
Copy Markdown
Contributor

I love that this brings back the intuitive command-oriented UX of dagger do. Seamless support for subcommands is fantastic. On the DX, having simple functions with minimal boilerplate is perfect.

A few notes and questions:

  • I am now convinced that “command” is the right noun to describe what is invoked by dagger do. I forgot who suggested it but: it’s better than “script”, “task” and “action”.

  • Terminology: I propose that to designate the program that implements a project’s commands, we try using the term “controller” rather than “entrypoint”.

  • Can I enumerate and invoke commands from the GraphQL client? For example could someone in the community easily develop a web UI or that does this? What would the graphql queries look like?

  • Related to the previous question: I think maybe when loading a controller, SDKs should not generate a dynamic schema, but rather dynamic resolvers for a common static schema. So the CLI would populate its cobra commands by sending simple queries like { project { commands(recursive: true) { name; description; flags { name; description; type } } } }. Note that type is an enum of possible cobra flag types, not graphql type.

Then to invoke a command: { project { command(name: “sdk”) { withStringFlag(name: “repo”, value: “github.com/…”) { command(name: “go”) { command(name: “lint”) { withBoolFlag(name: “strict”, value: true) { error; output; duration; } } } } } } }

@shykes

shykes commented May 6, 2023

Copy link
Copy Markdown
Contributor

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 dagger do shows the combined output of the enumeration query for all controllers.

@shykes

shykes commented May 6, 2023

Copy link
Copy Markdown
Contributor

I think we should adopt the mage (and others) convention for subcommands: sdk:go:test rather than sdk go test. This frees up the grammar for other things:

  1. Batch commands with flags only:dagger do sdk:go:test —branch main sdk:go:lint —strict
  2. Batch commands with mandatory positional args only (like mage): dagger do sdk:go:test main sdk:go:lint true
  3. Only command, with both flags and positional args. dagger do —branch main sdk:go:lint —strict ./src

@shykes

shykes commented May 6, 2023

Copy link
Copy Markdown
Contributor

I think access to host filesystem for each controller should be scoped to the directory that loaded that controller.

  • read access: project { directory } ?
  • write access: directory { export } with all paths relative to project dir? leading slashes ignored.

@shykes

shykes commented May 6, 2023

Copy link
Copy Markdown
Contributor

I think dagger do with no argument should show the list of available commands.

@robertu94

Copy link
Copy Markdown

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

  1. Technically make/ninja run the first defined target by default so that may be reasonable by default too, but for other reasons I think all is the better default ↩

@samalba

samalba commented May 6, 2023

Copy link
Copy Markdown
Contributor

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.

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.

@sipsma

sipsma commented May 8, 2023

Copy link
Copy Markdown
Contributor Author

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

@samalba Yes totally agree, should be a trivial update to make, will do

I am now convinced that “command” is the right noun to describe what is invoked by dagger do. I forgot who suggested it but: it’s better than “script”, “task” and “action”.
Terminology: I propose that to designate the program that implements a project’s commands, we try using the term “controller” rather than “entrypoint”.

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

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.

Can I enumerate and invoke commands from the GraphQL client? For example could someone in the community easily develop a web UI or that does this? What would the graphql queries look like?

Related to the previous question: I think maybe when loading a controller, SDKs should not generate a dynamic schema, but rather dynamic resolvers for a common static schema. So the CLI would populate its cobra commands by sending simple queries like { project { commands(recursive: true) { name; description; flags { name; description; type } } } }. Note that type is an enum of possible cobra flag types, not graphql type.

Right now dagger do is implemented by loading the project and performing a graphql introspection query to get the schema for it, which is used to create the cobra command structure. This was primarily because it required the least number of changes since it's essentially what our client codegen does already (just against the core schema rather than project schemas).

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.

Can controllers be stacked?

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 dagger.json. But it also could be nicer DX to just recursively load all dagger.jsons found under a given filesystem tree. Maybe that's modeled as an "implicit dependency", or maybe that's just it's own thing.

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!)

I think access to host filesystem for each controller should be scoped to the directory that loaded that controller.

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. dagger do my-command --your-socket /i/grant/you/this.sock.

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)

@sipsma

sipsma commented May 8, 2023 •

Copy link
Copy Markdown
Contributor Author

I think we should adopt the mage (and others) convention for subcommands: sdk:go:test rather than sdk go test. This frees up the grammar for other things:
* Batch commands with flags only:dagger do sdk:go:test —branch main sdk:go:lint —strict
* Batch commands with mandatory positional args only (like mage): dagger do sdk:go:test main sdk:go:lint true
* Only command, with both flags and positional args. dagger do —branch main sdk:go:lint —strict ./src

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

  1. I think that splitting by: may just be less intuitive to someone not familiar with mage relative to splitting out by space, which IME is the standard approach.
    • Is there any other convention for the target:subtarget syntax? I'm not aware of it besides mage but may be missing something
    • This is highly subjective too of course, just my opinion
  2. Right now it's possible for each subcommand to take its own flags separately, but that would get a little less clean with a mage syntax
    • e.g. it's currently possible to implement something like this: dagger do sdk --foo=fooval go --bar=barval lint --baz=bazval, which feels it could be useful in a lot of situations
    • We could group all flags together like dagger do sdk:go:lint --foo=fooval --bar=barval --bar=bazval, which creates a gotcha in that you can't ever create any flags with the same name on commands+subcommands. Maybe fine? But nice to avoid gotchas when possible of course.
    • Similar to above, if subcommands each accept positional args, I'm not sure how you could specify them for each subcommand in an unambiguous way
  3. Once we mix in positional args too, I think we might hit some weird parsing corner cases
    • e.g. dagger a:b c:d, if a:b accepts optional positional args, we need some way to differentiate between c:d being a separate command and a:b taking c:d as a positional argument
    • Maybe there's ways of doing that, would need to think more, but if not then I think we'd maybe end up having to do something like using -- to separate out commands, e.g. dagger a:b -- c:d, or something like that
    • This parsing ambiguity will actually also be true if we separate by spaces, so I don't see that either approach has an advantage over the other on this point

If we keep the space-separated syntax, we could support batching commands by separating by some special delimiter, e.g. -- as mentioned above

  • e.g. dagger do -- sdk go lint -- sdk go test
  • Not 100% sold on -- specifically, this is slightly different than the convention it's normally used in, but feel like it's close enough to not be too weird
  • Maybe we could even support something fancier like splitting at subcommands, e.g. dagger do sdk --foo=fooval go -- lint -- test? Not convinced by that, kind of looks weird, but could work.
    • EDIT: actually, I'm pretty sure this specifically would have tons of parsing ambiguities if you want to do multiple levels of splitting, so maybe not.

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 args that has to be a list of strings, e.g.:

func Lint(ctx dagger.Context, args []string, someFlag string)

Commands wouldn't have to accept args, but if they do it will be set to any positional args provided by the caller.

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 help).

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?

@sipsma

sipsma commented May 8, 2023 •

Copy link
Copy Markdown
Contributor Author

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

  • e.g. you have to type dagger do ci --branch main sdk go lint even though ci may be the only "top-level" command.
  • When there's only one top-level command, this feels like boilerplate and that you should be able to just type dagger do --branch main sdk go lint

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.


As for a what the default is, I would suggest run all defined pipelines.

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

  • We should of course put safety guards around the more "dangerous" targets such that they are skipped unless there's some explicit opt-in in one form or another (or the presence of secrets that developer machines don't have)
  • But my paranoia tells me that could become a footgun since it relies on the safeguard being totally correct; e.g. someone runs dagger do and due to a bug in their command implementation they accidentally publish a new prod image.
  • I guess this gets at what you said @shykes around this sort of convention making more sense in tools that only do builds, which aren't usually dangerous in the same way a tool that can could theoretically do deployments is.

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.

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 Containers/Directories/Files from code (whereas commands only support primitive types):

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 dagger artifacts --export ~/bin/ my-binary-artifact.

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.

@shykes

shykes commented May 9, 2023 •

Copy link
Copy Markdown
Contributor

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 dagger do ....

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.

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.

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.

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.

@shykes

shykes commented May 9, 2023

Copy link
Copy Markdown
Contributor

Can controllers be stacked?

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 dagger.json. But it also could be nicer DX to just recursively load all dagger.jsons found under a given filesystem tree. Maybe that's modeled as an "implicit dependency", or maybe that's just it's own thing.

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!)

I agree that how exactly to make use of the stacking is a can of worms. Plenty of fun bikeshedding ahead :).

  • I was just thinking about "implicit dependency" over the week-end, and how that could be a useful tool in the toolbox - that is, if we can decide in what direction to do the walking :) I remember that CUE actually supports both directions depending on the context: up towards the root for package unification; and down "recursively loading under a given tree" for another type of evaluation, the details of which elude me.
  • I also think stackable controllers might be a way to ship extensions sooner than anticipated - ie. before supporting codegen. Think about it: if I can write a controller that, say, scans my project's package.json and dynamically exposes each npm script as a dagger command... What if I can just package that controller into an extension, so that you can do the same thing in your project? This would be "extensions lite", because you wouldn't get arbitrary pipeline composition. But it could still be quite useful. Something to think about :)

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.

@shykes

shykes commented May 9, 2023

Copy link
Copy Markdown
Contributor

My concerns with the mage-syntax are:

  1. I think that splitting by: may just be less intuitive to someone not familiar with mage relative to splitting out by space, which IME is the standard approach.

    • Is there any other convention for the target:subtarget syntax? I'm not aware of it besides mage but may be missing something

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.

  1. Right now it's possible for each subcommand to take its own flags separately, but that would get a little less clean with a mage syntax

Not necessarily a dealbreaker, but I agree it's a plus for using spaces.

If we keep the space-separated syntax, we could support batching commands by separating by some special delimiter, e.g. -- as mentioned above

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 -- instead of just one. That's a subtle but potentially super confusing change to anyone familiar with the usual behavior.

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: &, wait etc. It's also consistent with our approach to concurrency in SDKs :)

We need to figure out positional args for either syntax we land on.

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!

@shykes

shykes commented May 9, 2023 •

Copy link
Copy Markdown
Contributor

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.

OK, I am getting good replies to that tweet, and a clearer picture is emerging:

  • There is in fact a strong convention of using colon as separators in build and build-adjacent tools. Originally started by Rake (ruby), and followed by NPM (javascript), Maven (java), Laravel Artisan (php), and Mage (go).
  • Original purpose was to simplify batching
  • I guess cascading flags are just not a thing in that model
  • Heroku is the only example of using this convention outside of user-defined scripts or build targets.

One reply says:

basically if you’re thinking of making a “build system” like Rake in which you’d want to specify multiple tasks to run in order, then go for it. otherwise i don’t think it’s a good idea, and Heroku probably just did it so it “looked more Railsy” since that’s their origins.

@robertu94

Copy link
Copy Markdown

@sipsma @shykes

Is there any other convention for the target:subtarget syntax? I'm not aware of it besides mage but may be missing something

I believe that bazel, buck, and pants all use /. My own dev-workflow tool uses :. My one piece of advice is don't use spaces, extra spaces sometimes get "eaten" by parsers and they can't be seen easily on slides or in talks.

But my paranoia tells me that could become a footgun since it relies on the safeguard being totally correct; e.g. someone runs dagger do and due to a bug in their command implementation they accidentally publish a new prod image.

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

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.

I think that is a feature, not a bug. Different projects have different needs. The other default that other tools (make, ninja mentioned before is first definition. The things in these tools that have side effects (install, clean) are not defaults and would be analogous to what you describe) If you want that to do multiple things you can do something like

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.

maybe we block internet access during the execution of artifact implementations in order to enforce hermeticity of builds

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 😄

Maybe there's ways of doing that, would need to think more, but if not then I think we'd maybe end up having to do something like using -- to separate out commands, e.g. dagger a:b -- c:d, or something like that

I've seen several tools do this, and I think it is a reasonable idea.

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 Containers/Directories/Files from code (whereas commands only support primitive types)

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.

@sipsma

sipsma commented May 9, 2023

Copy link
Copy Markdown
Contributor Author

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.

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.

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 :)

Awesome, thank you, incredibly helpful! Mixed opinions of course, but by eye there is a lot more opposition for : than support and the majority of the support is fairly lukewarm/caveated (with some exceptions).

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: &, wait etc. It's also consistent with our approach to concurrency in SDKs :)

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 xargs don't result in what I'd call beautiful code, but that's just shell code being shell code.

  • This is complicated by the fact that there are indeed mixed conventions in this case, : is not a one-off as it turns out and has advantages. But just based on the feedback so far the ~averaged sentiment probably leans more towards POSIX-y space separate commands and --flags being the "standard".

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.

  • This will currently be complicated by the fact that this is only really easy if you are the person controlling the command's controller code. But in our path to extensions, we will need to pick up features that let you import/wrap controllers across any SDK language, which should make this easier? Worth thinking more about this point.

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.

I believe that bazel, buck, and pants all use /. My own dev-workflow tool uses :. My one piece of advice is don't use spaces, extra spaces sometimes get "eaten" by parsers and they can't be seen easily on slides or in talks.

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 "space separated values" in "" or '' (definitely a common gotcha, myself included) and the readability tradeoffs.


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.

dagger do will still be hidden so we'll have time to pivot to : or similar if desired. As we start prototyping with this more, especially on more and more complicated use cases, it will be easy to see if using spaces results in a mess that could be cleaned up with : or other approaches.

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 -- or similar in the future in a backwards compatible way (or at least in a way that only breaks a tiny set of corner cases).

@shykes

shykes commented May 9, 2023 •

Copy link
Copy Markdown
Contributor

Here’s my summary of the “ask the internet about colon-separators” thread:

  1. Colon-separators are very common for user-defined commands in build and build-adjacent tools: rake, maven, npm, laravel, mage.. In that context it is familiar and often expected.

  2. Very uncommon otherwise. Heroku seems to be the exception.

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

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)

Comment thread .github/workflows/lint-daggerized.yml 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.

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

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.

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!

Comment thread ci/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.

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

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.

Yep this is what I commented on #5060 (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.

I love that 😍

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.

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.

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

@helderco helderco May 11, 2023 •

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.

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.

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.

- https://www.python-httpx.org/advanced/

With the example in #5060 (comment), that's easily managed in app():

app = dagger.Project()
...
app()  # manage client instance

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.

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.

@vito

vito commented May 10, 2023 •

Copy link
Copy Markdown
Contributor

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 push -fed.


re: "controller" cc @shykes

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.

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 go test.

There have been a lot of times where I want to do e.g. ./hack/make engine:test ./core/integration -run MyTest but can't because Mage doesn't support it.

For me, batching is a lower priority than positional args, because as @aluzzardi pointed out:

Or maybe, a simpler/more naive approach is to do this in userland (e.g. define "virtual" targets that just invoke the actual targets)

Personally I'm unlikely to write dagger run foo:bar baz:buzz more than once without immediately making a virtual alias, since they're so easy to add, they're much more flexible, and they help you codify your development practices across the team.

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 -- for disambiguation from the entrypoint flags. It would be extra nice to not need to use -- somehow, but I don't think that's a dealbreaker; it's a little bit of friction but not an unfamiliar one.


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 argument

Of course, using -- makes things very clear, but it'd be nice to not have to type it in simple cases. We could probably avoid it by seeing that we're at a "leaf" in the command hierarchy.

You could also argue that this is a feature, not a bug. It's kind of nifty that sdk go test ./foo looks like go test ./foo! Maybe we would end up with a convention where your command hierarchy matches the command that it runs, so it naturally flows into its arguments?

Another option could be / since it matches how we've been displaying pipeline paths in a few places (sdk / go / test). Just throwing that out there to see if there are strong reactions in favor or against. :)

dagger do sdk/go/test ./foo

One drawback is it could look like it's running a ./sdk/go/test script. Looks like Bazel avoids this by putting // at the front, making it just funky enough to raise suspicion.

sipsma added 17 commits May 16, 2023 16:38
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]>
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.

9 participants