status
stringclasses
1 value
repo_name
stringclasses
31 values
repo_url
stringclasses
31 values
issue_id
int64
1
104k
title
stringlengths
4
233
body
stringlengths
0
186k
issue_url
stringlengths
38
56
pull_url
stringlengths
37
54
before_fix_sha
stringlengths
40
40
after_fix_sha
stringlengths
40
40
report_datetime
timestamp[us, tz=UTC]
language
stringclasses
5 values
commit_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
7
188
chunk_content
stringlengths
1
1.03M
closed
dagger/dagger
https://github.com/dagger/dagger
4,652
🐞 network issue with [email protected] in k8s pod
### What is the issue? May cause by https://github.com/dagger/dagger/pull/4505 Here a new search in `/etc/resolv.conf` added before k8s searches ```conf search dns.dagger search gitlab.svc.cluster.local. svc.cluster.local. cluster.local. openstacklocal options ndots:5 ``` Then network because very slow to fetch anything. ### Log output _No response_ ### Steps to reproduce _No response_ ### SDK version Go SDK v0.4.6 ### OS version Unbuntu
https://github.com/dagger/dagger/issues/4652
https://github.com/dagger/dagger/pull/4666
253e3b227216468202a5b512838a77bd4315ed06
318cb775bed51438f6eb45fb4c96db1c2a2d39cd
2023-02-27T08:40:03Z
go
2023-03-01T01:16:55Z
internal/mage/engine.go
platformVariants := make([]*dagger.Container, 0, len(arches)) for _, arch := range arches { platformVariants = append(platformVariants, c. Container(dagger.ContainerOpts{Platform: dagger.Platform("linux/" + arch)}). From("alpine:"+alpineVersion). WithExec([]string{ "apk", "add", "git", "openssh", "pigz", "xz", "iptables", "ip6tables", "dnsmasq", }). WithFile("/usr/local/bin/runc", runcBin(c, arch), dagger.ContainerWithFileOpts{ Permissions: 0700, }). WithFile("/usr/local/bin/buildctl", buildctlBin(c, arch)). WithFile("/usr/local/bin/"+shimBinName, shimBin(c, arch)). WithFile("/usr/local/bin/"+engineBinName, engineBin(c, arch)). WithDirectory("/usr/local/bin", qemuBins(c, arch)). WithDirectory("/opt/cni/bin", cniPlugins(c, arch)). WithNewFile("/etc/dagger/cni.conflist", dagger.ContainerWithNewFileOpts{ Contents: cniConfig("dagger", network.CIDR), }). WithDirectory(engineDefaultStateDir, c.Directory()). WithNewFile(engineTomlPath, dagger.ContainerWithNewFileOpts{ Contents: buildkitConfig(), }). WithNewFile(engineEntrypointPath, dagger.ContainerWithNewFileOpts{ Contents: engineEntrypoint,
closed
dagger/dagger
https://github.com/dagger/dagger
4,652
🐞 network issue with [email protected] in k8s pod
### What is the issue? May cause by https://github.com/dagger/dagger/pull/4505 Here a new search in `/etc/resolv.conf` added before k8s searches ```conf search dns.dagger search gitlab.svc.cluster.local. svc.cluster.local. cluster.local. openstacklocal options ndots:5 ``` Then network because very slow to fetch anything. ### Log output _No response_ ### Steps to reproduce _No response_ ### SDK version Go SDK v0.4.6 ### OS version Unbuntu
https://github.com/dagger/dagger/issues/4652
https://github.com/dagger/dagger/pull/4666
253e3b227216468202a5b512838a77bd4315ed06
318cb775bed51438f6eb45fb4c96db1c2a2d39cd
2023-02-27T08:40:03Z
go
2023-03-01T01:16:55Z
internal/mage/engine.go
Permissions: 755, }). WithEntrypoint([]string{"dagger-entrypoint.sh"}), ) } return platformVariants } func cniConfig(name, subnet string) string { b, err := json.Marshal(map[string]any{ "cniVersion": "0.4.0", "name": name, "plugins": []any{ map[string]any{ "type": "bridge", "bridge": name + "0", "isDefaultGateway": true, "ipMasq": true, "hairpinMode": true, "ipam": map[string]any{ "type": "host-local", "ranges": []any{[]any{map[string]any{"subnet": subnet}}}, }, }, map[string]any{ "type": "firewall", }, map[string]any{ "type": "dnsname", "domainName": "dns.dagger", "capabilities": map[string]any{
closed
dagger/dagger
https://github.com/dagger/dagger
4,652
🐞 network issue with [email protected] in k8s pod
### What is the issue? May cause by https://github.com/dagger/dagger/pull/4505 Here a new search in `/etc/resolv.conf` added before k8s searches ```conf search dns.dagger search gitlab.svc.cluster.local. svc.cluster.local. cluster.local. openstacklocal options ndots:5 ``` Then network because very slow to fetch anything. ### Log output _No response_ ### Steps to reproduce _No response_ ### SDK version Go SDK v0.4.6 ### OS version Unbuntu
https://github.com/dagger/dagger/issues/4652
https://github.com/dagger/dagger/pull/4666
253e3b227216468202a5b512838a77bd4315ed06
318cb775bed51438f6eb45fb4c96db1c2a2d39cd
2023-02-27T08:40:03Z
go
2023-03-01T01:16:55Z
internal/mage/engine.go
"aliases": true, }, }, }, }) if err != nil { panic(err) } return string(b) } func cniPlugins(c *dagger.Client, arch string) *dagger.Directory { cniURL := fmt.Sprintf( "https://github.com/containernetworking/plugins/releases/download/%s/cni-plugins-%s-%s-%s.tgz", cniVersion, "linux", arch, cniVersion, ) return c.Container(). From("alpine:"+alpineVersion). WithMountedFile("/tmp/cni-plugins.tgz", c.HTTP(cniURL)). WithDirectory("/opt/cni/bin", c.Directory()). WithExec([]string{ "tar", "-xzf", "/tmp/cni-plugins.tgz", "-C", "/opt/cni/bin", "./bridge", "./firewall", "./loopback", "./host-local", }). WithFile("/opt/cni/bin/dnsname", dnsnameBinary(c, arch)). Directory("/opt/cni/bin") } func buildkitConfig() string {
closed
dagger/dagger
https://github.com/dagger/dagger
4,652
🐞 network issue with [email protected] in k8s pod
### What is the issue? May cause by https://github.com/dagger/dagger/pull/4505 Here a new search in `/etc/resolv.conf` added before k8s searches ```conf search dns.dagger search gitlab.svc.cluster.local. svc.cluster.local. cluster.local. openstacklocal options ndots:5 ``` Then network because very slow to fetch anything. ### Log output _No response_ ### Steps to reproduce _No response_ ### SDK version Go SDK v0.4.6 ### OS version Unbuntu
https://github.com/dagger/dagger/issues/4652
https://github.com/dagger/dagger/pull/4666
253e3b227216468202a5b512838a77bd4315ed06
318cb775bed51438f6eb45fb4c96db1c2a2d39cd
2023-02-27T08:40:03Z
go
2023-03-01T01:16:55Z
internal/mage/engine.go
return strings.Join([]string{ fmt.Sprintf("root = %q", engineDefaultStateDir), }, "\n") } func engineBin(c *dagger.Client, arch string) *dagger.File {
closed
dagger/dagger
https://github.com/dagger/dagger
4,652
🐞 network issue with [email protected] in k8s pod
### What is the issue? May cause by https://github.com/dagger/dagger/pull/4505 Here a new search in `/etc/resolv.conf` added before k8s searches ```conf search dns.dagger search gitlab.svc.cluster.local. svc.cluster.local. cluster.local. openstacklocal options ndots:5 ``` Then network because very slow to fetch anything. ### Log output _No response_ ### Steps to reproduce _No response_ ### SDK version Go SDK v0.4.6 ### OS version Unbuntu
https://github.com/dagger/dagger/issues/4652
https://github.com/dagger/dagger/pull/4666
253e3b227216468202a5b512838a77bd4315ed06
318cb775bed51438f6eb45fb4c96db1c2a2d39cd
2023-02-27T08:40:03Z
go
2023-03-01T01:16:55Z
internal/mage/engine.go
return util.GoBase(c). WithEnvVariable("GOOS", "linux"). WithEnvVariable("GOARCH", arch). WithExec([]string{ "go", "build", "-o", "./bin/" + engineBinName, "-ldflags", "-s -w", "/app/cmd/engine", }). File("./bin/" + engineBinName) } func shimBin(c *dagger.Client, arch string) *dagger.File { return util.GoBase(c). WithEnvVariable("GOOS", "linux"). WithEnvVariable("GOARCH", arch). WithExec([]string{ "go", "build", "-o", "./bin/" + shimBinName, "-ldflags", "-s -w", "/app/cmd/shim", }). File("./bin/" + shimBinName) } func buildctlBin(c *dagger.Client, arch string) *dagger.File {
closed
dagger/dagger
https://github.com/dagger/dagger
4,652
🐞 network issue with [email protected] in k8s pod
### What is the issue? May cause by https://github.com/dagger/dagger/pull/4505 Here a new search in `/etc/resolv.conf` added before k8s searches ```conf search dns.dagger search gitlab.svc.cluster.local. svc.cluster.local. cluster.local. openstacklocal options ndots:5 ``` Then network because very slow to fetch anything. ### Log output _No response_ ### Steps to reproduce _No response_ ### SDK version Go SDK v0.4.6 ### OS version Unbuntu
https://github.com/dagger/dagger/issues/4652
https://github.com/dagger/dagger/pull/4666
253e3b227216468202a5b512838a77bd4315ed06
318cb775bed51438f6eb45fb4c96db1c2a2d39cd
2023-02-27T08:40:03Z
go
2023-03-01T01:16:55Z
internal/mage/engine.go
return util.GoBase(c). WithEnvVariable("GOOS", "linux"). WithEnvVariable("GOARCH", arch). WithMountedDirectory("/app", c.Git(buildkitRepo).Branch(buildkitRef).Tree()). WithExec([]string{ "go", "build", "-o", "./bin/buildctl", "-ldflags", "-s -w", "/app/cmd/buildctl", }). File("./bin/buildctl") } func runcBin(c *dagger.Client, arch string) *dagger.File { return c.HTTP(fmt.Sprintf( "https://github.com/opencontainers/runc/releases/download/%s/runc.%s", runcVersion, arch, )) } func qemuBins(c *dagger.Client, arch string) *dagger.Directory { return c. Container(dagger.ContainerOpts{Platform: dagger.Platform("linux/" + arch)}). From(qemuBinImage). Rootfs() }
closed
dagger/dagger
https://github.com/dagger/dagger
4,652
🐞 network issue with [email protected] in k8s pod
### What is the issue? May cause by https://github.com/dagger/dagger/pull/4505 Here a new search in `/etc/resolv.conf` added before k8s searches ```conf search dns.dagger search gitlab.svc.cluster.local. svc.cluster.local. cluster.local. openstacklocal options ndots:5 ``` Then network because very slow to fetch anything. ### Log output _No response_ ### Steps to reproduce _No response_ ### SDK version Go SDK v0.4.6 ### OS version Unbuntu
https://github.com/dagger/dagger/issues/4652
https://github.com/dagger/dagger/pull/4666
253e3b227216468202a5b512838a77bd4315ed06
318cb775bed51438f6eb45fb4c96db1c2a2d39cd
2023-02-27T08:40:03Z
go
2023-03-01T01:16:55Z
network/network.go
package network const ( DNSDomain = "dns.dagger" CIDR = "10.87.0.0/16" Bridge = "10.87.0.1" )
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
package main import ( "context" "crypto/tls" "crypto/x509" "fmt" "net" "os" "os/user" "path/filepath" "sort" "strconv" "strings" "time" "github.com/containerd/containerd/pkg/seed" "github.com/containerd/containerd/pkg/userns" "github.com/containerd/containerd/platforms" "github.com/containerd/containerd/remotes/docker" "github.com/containerd/containerd/sys" sddaemon "github.com/coreos/go-systemd/v22/daemon" daggerremotecache "github.com/dagger/dagger/engine/remotecache" "github.com/docker/docker/pkg/reexec" "github.com/gofrs/flock" grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
"github.com/moby/buildkit/cache/remotecache" "github.com/moby/buildkit/client" "github.com/moby/buildkit/cmd/buildkitd/config" "github.com/moby/buildkit/control" "github.com/moby/buildkit/executor/oci" "github.com/moby/buildkit/frontend" dockerfile "github.com/moby/buildkit/frontend/dockerfile/builder" "github.com/moby/buildkit/frontend/gateway" "github.com/moby/buildkit/frontend/gateway/forwarder" "github.com/moby/buildkit/session" "github.com/moby/buildkit/solver/bboltcachestorage" "github.com/moby/buildkit/util/apicaps" "github.com/moby/buildkit/util/appcontext" "github.com/moby/buildkit/util/appdefaults" "github.com/moby/buildkit/util/archutil" "github.com/moby/buildkit/util/bklog" "github.com/moby/buildkit/util/grpcerrors" "github.com/moby/buildkit/util/profiler" "github.com/moby/buildkit/util/resolver" "github.com/moby/buildkit/util/stack" "github.com/moby/buildkit/util/tracing/detect" _ "github.com/moby/buildkit/util/tracing/detect/jaeger" _ "github.com/moby/buildkit/util/tracing/env" "github.com/moby/buildkit/util/tracing/transform" "github.com/moby/buildkit/version" "github.com/moby/buildkit/worker" ocispecs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/urfave/cli"
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
"go.etcd.io/bbolt" "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" "go.opentelemetry.io/otel/propagation" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/trace" tracev1 "go.opentelemetry.io/proto/otlp/collector/trace/v1" "golang.org/x/sync/errgroup" "google.golang.org/grpc" ) const ( autoMode = "auto" ) func init() { apicaps.ExportedProduct = "buildkit" stack.SetVersionInfo(version.Version, version.Revision) seed.WithTimeAndRand() if reexec.Init() { os.Exit(0) } detect.Recorder = detect.NewTraceRecorder() } var propagators = propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}) type workerInitializerOpt struct { config *config.Config sessionManager *session.Manager traceSocket string } type workerInitializer struct {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
fn func(c *cli.Context, common workerInitializerOpt) ([]worker.Worker, error) priority int } var ( appFlags []cli.Flag workerInitializers []workerInitializer ) func registerWorkerInitializer(wi workerInitializer, flags ...cli.Flag) { workerInitializers = append(workerInitializers, wi) sort.Slice(workerInitializers, func(i, j int) bool { return workerInitializers[i].priority < workerInitializers[j].priority }) appFlags = append(appFlags, flags...) } func main() { cli.VersionPrinter = func(c *cli.Context) { fmt.Println(c.App.Name, version.Package, c.App.Version, version.Revision) } app := cli.NewApp() app.Name = "buildkitd" app.Usage = "build daemon" app.Version = version.Version defaultConf, err := defaultConf() if err != nil {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
fmt.Fprintf(os.Stderr, "%+v\n", err) os.Exit(1) } rootlessUsage := "set all the default options to be compatible with rootless containers" if userns.RunningInUserNS() { app.Flags = append(app.Flags, cli.BoolTFlag{ Name: "rootless", Usage: rootlessUsage + " (default: true)", }) } else { app.Flags = append(app.Flags, cli.BoolFlag{ Name: "rootless", Usage: rootlessUsage, }) } groupValue := func(gid *int) string { if gid == nil { return "" } return strconv.Itoa(*gid) } app.Flags = append(app.Flags, cli.StringFlag{ Name: "config", Usage: "path to config file", Value: defaultConfigPath(), }, cli.BoolFlag{ Name: "debug", Usage: "enable debug output in logs",
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
}, cli.StringFlag{ Name: "root", Usage: "path to state directory", Value: defaultConf.Root, }, cli.StringSliceFlag{ Name: "addr", Usage: "listening address (socket or tcp)", Value: &cli.StringSlice{defaultConf.GRPC.Address[0]}, }, cli.StringFlag{ Name: "group", Usage: "group (name or gid) which will own all Unix socket listening addresses", Value: groupValue(defaultConf.GRPC.GID), }, cli.StringFlag{ Name: "debugaddr", Usage: "debugging address (eg. 0.0.0.0:6060)", Value: defaultConf.GRPC.DebugAddress, }, cli.StringFlag{ Name: "tlscert", Usage: "certificate file to use", Value: defaultConf.GRPC.TLS.Cert, }, cli.StringFlag{ Name: "tlskey", Usage: "key file to use", Value: defaultConf.GRPC.TLS.Key,
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
}, cli.StringFlag{ Name: "tlscacert", Usage: "ca certificate to verify clients", Value: defaultConf.GRPC.TLS.CA, }, cli.StringSliceFlag{ Name: "allow-insecure-entitlement", Usage: "allows insecure entitlements e.g. network.host, security.insecure", }, ) app.Flags = append(app.Flags, appFlags...) app.Action = func(c *cli.Context) error { if os.Geteuid() > 0 { return errors.New("rootless mode requires to be executed as the mapped root in a user namespace; you may use RootlessKit for setting up the namespace") } ctx, cancel := context.WithCancel(appcontext.Context()) defer cancel() cfg, err := config.LoadFile(c.GlobalString("config")) if err != nil { return err } if err := setDaggerDefaults(&cfg); err != nil { return err } setDefaultConfig(&cfg) if err := applyMainFlags(c, &cfg); err != nil { return err
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
} logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true}) if cfg.Debug { logrus.SetLevel(logrus.DebugLevel) } if cfg.GRPC.DebugAddress != "" { if err := setupDebugHandlers(cfg.GRPC.DebugAddress); err != nil { return err } } tp, err := detect.TracerProvider() if err != nil { return err } streamTracer := otelgrpc.StreamServerInterceptor(otelgrpc.WithTracerProvider(tp), otelgrpc.WithPropagators(propagators)) unary := grpc_middleware.ChainUnaryServer(unaryInterceptor(ctx, tp), grpcerrors.UnaryServerInterceptor) stream := grpc_middleware.ChainStreamServer(streamTracer, grpcerrors.StreamServerInterceptor) opts := []grpc.ServerOption{grpc.UnaryInterceptor(unary), grpc.StreamInterceptor(stream)} server := grpc.NewServer(opts...) root, err := filepath.Abs(cfg.Root) if err != nil { return err } cfg.Root = root if err := os.MkdirAll(root, 0700); err != nil { return errors.Wrapf(err, "failed to create %s", root) } lockPath := filepath.Join(root, "buildkitd.lock") lock := flock.New(lockPath)
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
locked, err := lock.TryLock() if err != nil { return errors.Wrapf(err, "could not lock %s", lockPath) } if !locked { return errors.Errorf("could not lock %s, another instance running?", lockPath) } defer func() { lock.Unlock() os.RemoveAll(lockPath) }() controller, err := newController(c, &cfg) if err != nil { return err } defer controller.Close() controller.Register(server) ents := c.GlobalStringSlice("allow-insecure-entitlement") if len(ents) > 0 { cfg.Entitlements = []string{} for _, e := range ents { switch e { case "security.insecure": cfg.Entitlements = append(cfg.Entitlements, e) case "network.host": cfg.Entitlements = append(cfg.Entitlements, e) default: return errors.Errorf("invalid entitlement : %s", e) } }
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
} errCh := make(chan error, 1) if err := serveGRPC(cfg.GRPC, server, errCh); err != nil { return err } select { case serverErr := <-errCh: err = serverErr cancel() case <-ctx.Done(): err = ctx.Err() } bklog.G(ctx).Infof("stopping server") if os.Getenv("NOTIFY_SOCKET") != "" { notified, notifyErr := sddaemon.SdNotify(false, sddaemon.SdNotifyStopping) bklog.G(ctx).Debugf("SdNotifyStopping notified=%v, err=%v", notified, notifyErr) } server.GracefulStop() return err } app.After = func(_ *cli.Context) error { return detect.Shutdown(context.TODO()) } profiler.Attach(app) if err := app.Run(os.Args); err != nil { fmt.Fprintf(os.Stderr, "buildkitd: %+v\n", err) os.Exit(1) } } func serveGRPC(cfg config.GRPCConfig, server *grpc.Server, errCh chan error) error {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
addrs := cfg.Address if len(addrs) == 0 { return errors.New("--addr cannot be empty") } tlsConfig, err := serverCredentials(cfg.TLS) if err != nil { return err } eg, _ := errgroup.WithContext(context.Background()) listeners := make([]net.Listener, 0, len(addrs)) for _, addr := range addrs { l, err := getListener(addr, *cfg.UID, *cfg.GID, tlsConfig) if err != nil { for _, l := range listeners { l.Close() } return err } listeners = append(listeners, l) } if os.Getenv("NOTIFY_SOCKET") != "" { notified, notifyErr := sddaemon.SdNotify(false, sddaemon.SdNotifyReady) logrus.Debugf("SdNotifyReady notified=%v, err=%v", notified, notifyErr) } for _, l := range listeners { func(l net.Listener) { eg.Go(func() error {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
defer l.Close() logrus.Infof("running server on %s", l.Addr()) return server.Serve(l) }) }(l) } go func() { errCh <- eg.Wait() }() return nil } func defaultConfigPath() string { if userns.RunningInUserNS() { return filepath.Join(appdefaults.UserConfigDir(), "buildkitd.toml") } return filepath.Join(appdefaults.ConfigDir, "buildkitd.toml") } func defaultConf() (config.Config, error) { cfg, err := config.LoadFile(defaultConfigPath()) if err != nil { var pe *os.PathError if !errors.As(err, &pe) { return config.Config{}, err } logrus.Warnf("failed to load default config: %v", err) } setDefaultConfig(&cfg) return cfg, nil } func setDefaultNetworkConfig(nc config.NetworkConfig) config.NetworkConfig {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
if nc.Mode == "" { nc.Mode = autoMode } if nc.CNIConfigPath == "" { nc.CNIConfigPath = appdefaults.DefaultCNIConfigPath } if nc.CNIBinaryPath == "" { nc.CNIBinaryPath = appdefaults.DefaultCNIBinDir } return nc } func setDefaultConfig(cfg *config.Config) { orig := *cfg if cfg.Root == "" { cfg.Root = appdefaults.Root } if len(cfg.GRPC.Address) == 0 { cfg.GRPC.Address = []string{appdefaults.Address} } if cfg.Workers.OCI.Platforms == nil { cfg.Workers.OCI.Platforms = formatPlatforms(archutil.SupportedPlatforms(false)) } if cfg.Workers.Containerd.Platforms == nil { cfg.Workers.Containerd.Platforms = formatPlatforms(archutil.SupportedPlatforms(false)) } cfg.Workers.OCI.NetworkConfig = setDefaultNetworkConfig(cfg.Workers.OCI.NetworkConfig)
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
cfg.Workers.Containerd.NetworkConfig = setDefaultNetworkConfig(cfg.Workers.Containerd.NetworkConfig) if userns.RunningInUserNS() { if u := os.Getenv("USER"); u != "" && u != "root" { if orig.Root == "" { cfg.Root = appdefaults.UserRoot() } if len(orig.GRPC.Address) == 0 { cfg.GRPC.Address = []string{appdefaults.UserAddress()} } appdefaults.EnsureUserAddressDir() } } } func applyMainFlags(c *cli.Context, cfg *config.Config) error { if c.IsSet("debug") { cfg.Debug = c.Bool("debug") } if c.IsSet("root") { cfg.Root = c.String("root") } if c.IsSet("addr") || len(cfg.GRPC.Address) == 0 { cfg.GRPC.Address = c.StringSlice("addr") } if c.IsSet("allow-insecure-entitlement") { cfg.Entitlements = c.StringSlice("allow-insecure-entitlement") }
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
if c.IsSet("debugaddr") { cfg.GRPC.DebugAddress = c.String("debugaddr") } if cfg.GRPC.UID == nil { uid := os.Getuid() cfg.GRPC.UID = &uid } if cfg.GRPC.GID == nil { gid := os.Getgid() cfg.GRPC.GID = &gid } if group := c.String("group"); group != "" { gid, err := grouptoGID(group) if err != nil { return err } cfg.GRPC.GID = &gid } if tlscert := c.String("tlscert"); tlscert != "" { cfg.GRPC.TLS.Cert = tlscert } if tlskey := c.String("tlskey"); tlskey != "" { cfg.GRPC.TLS.Key = tlskey } if tlsca := c.String("tlscacert"); tlsca != "" { cfg.GRPC.TLS.CA = tlsca } return nil } func grouptoGID(group string) (int, error) {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
if group == "" { return os.Getgid(), nil } var ( err error id int ) if id, err = strconv.Atoi(group); err == nil { return id, nil } else if err.(*strconv.NumError).Err != strconv.ErrSyntax { return 0, err } ginfo, err := user.LookupGroup(group) if err != nil { return 0, err } group = ginfo.Gid if id, err = strconv.Atoi(group); err != nil { return 0, err } return id, nil } func getListener(addr string, uid, gid int, tlsConfig *tls.Config) (net.Listener, error) {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
addrSlice := strings.SplitN(addr, "://", 2) if len(addrSlice) < 2 { return nil, errors.Errorf("address %s does not contain proto, you meant unix://%s ?", addr, addr) } proto := addrSlice[0] listenAddr := addrSlice[1] switch proto { case "unix", "npipe": if tlsConfig != nil { logrus.Warnf("TLS is disabled for %s", addr) } return sys.GetLocalListener(listenAddr, uid, gid) case "fd": return listenFD(listenAddr, tlsConfig) case "tcp": l, err := net.Listen("tcp", listenAddr) if err != nil { return nil, err } if tlsConfig == nil { logrus.Warnf("TLS is not enabled for %s. enabling mutual TLS authentication is highly recommended", addr) return l, nil } return tls.NewListener(l, tlsConfig), nil default: return nil, errors.Errorf("addr %s not supported", addr) } } func unaryInterceptor(globalCtx context.Context, tp trace.TracerProvider) grpc.UnaryServerInterceptor {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
withTrace := otelgrpc.UnaryServerInterceptor(otelgrpc.WithTracerProvider(tp), otelgrpc.WithPropagators(propagators)) return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { ctx, cancel := context.WithCancel(ctx) defer cancel() go func() { select { case <-ctx.Done(): case <-globalCtx.Done(): cancel() } }() if strings.HasSuffix(info.FullMethod, "opentelemetry.proto.collector.trace.v1.TraceService/Export") { return handler(ctx, req) } resp, err = withTrace(ctx, req, info, handler) if err != nil { logrus.Errorf("%s returned error: %v", info.FullMethod, err) if logrus.GetLevel() >= logrus.DebugLevel { fmt.Fprintf(os.Stderr, "%+v", stack.Formatter(grpcerrors.FromGRPC(err))) } } return } } func serverCredentials(cfg config.TLSConfig) (*tls.Config, error) {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
certFile := cfg.Cert keyFile := cfg.Key caFile := cfg.CA if certFile == "" && keyFile == "" { return nil, nil } err := errors.New("you must specify key and cert file if one is specified") if certFile == "" { return nil, err } if keyFile == "" { return nil, err
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
} certificate, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { return nil, errors.Wrap(err, "could not load server key pair") } tlsConf := &tls.Config{ Certificates: []tls.Certificate{certificate}, MinVersion: tls.VersionTLS12, } if caFile != "" { certPool := x509.NewCertPool() ca, err := os.ReadFile(caFile) if err != nil { return nil, errors.Wrap(err, "could not read ca certificate") } if ok := certPool.AppendCertsFromPEM(ca); !ok { return nil, errors.New("failed to append ca cert") } tlsConf.ClientAuth = tls.RequireAndVerifyClientCert tlsConf.ClientCAs = certPool } return tlsConf, nil } func newController(c *cli.Context, cfg *config.Config) (*control.Controller, error) { sessionManager, err := session.NewManager() if err != nil { return nil, err } tc, err := detect.Exporter()
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
if err != nil { return nil, err } var traceSocket string if tc != nil { traceSocket = filepath.Join(cfg.Root, "otel-grpc.sock") if err := runTraceController(traceSocket, tc); err != nil { logrus.Warnf("failed set up otel-grpc controller: %v", err) traceSocket = "" } } wc, err := newWorkerController(c, workerInitializerOpt{ config: cfg, sessionManager: sessionManager, traceSocket: traceSocket, }) if err != nil { return nil, err } frontends := map[string]frontend.Frontend{} frontends["dockerfile.v0"] = forwarder.NewGatewayForwarder(wc, dockerfile.Build) frontends["gateway.v0"] = gateway.NewGatewayFrontend(wc) cacheStorage, err := bboltcachestorage.NewStore(filepath.Join(cfg.Root, "cache.db")) if err != nil { return nil, err } historyDB, err := bbolt.Open(filepath.Join(cfg.Root, "history.db"), 0600, nil) if err != nil { return nil, err }
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
resolverFn := resolverFunc(cfg) w, err := wc.GetDefault() if err != nil { return nil, err } remoteCacheExporterFuncs := map[string]remotecache.ResolveCacheExporterFunc{ "dagger": daggerremotecache.ResolveCacheExporterFunc(sessionManager, resolverFn), } remoteCacheImporterFuncs := map[string]remotecache.ResolveCacheImporterFunc{ "dagger": daggerremotecache.ResolveCacheImporterFunc(sessionManager, w.ContentStore(), resolverFn), } return control.NewController(control.Opt{ SessionManager: sessionManager, WorkerController: wc, Frontends: frontends, ResolveCacheExporterFuncs: remoteCacheExporterFuncs, ResolveCacheImporterFuncs: remoteCacheImporterFuncs, CacheKeyStorage: cacheStorage, Entitlements: cfg.Entitlements, TraceCollector: tc, HistoryDB: historyDB, LeaseManager: w.LeaseManager(), ContentStore: w.ContentStore(), HistoryConfig: cfg.History, }) } func resolverFunc(cfg *config.Config) docker.RegistryHosts { return resolver.NewRegistryConfig(cfg.Registries) } func newWorkerController(c *cli.Context, wiOpt workerInitializerOpt) (*worker.Controller, error) {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
wc := &worker.Controller{} nWorkers := 0 for _, wi := range workerInitializers { ws, err := wi.fn(c, wiOpt) if err != nil { return nil, err } for _, w := range ws { p := w.Platforms(false) logrus.Infof("found worker %q, labels=%v, platforms=%v", w.ID(), w.Labels(), formatPlatforms(p)) archutil.WarnIfUnsupported(p) if err = wc.Add(w); err != nil { return nil, err } nWorkers++ } } if nWorkers == 0 { return nil, errors.New("no worker found, rebuild the buildkit daemon?") } defaultWorker, err := wc.GetDefault() if err != nil { return nil, err } logrus.Infof("found %d workers, default=%q", nWorkers, defaultWorker.ID()) logrus.Warn("currently, only the default worker can be used.") return wc, nil } func attrMap(sl []string) (map[string]string, error) {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
m := map[string]string{} for _, v := range sl { parts := strings.SplitN(v, "=", 2) if len(parts) != 2 { return nil, errors.Errorf("invalid value %s", v) } m[parts[0]] = parts[1] } return m, nil } func formatPlatforms(p []ocispecs.Platform) []string { str := make([]string, 0, len(p)) for _, pp := range p { str = append(str, platforms.Format(platforms.Normalize(pp))) } return str } func parsePlatforms(platformsStr []string) ([]ocispecs.Platform, error) {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
out := make([]ocispecs.Platform, 0, len(platformsStr)) for _, s := range platformsStr { p, err := platforms.Parse(s) if err != nil { return nil, err } out = append(out, platforms.Normalize(p)) } return out, nil } func getGCPolicy(cfg config.GCConfig, root string) []client.PruneInfo { if cfg.GC != nil && !*cfg.GC { return nil } if len(cfg.GCPolicy) == 0 { cfg.GCPolicy = config.DefaultGCPolicy(root, cfg.GCKeepStorage) } out := make([]client.PruneInfo, 0, len(cfg.GCPolicy)) for _, rule := range cfg.GCPolicy { out = append(out, client.PruneInfo{ Filter: rule.Filters, All: rule.All, KeepBytes: rule.KeepBytes, KeepDuration: time.Duration(rule.KeepDuration) * time.Second, }) } return out } func getBuildkitVersion() client.BuildkitVersion {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
return client.BuildkitVersion{ Package: version.Package, Version: version.Version, Revision: version.Revision, } } func getDNSConfig(cfg *config.DNSConfig) *oci.DNSConfig { var dns *oci.DNSConfig if cfg != nil { dns = &oci.DNSConfig{ Nameservers: cfg.Nameservers, Options: cfg.Options, SearchDomains: cfg.SearchDomains, } } return dns } func parseBoolOrAuto(s string) (*bool, error) { if s == "" || strings.EqualFold(s, autoMode) { return nil, nil } b, err := strconv.ParseBool(s) return &b, err } func runTraceController(p string, exp sdktrace.SpanExporter) error {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
cmd/engine/main.go
server := grpc.NewServer() tracev1.RegisterTraceServiceServer(server, &traceCollector{exporter: exp}) uid := os.Getuid() l, err := sys.GetLocalListener(p, uid, uid) if err != nil { return err } if err := os.Chmod(p, 0666); err != nil { l.Close() return err } go server.Serve(l) return nil } type traceCollector struct { *tracev1.UnimplementedTraceServiceServer exporter sdktrace.SpanExporter } func (t *traceCollector) Export(ctx context.Context, req *tracev1.ExportTraceServiceRequest) (*tracev1.ExportTraceServiceResponse, error) { err := t.exporter.ExportSpans(ctx, transform.Spans(req.GetResourceSpans())) if err != nil { return nil, err } return &tracev1.ExportTraceServiceResponse{}, nil }
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
core/integration/remotecache_test.go
package core import ( "context" "os" "os/exec" "sync" "testing" "time" "dagger.io/dagger" "github.com/moby/buildkit/identity" "github.com/stretchr/testify/require" "golang.org/x/sync/errgroup" ) func TestRemoteCacheRegistry(t *testing.T) {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
core/integration/remotecache_test.go
ctx, cancel := context.WithCancel(context.Background()) defer cancel() registryContainerName := runRegistryInDocker(ctx, t) getClient := func() *dagger.Client { return runSeparateEngine(ctx, t, map[string]string{ "_EXPERIMENTAL_DAGGER_CACHE_CONFIG": "type=registry,ref=127.0.0.1:5000/test-cache,mode=max", }, "container:"+registryContainerName) } pipelineOutput := func(c *dagger.Client) string { output, err := c.Container().From("alpine:3.17").WithExec([]string{ "sh", "-c", "head -c 128 /dev/random | sha256sum", }).Stdout(ctx) require.NoError(t, err) return output } /* 1. Start a registry for storing the cache 2. Start two independent engines from empty cache that are configured to use the registry as remote cache backend 3. Run an exec w/ output from /dev/random in the first engine 4. Close the first engine's client, flushing the remote cache for the session 5. Run the same exec in the second engine, verify it imports the cache and output the same value as the first engine */ clientA := getClient()
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
core/integration/remotecache_test.go
clientB := getClient() outputA := pipelineOutput(clientA) require.NoError(t, clientA.Close()) outputB := pipelineOutput(clientB) require.Equal(t, outputA, outputB) } func TestRemoteCacheS3(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() t.Run("buildkit s3 caching", func(t *testing.T) { bucket := "dagger-test-remote-cache-s3-" + identity.NewID() s3ContainerName := runS3InDocker(ctx, t, bucket) getClient := func() *dagger.Client { return runSeparateEngine(ctx, t, map[string]string{ "_EXPERIMENTAL_DAGGER_CACHE_CONFIG": "type=s3,mode=max,endpoint_url=http://localhost:9000,access_key_id=minioadmin,secret_access_key=minioadmin,region=mars,use_path_style=true,bucket=" + bucket, }, "container:"+s3ContainerName) } pipelineOutput := func(c *dagger.Client) string { output, err := c.Container().From("alpine:3.17").WithExec([]string{ "sh", "-c", "head -c 128 /dev/random | sha256sum", }).Stdout(ctx) require.NoError(t, err) return output } /* 1. Start an s3 compatible server (minio) locally for storing the cache 2. Start two independent engines from empty cache that are configured to use s3 as remote cache backend 3. Run an exec w/ output from /dev/random in the first engine 4. Close the first engine's client, flushing the remote cache for the session 5. Run the same exec in the second engine, verify it imports the cache and output the same value as the first engine
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
core/integration/remotecache_test.go
*/ clientA := getClient() clientB := getClient() outputA := pipelineOutput(clientA) require.NoError(t, clientA.Close()) outputB := pipelineOutput(clientB) require.Equal(t, outputA, outputB) }) t.Run("dagger s3 caching (with pooling)", func(t *testing.T) { bucket := "dagger-test-remote-cache-s3-" + identity.NewID() s3ContainerName := runS3InDocker(ctx, t, bucket) getClient := func() *dagger.Client { return runSeparateEngine(ctx, t, map[string]string{ "_EXPERIMENTAL_DAGGER_CACHE_CONFIG": "type=experimental_dagger_s3,mode=max,endpoint_url=http://localhost:9000,access_key_id=minioadmin,secret_access_key=minioadmin,region=mars,use_path_style=true,bucket=" + bucket + ",prefix=test-cache-pool/", "_EXPERIMENTAL_DAGGER_SERVICES_DNS": "0", }, "container:"+s3ContainerName) } pipelineOutput := func(c *dagger.Client, id string) string { output, err := c.Container(). From("alpine:3.17"). WithEnvVariable("ID", id). WithExec([]string{ "sh", "-c", "head -c 128 /dev/random | sha256sum", }).Stdout(ctx) require.NoError(t, err) return output
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
core/integration/remotecache_test.go
} generatedOutputs := map[string]string{} var mu sync.Mutex var eg errgroup.Group for i := 0; i < 5; i++ { eg.Go(func() error { id := identity.NewID() client := getClient() mu.Lock() defer mu.Unlock() generatedOutputs[id] = pipelineOutput(client, id) return client.Close() }) } require.NoError(t, eg.Wait()) require.Len(t, generatedOutputs, 5) eg = errgroup.Group{} client := getClient() for id, cachedOutput := range generatedOutputs { id, cachedOutput := id, cachedOutput eg.Go(func() error { require.Equal(t, cachedOutput, pipelineOutput(client, id)) return nil }) } require.NoError(t, eg.Wait()) require.NoError(t, client.Close()) }) } func runS3InDocker(ctx context.Context, t *testing.T, bucket string) string {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
core/integration/remotecache_test.go
t.Helper() name := "dagger-test-remote-cache-s3-" + identity.NewID() cmd := exec.Command("docker", "run", "--rm", "--name", name, "minio/minio", "server", "/data") t.Cleanup(func() { stopDockerRun(cmd, name) }) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Start() require.NoError(t, err) for i := 0; i < 100; i++ { cmd := exec.CommandContext(ctx, "docker", "exec", name, "sh", "-c", "curl -s -o /dev/null -w '%{http_code}' http://localhost:9000/minio/health/live") out, err := cmd.CombinedOutput() if string(out) == "200" && err == nil { break } if i == 99 { t.Fatalf("minio s3 not ready: %v: %s", err, out) } time.Sleep(100 * time.Millisecond) } cmd = exec.Command("docker", "run", "--rm", "--network", "container:"+name, "--entrypoint", "sh", "minio/mc", "-c", "mc config host add minio http://localhost:9000 minioadmin minioadmin && mc mb minio/"+bucket) cmd.Stdout = os.Stdout
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
core/integration/remotecache_test.go
cmd.Stderr = os.Stderr err = cmd.Run() require.NoError(t, err) return name } func runRegistryInDocker(ctx context.Context, t *testing.T) string { t.Helper() name := "dagger-test-remote-cache-registry-" + identity.NewID() cmd := exec.Command("docker", "run", "--rm", "--name", name, "registry:2") t.Cleanup(func() { stopDockerRun(cmd, name) }) err := cmd.Start() require.NoError(t, err) for i := 0; i < 100; i++ { cmd := exec.CommandContext(ctx, "docker", "exec", name, "sh", "-c", "wget -q -O - http://localhost:5000/v2/") out, err := cmd.CombinedOutput() if string(out) == "{}" && err == nil { break } if i == 99 { t.Fatalf("registry not ready: %v: %s", err, out) } time.Sleep(100 * time.Millisecond) } return name } var connectLock sync.Mutex func runSeparateEngine(ctx context.Context, t *testing.T, env map[string]string, network string) *dagger.Client {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
core/integration/remotecache_test.go
connectLock.Lock() defer connectLock.Unlock() t.Helper() name := "dagger-test-remote-cache-" + identity.NewID() allArgs := []string{"run"} dockerRunArgs := []string{ "--rm", "-v", "/var/lib/dagger", "--privileged", "--name", name, } for k, v := range env { dockerRunArgs = append(dockerRunArgs, "-e", k+"="+v) }
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
core/integration/remotecache_test.go
if network != "" { dockerRunArgs = append(dockerRunArgs, "--network", network) } allArgs = append(allArgs, dockerRunArgs...) allArgs = append(allArgs, "localhost/dagger-engine.dev:latest", "--debug", ) cmd := exec.Command("docker", allArgs...) t.Cleanup(func() { stopDockerRun(cmd, name) }) err := cmd.Start() require.NoError(t, err) currentRunnerHost, ok := os.LookupEnv("_EXPERIMENTAL_DAGGER_RUNNER_HOST") os.Setenv("_EXPERIMENTAL_DAGGER_RUNNER_HOST", "docker-container://"+name) if ok { defer os.Setenv("_EXPERIMENTAL_DAGGER_RUNNER_HOST", currentRunnerHost) } else { defer os.Unsetenv("_EXPERIMENTAL_DAGGER_RUNNER_HOST") } c, err := dagger.Connect(ctx, dagger.WithLogOutput(os.Stdout)) require.NoError(t, err) return c } func stopDockerRun(cmd *exec.Cmd, ctrName string) { exec.Command("docker", "rm", "-fv", ctrName).Run() cmd.Process.Kill() }
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
engine/remotecache/cache.go
package remotecache import ( "context" "os" "strings" "github.com/containerd/containerd/content" "github.com/containerd/containerd/remotes/docker" "github.com/dagger/dagger/internal/engine" "github.com/moby/buildkit/cache/remotecache" "github.com/moby/buildkit/cache/remotecache/azblob" "github.com/moby/buildkit/cache/remotecache/gha" registryremotecache "github.com/moby/buildkit/cache/remotecache/registry" "github.com/moby/buildkit/cache/remotecache/s3" "github.com/moby/buildkit/session" "github.com/moby/buildkit/util/bklog" ocispecs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" ) func ResolveCacheExporterFunc(sm *session.Manager, resolverFn docker.RegistryHosts) remotecache.ResolveCacheExporterFunc {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
engine/remotecache/cache.go
return func(ctx context.Context, g session.Group, userAttrs map[string]string) (remotecache.Exporter, error) { cacheType, attrs, err := cacheConfigFromEnv() if err != nil { return nil, err } var impl remotecache.Exporter switch cacheType { case "registry": impl, err = registryremotecache.ResolveCacheExporterFunc(sm, resolverFn)(ctx, g, attrs) case "gha": impl, err = gha.ResolveCacheExporterFunc()(ctx, g, attrs) case "s3": impl, err = s3.ResolveCacheExporterFunc()(ctx, g, attrs) case "experimental_dagger_s3": impl, err = s3Exporter(ctx, g, attrs) case "azblob": impl, err = azblob.ResolveCacheExporterFunc()(ctx, g, attrs) default: bklog.G(ctx).Debugf("unsupported cache type %s, defaulting export off", cacheType) } if err != nil { return nil, err } if userAttrs != nil { userAttrs["mode"] = attrs["mode"] } return impl, nil } }
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
engine/remotecache/cache.go
func ResolveCacheImporterFunc(sm *session.Manager, cs content.Store, hosts docker.RegistryHosts) remotecache.ResolveCacheImporterFunc { return func(ctx context.Context, g session.Group, userAttrs map[string]string) (remotecache.Importer, ocispecs.Descriptor, error) { cacheType, attrs, err := cacheConfigFromEnv() if err != nil { return nil, ocispecs.Descriptor{}, err } var impl remotecache.Importer var desc ocispecs.Descriptor switch cacheType { case "registry": impl, desc, err = registryremotecache.ResolveCacheImporterFunc(sm, cs, hosts)(ctx, g, attrs) case "gha": impl, desc, err = gha.ResolveCacheImporterFunc()(ctx, g, attrs) case "s3": impl, desc, err = s3.ResolveCacheImporterFunc()(ctx, g, attrs) case "experimental_dagger_s3": impl, desc, err = s3Importer(ctx, g, attrs) case "azblob": impl, desc, err = azblob.ResolveCacheImporterFunc()(ctx, g, attrs) default: bklog.G(ctx).Debugf("unsupported cache type %s, defaulting to noop", cacheType) impl = &noopImporter{} } if err != nil { return nil, ocispecs.Descriptor{}, err } return impl, desc, nil } } func cacheConfigFromEnv() (string, map[string]string, error) {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
engine/remotecache/cache.go
envVal, ok := os.LookupEnv(engine.CacheConfigEnvName) if !ok { return "", nil, nil } kvs := strings.Split(envVal, ",") if len(kvs) == 0 { return "", nil, nil } attrs := make(map[string]string) for _, kv := range kvs { parts := strings.SplitN(kv, "=", 2) if len(parts) != 2 { return "", nil, errors.Errorf("invalid form for cache config %q", kv) } attrs[parts[0]] = parts[1] } typeVal, ok := attrs["type"] if !ok { return "", nil, errors.Errorf("missing type in cache config: %q", envVal) } delete(attrs, "type") return typeVal, attrs, nil }
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
engine/remotecache/combined.go
package remotecache import ( "context" "strconv" "github.com/moby/buildkit/cache/remotecache" "github.com/moby/buildkit/solver" "github.com/moby/buildkit/worker" ocispecs "github.com/opencontainers/image-spec/specs-go/v1" ) type combinedImporter struct { importers []remotecache.Importer } func (i *combinedImporter) Resolve(ctx context.Context, desc ocispecs.Descriptor, id string, w worker.Worker) (solver.CacheManager, error) { cacheManagers := make([]solver.CacheManager, len(i.importers)) for i, importer := range i.importers { cm, err := importer.Resolve(ctx, desc, id+"-"+strconv.Itoa(i), w) if err != nil { return nil, err } cacheManagers[i] = cm } return solver.NewCombinedCacheManager(cacheManagers, nil), nil }
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
engine/remotecache/s3.go
package remotecache import ( "context" "os" "strconv" "time" awsConfig "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/moby/buildkit/cache/remotecache" s3remotecache "github.com/moby/buildkit/cache/remotecache/s3" "github.com/moby/buildkit/session" "github.com/moby/buildkit/util/bklog" ocispecs "github.com/opencontainers/image-spec/specs-go/v1"
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
engine/remotecache/s3.go
"github.com/pkg/errors" ) const ( bucketAttr = "bucket" regionAttr = "region" prefixAttr = "prefix" endpointURLAttr = "endpoint_url" usePathStyleAttr = "use_path_style" accessKeyAttr = "access_key_id" secretKeyAttr = "secret_access_key" sessionTokenAttr = "session_token" blobsSubprefix = "blobs/" manifestsSubprefix = "manifests/" ) func s3Exporter(ctx context.Context, g session.Group, attrs map[string]string) (remotecache.Exporter, error) { attrs["blob_prefix"] = blobsSubprefix attrs["manifests_prefix"] = manifestsSubprefix attrs["name"] = strconv.Itoa(int(time.Now().UnixNano())) + ".json" attrs["ignore-error"] = "true" return s3remotecache.ResolveCacheExporterFunc()(ctx, g, attrs) } func s3Importer(ctx context.Context, g session.Group, attrs map[string]string) (remotecache.Importer, ocispecs.Descriptor, error) { prefix := attrs[prefixAttr] bklog.G(ctx).Debugf("importing all manifests under prefix %q", prefix) region := attrs[regionAttr] if region == "" { region = os.Getenv("AWS_REGION") } bucket := attrs[bucketAttr] if bucket == "" {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
engine/remotecache/s3.go
bucket = os.Getenv("AWS_BUCKET") } accessKey := attrs[accessKeyAttr] secretKey := attrs[secretKeyAttr] sessionToken := attrs[sessionTokenAttr] endpointURL := attrs[endpointURLAttr] usePathStyle := attrs[usePathStyleAttr] == "true" cfg, err := awsConfig.LoadDefaultConfig(ctx, awsConfig.WithRegion(region)) if err != nil { return nil, ocispecs.Descriptor{}, errors.Errorf("Unable to load AWS SDK config, %v", err) } s3Client := s3.NewFromConfig(cfg, func(options *s3.Options) { if accessKey != "" && secretKey != "" { options.Credentials = credentials.NewStaticCredentialsProvider(accessKey, secretKey, sessionToken) } if endpointURL != "" { options.UsePathStyle = usePathStyle options.EndpointResolver = s3.EndpointResolverFromURL(endpointURL) } }) manifestsPrefix := prefix + manifestsSubprefix listObjectsPages := s3.NewListObjectsV2Paginator(s3Client, &s3.ListObjectsV2Input{ Bucket: aws.String(bucket), Prefix: aws.String(manifestsPrefix), }) var manifestKeys []string for listObjectsPages.HasMorePages() { listResp, err := listObjectsPages.NextPage(ctx) if err != nil {
closed
dagger/dagger
https://github.com/dagger/dagger
4,648
Fix cache export running when image/local exports run
We currently have to open separate sessions when doing an image/local export. This causes cache export to run in these subsessions, which is confusing because it means the manifest will be written for the subsession and then later the main session. Additionally, if the refs being tracked only end up in these subsessions, then if the manifest written by the main session at the end overwrites those refs might not be part of the export 😵‍💫 If you use the pooling support this is less of an issue since manifests are additive, but even then it's still not ideal.
https://github.com/dagger/dagger/issues/4648
https://github.com/dagger/dagger/pull/4715
2c04a71b0cdcbbe0e9712743a383f652a9f1211e
2b4831aff2fddbf68a5941b873e03ceb1e48f185
2023-02-24T21:53:07Z
go
2023-03-07T18:19:57Z
engine/remotecache/s3.go
if awsErr, ok := err.(awserr.Error); !ok || awsErr.Code() != "NotFound" { return nil, ocispecs.Descriptor{}, err } bklog.G(ctx).Debugf("not found error under prefix %s", prefix) } for _, obj := range listResp.Contents { manifestKeys = append(manifestKeys, *obj.Key) } } bklog.G(ctx).Debugf("found manifests under prefix %s: %+v", prefix, manifestKeys) importers := make([]remotecache.Importer, len(manifestKeys)) for i, manifestKey := range manifestKeys { theseAttrs := map[string]string{} for k, v := range attrs { theseAttrs[k] = v } theseAttrs["prefix"] = "" theseAttrs["manifests_prefix"] = "" theseAttrs["blobs_prefix"] = prefix + blobsSubprefix theseAttrs["name"] = manifestKey importer, _, err := s3remotecache.ResolveCacheImporterFunc()(ctx, g, theseAttrs) if err != nil { return nil, ocispecs.Descriptor{}, err } importers[i] = importer } return &combinedImporter{importers: importers}, ocispecs.Descriptor{}, nil }
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
package core import ( "context" "encoding/base32" "encoding/binary"
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
"encoding/hex" "encoding/json" "fmt" "io" "io/fs" "os" "path" "path/filepath" "sort" "strconv" "strings" "github.com/containerd/containerd/platforms" "github.com/dagger/dagger/core/pipeline" "github.com/dagger/dagger/network" "github.com/docker/distribution/reference" bkclient "github.com/moby/buildkit/client" "github.com/moby/buildkit/client/llb" "github.com/moby/buildkit/exporter/containerimage/exptypes" "github.com/moby/buildkit/frontend/dockerui" bkgw "github.com/moby/buildkit/frontend/gateway/client" "github.com/moby/buildkit/solver/pb" "github.com/opencontainers/go-digest" specs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" "github.com/zeebo/xxh3" ) type Container struct { ID ContainerID `json:"id"` } func NewContainer(id ContainerID, pipeline pipeline.Path, platform specs.Platform) (*Container, error) {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
if id == "" { payload := &containerIDPayload{ Pipeline: pipeline.Copy(), Platform: platform, } id, err := payload.Encode() if err != nil { return nil, err } return &Container{ID: id}, nil } return &Container{ID: id}, nil } type ContainerID string func (id ContainerID) String() string { return string(id) } func (id ContainerID) decode() (*containerIDPayload, error) { if id == "" { return &containerIDPayload{}, nil } var payload containerIDPayload if err := decodeID(&payload, id); err != nil { return nil, err } return &payload, nil } type containerIDPayload struct {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
FS *pb.Definition `json:"fs"` Config specs.ImageConfig `json:"cfg"` Pipeline pipeline.Path `json:"pipeline"` Mounts ContainerMounts `json:"mounts,omitempty"` Meta *pb.Definition `json:"meta,omitempty"` Platform specs.Platform `json:"platform,omitempty"` Secrets []ContainerSecret `json:"secret_env,omitempty"` Sockets []ContainerSocket `json:"sockets,omitempty"` ImageRef string `json:"image_ref,omitempty"` Hostname string `json:"hostname,omitempty"` Ports []ContainerPort `json:"ports,omitempty"` Services ServiceBindings `json:"services,omitempty"` HostAliases []HostAlias `json:"host_aliases,omitempty"` } type HostAlias struct {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
Alias string `json:"alias"` Target string `json:"target"` } type ContainerSecret struct { Secret SecretID `json:"secret"` EnvName string `json:"env,omitempty"` MountPath string `json:"path,omitempty"` } type ContainerSocket struct { Socket SocketID `json:"socket"` UnixPath string `json:"unix_path,omitempty"` } type ContainerPort struct {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
Port int `json:"port"` Protocol NetworkProtocol `json:"protocol"` Description *string `json:"description,omitempty"` } func (payload *containerIDPayload) Encode() (ContainerID, error) { id, err := encodeID(payload) if err != nil { return "", err } return ContainerID(id), nil } func (payload *containerIDPayload) FSState() (llb.State, error) { if payload.FS == nil { return llb.Scratch(), nil } return defToState(payload.FS) } const metaMountDestPath = "/.dagger_meta_mount" const metaSourcePath = "meta" func (payload *containerIDPayload) MetaState() (*llb.State, error) { if payload.Meta == nil { return nil, nil } metaSt, err := defToState(payload.Meta) if err != nil { return nil, err } return &metaSt, nil } type ContainerMount struct {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
Source *pb.Definition `json:"source,omitempty"` SourcePath string `json:"source_path,omitempty"` Target string `json:"target"` CacheID string `json:"cache_id,omitempty"` CacheSharingMode string `json:"cache_sharing,omitempty"` Tmpfs bool `json:"tmpfs,omitempty"` } func (mnt ContainerMount) SourceState() (llb.State, error) { if mnt.Source == nil { return llb.Scratch(), nil } return defToState(mnt.Source) } type ContainerMounts []ContainerMount func (mnts ContainerMounts) With(newMnt ContainerMount) ContainerMounts { mntsCp := make(ContainerMounts, 0, len(mnts)) parent := newMnt.Target + "/"
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
for _, mnt := range mnts { if mnt.Target == newMnt.Target || strings.HasPrefix(mnt.Target, parent) { continue } mntsCp = append(mntsCp, mnt) } mntsCp = append(mntsCp, newMnt) return mntsCp } func (container *Container) From(ctx context.Context, gw bkgw.Client, addr string) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } platform := payload.Platform p := payload.Pipeline.Add(pipeline.Pipeline{ Name: fmt.Sprintf("from %s", addr), }) refName, err := reference.ParseNormalizedNamed(addr) if err != nil { return nil, err } ref := reference.TagNameOnly(refName).String() digest, cfgBytes, err := gw.ResolveImageConfig(ctx, ref, llb.ResolveImageConfigOpt{ Platform: &platform, ResolveMode: llb.ResolveModeDefault.String(),
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
LogName: pipeline.CustomName{Name: fmt.Sprintf("resolve image config for %s", ref), Pipeline: p}.String(), }) if err != nil { return nil, err } digested, err := reference.WithDigest(refName, digest) if err != nil { return nil, err } var imgSpec specs.Image if err := json.Unmarshal(cfgBytes, &imgSpec); err != nil { return nil, err } dir, err := NewDirectory(ctx, llb.Image(addr, llb.WithCustomNamef("pull %s", ref), p.LLBOpt(), ), "/", payload.Pipeline, platform, nil) if err != nil { return nil, err } ctr, err := container.WithRootFS(ctx, dir) if err != nil { return nil, err } ctr, err = ctr.UpdateImageConfig(ctx, func(config specs.ImageConfig) specs.ImageConfig { newEnv := config.Env if imgSpec.Config.Env != nil {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
newEnv = append(newEnv, imgSpec.Config.Env...) } imgSpec.Config.Env = newEnv return imgSpec.Config }) if err != nil { return nil, err } payload, err = ctr.ID.decode() if err != nil { return nil, err } payload.ImageRef = digested.String() return container.containerFromPayload(payload) } const defaultDockerfileName = "Dockerfile" func (container *Container) Build(ctx context.Context, gw bkgw.Client, context *Directory, dockerfile string, buildArgs []BuildArg, target string) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } ctxPayload, err := context.ID.Decode() if err != nil { return nil, err } payload.Services.Merge(ctxPayload.Services) payload.ImageRef = "" return WithServices(ctx, gw, payload.Services, func() (*Container, error) { platform := payload.Platform
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
opts := map[string]string{ "platform": platforms.Format(platform), "contextsubdir": ctxPayload.Dir, } if dockerfile != "" { opts["filename"] = path.Join(ctxPayload.Dir, dockerfile) } else { opts["filename"] = path.Join(ctxPayload.Dir, defaultDockerfileName) } if target != "" { opts["target"] = target } for _, buildArg := range buildArgs { opts["build-arg:"+buildArg.Name] = buildArg.Value } inputs := map[string]*pb.Definition{ dockerui.DefaultLocalNameContext: ctxPayload.LLB, dockerui.DefaultLocalNameDockerfile: ctxPayload.LLB, } res, err := gw.Solve(ctx, bkgw.SolveRequest{ Frontend: "dockerfile.v0", FrontendOpt: opts, FrontendInputs: inputs, }) if err != nil { return nil, err } bkref, err := res.SingleRef() if err != nil { return nil, err
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
} var st llb.State if bkref == nil { st = llb.Scratch() } else { st, err = bkref.ToState() if err != nil { return nil, err } } def, err := st.Marshal(ctx, llb.Platform(platform)) if err != nil { return nil, err } pipeline := payload.Pipeline.Add(pipeline.Pipeline{ Name: "docker build", }) for dgst, metadata := range def.Metadata { metadata.ProgressGroup = pipeline.ProgressGroup() def.Metadata[dgst] = metadata } payload.FS = def.ToPB() cfgBytes, found := res.Metadata[exptypes.ExporterImageConfigKey] if found { var imgSpec specs.Image if err := json.Unmarshal(cfgBytes, &imgSpec); err != nil {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
return nil, err } payload.Config = imgSpec.Config } return container.containerFromPayload(payload) }) } func (container *Container) RootFS(ctx context.Context) (*Directory, error) { payload, err := container.ID.decode() if err != nil { return nil, err } return (&directoryIDPayload{ LLB: payload.FS, Platform: payload.Platform, Pipeline: payload.Pipeline, Services: payload.Services, }).ToDirectory() } func (container *Container) WithRootFS(ctx context.Context, dir *Directory) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } dirPayload, err := dir.ID.Decode() if err != nil { return nil, err } payload.FS = dirPayload.LLB payload.Services.Merge(dirPayload.Services)
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
payload.ImageRef = "" return container.containerFromPayload(payload) } func (container *Container) WithDirectory(ctx context.Context, gw bkgw.Client, subdir string, src *Directory, filter CopyFilter) (*Container, error) { return container.updateRootFS(ctx, subdir, func(dir *Directory) (*Directory, error) { return dir.WithDirectory(ctx, ".", src, filter) }) } func (container *Container) WithFile(ctx context.Context, gw bkgw.Client, subdir string, src *File, permissions fs.FileMode) (*Container, error) { return container.updateRootFS(ctx, subdir, func(dir *Directory) (*Directory, error) { return dir.WithFile(ctx, ".", src, permissions) }) } func (container *Container) WithNewFile(ctx context.Context, gw bkgw.Client, dest string, content []byte, permissions fs.FileMode) (*Container, error) { dir, file := filepath.Split(dest) return container.updateRootFS(ctx, dir, func(dir *Directory) (*Directory, error) { return dir.WithNewFile(ctx, file, content, permissions) }) } func (container *Container) WithMountedDirectory(ctx context.Context, target string, source *Directory) (*Container, error) { payload, err := source.ID.Decode() if err != nil { return nil, err } return container.withMounted(target, payload.LLB, payload.Dir, payload.Services) } func (container *Container) WithMountedFile(ctx context.Context, target string, source *File) (*Container, error) { payload, err := source.ID.decode() if err != nil {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
return nil, err } return container.withMounted(target, payload.LLB, payload.File, payload.Services) } func (container *Container) WithMountedCache(ctx context.Context, target string, cache CacheID, source *Directory, concurrency CacheSharingMode) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } cachePayload, err := cache.decode() if err != nil { return nil, err } target = absPath(payload.Config.WorkingDir, target) cacheSharingMode := "" switch concurrency { case CacheSharingModePrivate: cacheSharingMode = "private" case CacheSharingModeLocked: cacheSharingMode = "locked" default: cacheSharingMode = "shared" } mount := ContainerMount{ Target: target, CacheID: cachePayload.Sum(), CacheSharingMode: cacheSharingMode, } if source != nil { srcPayload, err := source.ID.Decode()
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
if err != nil { return nil, err } mount.Source = srcPayload.LLB mount.SourcePath = srcPayload.Dir } payload.Mounts = payload.Mounts.With(mount) payload.ImageRef = "" return container.containerFromPayload(payload) } func (container *Container) WithMountedTemp(ctx context.Context, target string) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } target = absPath(payload.Config.WorkingDir, target) payload.Mounts = payload.Mounts.With(ContainerMount{ Target: target, Tmpfs: true, }) payload.ImageRef = "" return container.containerFromPayload(payload) } func (container *Container) WithMountedSecret(ctx context.Context, target string, source *Secret) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err }
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
target = absPath(payload.Config.WorkingDir, target) payload.Secrets = append(payload.Secrets, ContainerSecret{ Secret: source.ID, MountPath: target, }) payload.ImageRef = "" return container.containerFromPayload(payload) } func (container *Container) WithoutMount(ctx context.Context, target string) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } target = absPath(payload.Config.WorkingDir, target) var found bool var foundIdx int for i := len(payload.Mounts) - 1; i >= 0; i-- { if payload.Mounts[i].Target == target { found = true foundIdx = i break } } if found { payload.Mounts = append(payload.Mounts[:foundIdx], payload.Mounts[foundIdx+1:]...) } payload.ImageRef = "" return container.containerFromPayload(payload)
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
} func (container *Container) Mounts(ctx context.Context) ([]string, error) { payload, err := container.ID.decode() if err != nil { return nil, err } mounts := []string{} for _, mnt := range payload.Mounts { mounts = append(mounts, mnt.Target) } return mounts, nil } func (container *Container) WithUnixSocket(ctx context.Context, target string, source *Socket) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } target = absPath(payload.Config.WorkingDir, target) newSocket := ContainerSocket{ Socket: source.ID, UnixPath: target, } var replaced bool for i, sock := range payload.Sockets { if sock.UnixPath == target { payload.Sockets[i] = newSocket replaced = true break } }
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
if !replaced { payload.Sockets = append(payload.Sockets, newSocket) } payload.ImageRef = "" return container.containerFromPayload(payload) } func (container *Container) WithoutUnixSocket(ctx context.Context, target string) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } target = absPath(payload.Config.WorkingDir, target) for i, sock := range payload.Sockets { if sock.UnixPath == target { payload.Sockets = append(payload.Sockets[:i], payload.Sockets[i+1:]...) break } } payload.ImageRef = "" return container.containerFromPayload(payload) } func (container *Container) WithSecretVariable(ctx context.Context, name string, secret *Secret) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } payload.Secrets = append(payload.Secrets, ContainerSecret{ Secret: secret.ID,
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
EnvName: name, }) payload.ImageRef = "" return container.containerFromPayload(payload) } func (container *Container) Directory(ctx context.Context, gw bkgw.Client, dirPath string) (*Directory, error) { dir, _, err := locatePath(ctx, container, dirPath, NewDirectory) if err != nil { return nil, err } info, err := dir.Stat(ctx, gw, ".") if err != nil { return nil, err } if !info.IsDir() { return nil, fmt.Errorf("path %s is a file, not a directory", dirPath) } return dir, nil } func (container *Container) File(ctx context.Context, gw bkgw.Client, filePath string) (*File, error) { file, _, err := locatePath(ctx, container, filePath, NewFile) if err != nil { return nil, err } info, err := file.Stat(ctx, gw)
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
if err != nil { return nil, err } if info.IsDir() { return nil, fmt.Errorf("path %s is a directory, not a file", filePath) } return file, nil } func locatePath[T *File | *Directory]( ctx context.Context, container *Container, containerPath string, init func(context.Context, llb.State, string, pipeline.Path, specs.Platform, ServiceBindings) (T, error), ) (T, *ContainerMount, error) { payload, err := container.ID.decode() if err != nil { return nil, nil, err } containerPath = absPath(payload.Config.WorkingDir, containerPath) var found T for i := len(payload.Mounts) - 1; i >= 0; i-- { mnt := payload.Mounts[i] if containerPath == mnt.Target || strings.HasPrefix(containerPath, mnt.Target+"/") { if mnt.Tmpfs { return nil, nil, fmt.Errorf("%s: cannot retrieve path from tmpfs", containerPath) } if mnt.CacheID != "" { return nil, nil, fmt.Errorf("%s: cannot retrieve path from cache", containerPath) }
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
st, err := mnt.SourceState() if err != nil { return nil, nil, err } sub := mnt.SourcePath if containerPath != mnt.Target { dirSub := strings.TrimPrefix(containerPath, mnt.Target+"/") if dirSub != "" { sub = path.Join(sub, dirSub) } } found, err := init(ctx, st, sub, payload.Pipeline, payload.Platform, payload.Services) if err != nil { return nil, nil, err } return found, &mnt, nil } } st, err := payload.FSState() if err != nil { return nil, nil, err } found, err = init(ctx, st, containerPath, payload.Pipeline, payload.Platform, payload.Services) if err != nil { return nil, nil, err } return found, nil, nil }
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
func (container *Container) withMounted(target string, srcDef *pb.Definition, srcPath string, svcs ServiceBindings) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } target = absPath(payload.Config.WorkingDir, target) payload.Mounts = payload.Mounts.With(ContainerMount{ Source: srcDef, SourcePath: srcPath, Target: target, }) payload.Services.Merge(svcs) payload.ImageRef = "" return container.containerFromPayload(payload) } func (container *Container) updateRootFS(ctx context.Context, subdir string, fn func(dir *Directory) (*Directory, error)) (*Container, error) { dir, mount, err := locatePath(ctx, container, subdir, NewDirectory) if err != nil { return nil, err } containerPayload, err := container.ID.decode() if err != nil { return nil, err } dirPayload, err := dir.ID.Decode() if err != nil { return nil, err } dirPayload.Pipeline = containerPayload.Pipeline
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
dir, err = dirPayload.ToDirectory() if err != nil { return nil, err } dir, err = fn(dir) if err != nil { return nil, err } if mount == nil { return container.WithRootFS(ctx, dir) } dirPayload, err = dir.ID.Decode() if err != nil { return nil, err } return container.withMounted(mount.Target, dirPayload.LLB, mount.SourcePath, nil) } func (container *Container) ImageConfig(ctx context.Context) (specs.ImageConfig, error) { payload, err := container.ID.decode() if err != nil { return specs.ImageConfig{}, err } return payload.Config, nil } func (container *Container) UpdateImageConfig(ctx context.Context, updateFn func(specs.ImageConfig) specs.ImageConfig) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err }
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
payload.Config = updateFn(payload.Config) return container.containerFromPayload(payload) } func (container *Container) Pipeline(ctx context.Context, name, description string, labels []pipeline.Label) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, fmt.Errorf("decode id: %w", err) } payload.Pipeline = payload.Pipeline.Add(pipeline.Pipeline{ Name: name, Description: description, Labels: labels, }) return container.containerFromPayload(payload) } func (container *Container) WithExec(ctx context.Context, gw bkgw.Client, defaultPlatform specs.Platform, opts ContainerExecOpts) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, fmt.Errorf("decode id: %w", err) } cfg := payload.Config mounts := payload.Mounts platform := payload.Platform if platform.OS == "" { platform = defaultPlatform } args := opts.Args if len(args) == 0 { args = cfg.Cmd
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
} if len(cfg.Entrypoint) > 0 { args = append(cfg.Entrypoint, args...) } runOpts := []llb.RunOption{ llb.Args(args), payload.Pipeline.LLBOpt(), llb.WithCustomNamef("exec %s", strings.Join(args, " ")), } if opts.ExperimentalPrivilegedNesting { runOpts = append(runOpts, llb.AddEnv("_DAGGER_ENABLE_NESTING", ""), ) } meta := llb.Mkdir(metaSourcePath, 0o777) if opts.Stdin != "" { meta = meta.Mkfile(path.Join(metaSourcePath, "stdin"), 0o600, []byte(opts.Stdin)) } runOpts = append(runOpts, llb.AddMount(metaMountDestPath, llb.Scratch().File(meta, pipeline.CustomName{Name: "creating dagger metadata", Internal: true}.LLBOpt(), payload.Pipeline.LLBOpt()), llb.SourcePath(metaSourcePath))) if opts.RedirectStdout != "" { runOpts = append(runOpts, llb.AddEnv("_DAGGER_REDIRECT_STDOUT", opts.RedirectStdout))
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
} if opts.RedirectStderr != "" { runOpts = append(runOpts, llb.AddEnv("_DAGGER_REDIRECT_STDERR", opts.RedirectStderr)) } for _, alias := range payload.HostAliases { runOpts = append(runOpts, llb.AddEnv("_DAGGER_HOSTNAME_ALIAS_"+alias.Alias, alias.Target)) } if cfg.User != "" { runOpts = append(runOpts, llb.User(cfg.User)) } if cfg.WorkingDir != "" { runOpts = append(runOpts, llb.Dir(cfg.WorkingDir)) } for _, env := range cfg.Env { name, val, ok := strings.Cut(env, "=") if !ok { _ = ok } if name == "_DAGGER_ENABLE_NESTING" && !opts.ExperimentalPrivilegedNesting { continue } if name == DebugFailedExecEnv { continue } runOpts = append(runOpts, llb.AddEnv(name, val))
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
} secretsToScrub := SecretToScrubInfo{} for i, secret := range payload.Secrets { secretOpts := []llb.SecretOption{llb.SecretID(secret.Secret.String())} var secretDest string switch { case secret.EnvName != "": secretDest = secret.EnvName secretOpts = append(secretOpts, llb.SecretAsEnv(true)) secretsToScrub.Envs = append(secretsToScrub.Envs, secret.EnvName) case secret.MountPath != "": secretDest = secret.MountPath secretsToScrub.Files = append(secretsToScrub.Files, secret.MountPath) default: return nil, fmt.Errorf("malformed secret config at index %d", i) } runOpts = append(runOpts, llb.AddSecret(secretDest, secretOpts...)) } if len(secretsToScrub.Envs) != 0 || len(secretsToScrub.Files) != 0 { sort.Strings(secretsToScrub.Envs) sort.Strings(secretsToScrub.Files) secretsToScrubJSON, err := json.Marshal(secretsToScrub) if err != nil { return nil, fmt.Errorf("scrub secrets json: %w", err) } runOpts = append(runOpts, llb.AddEnv("_DAGGER_SCRUB_SECRETS", string(secretsToScrubJSON))) } for _, socket := range payload.Sockets { if socket.UnixPath == "" {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
return nil, fmt.Errorf("unsupported socket: only unix paths are implemented") } runOpts = append(runOpts, llb.AddSSHSocket( llb.SSHID(socket.Socket.LLBID()), llb.SSHSocketTarget(socket.UnixPath), )) } fsSt, err := payload.FSState() if err != nil { return nil, fmt.Errorf("fs state: %w", err) } for _, mnt := range mounts { srcSt, err := mnt.SourceState() if err != nil { return nil, fmt.Errorf("mount %s: %w", mnt.Target, err) } mountOpts := []llb.MountOption{} if mnt.SourcePath != "" { mountOpts = append(mountOpts, llb.SourcePath(mnt.SourcePath)) } if mnt.CacheSharingMode != "" { var sharingMode llb.CacheMountSharingMode switch mnt.CacheSharingMode { case "shared": sharingMode = llb.CacheMountShared case "private": sharingMode = llb.CacheMountPrivate case "locked": sharingMode = llb.CacheMountLocked
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
default: return nil, errors.Errorf("invalid cache mount sharing mode %q", mnt.CacheSharingMode) } mountOpts = append(mountOpts, llb.AsPersistentCacheDir(mnt.CacheID, sharingMode)) } if mnt.Tmpfs { mountOpts = append(mountOpts, llb.Tmpfs()) } runOpts = append(runOpts, llb.AddMount(mnt.Target, srcSt, mountOpts...)) } if opts.InsecureRootCapabilities { runOpts = append(runOpts, llb.Security(llb.SecurityModeInsecure)) } execStNoHostname := fsSt.Run(runOpts...) constraints := llb.NewConstraints(llb.Platform(platform)) rootVtx := execStNoHostname.Root().Output().Vertex(ctx, constraints) digest, _, _, _, err := rootVtx.Marshal(ctx, constraints) if err != nil { return nil, fmt.Errorf("marshal: %w", err) } hostname := hostHash(digest) payload.Hostname = fmt.Sprintf("%s.%s", hostname, network.DNSDomain) runOpts = append(runOpts, llb.Hostname(hostname)) execSt := fsSt.Run(runOpts...) execDef, err := execSt.Root().Marshal(ctx, llb.Platform(platform)) if err != nil { return nil, fmt.Errorf("marshal root: %w", err)
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
} payload.FS = execDef.ToPB() metaDef, err := execSt.GetMount(metaMountDestPath).Marshal(ctx, llb.Platform(platform)) if err != nil { return nil, fmt.Errorf("get meta mount: %w", err) } payload.Meta = metaDef.ToPB() for i, mnt := range mounts { if mnt.Tmpfs || mnt.CacheID != "" { continue } mountSt := execSt.GetMount(mnt.Target) execMountDef, err := mountSt.Marshal(ctx, llb.Platform(platform)) if err != nil { return nil, fmt.Errorf("propagate %s: %w", mnt.Target, err) } mounts[i].Source = execMountDef.ToPB() } payload.Mounts = mounts payload.ImageRef = "" return container.containerFromPayload(payload) } func (container *Container) Evaluate(ctx context.Context, gw bkgw.Client) error { payload, err := container.ID.decode() if err != nil { return err } if payload.FS == nil {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
return nil } _, err = WithServices(ctx, gw, payload.Services, func() (*bkgw.Result, error) { st, err := payload.FSState() if err != nil { return nil, err } stDef, err := st.Marshal(ctx, llb.Platform(payload.Platform)) if err != nil { return nil, err } return gw.Solve(ctx, bkgw.SolveRequest{ Evaluate: true, Definition: stDef.ToPB(), }) }) return err } func (container *Container) ExitCode(ctx context.Context, gw bkgw.Client) (*int, error) { content, err := container.MetaFileContents(ctx, gw, "exitCode") if err != nil { return nil, err } if content == nil { return nil, nil } exitCode, err := strconv.Atoi(*content) if err != nil { return nil, err }
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
return &exitCode, nil } func (container *Container) Start(ctx context.Context, gw bkgw.Client) (*Service, error) { payload, err := container.ID.decode() if err != nil { return nil, err } health := newHealth(gw, payload.Hostname, payload.Ports) svcCtx, stop := context.WithCancel(context.Background()) checked := make(chan error, 1) go func() { checked <- health.Check(ctx) }() exited := make(chan error, 1) go func() { exited <- container.Evaluate(svcCtx, gw) }() select { case err := <-checked: if err != nil { stop() return nil, fmt.Errorf("health check errored: %w", err) } _ = stop return &Service{ Container: container, Detach: stop, }, nil case err := <-exited: stop()
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
if err != nil { return nil, fmt.Errorf("exited: %w", err) } return nil, fmt.Errorf("service exited before healthcheck") } } func (container *Container) MetaFileContents(ctx context.Context, gw bkgw.Client, filePath string) (*string, error) { payload, err := container.ID.decode() if err != nil { return nil, err } metaSt, err := payload.MetaState() if err != nil { return nil, err } if metaSt == nil { return nil, nil } file, err := NewFile( ctx, *metaSt, path.Join(metaSourcePath, filePath), payload.Pipeline, payload.Platform, payload.Services, ) if err != nil { return nil, err } content, err := file.Contents(ctx, gw)
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
if err != nil { return nil, err } strContent := string(content) return &strContent, nil } func (container *Container) Publish( ctx context.Context, ref string, platformVariants []ContainerID, bkClient *bkclient.Client, solveOpts bkclient.SolveOpt, solveCh chan<- *bkclient.SolveStatus, ) (string, error) { solveOpts.Exports = []bkclient.ExportEntry{ { Type: bkclient.ExporterImage, Attrs: map[string]string{ "name": ref, "push": "true", }, }, } ch, wg := mirrorCh(solveCh) defer wg.Wait() res, err := bkClient.Build(ctx, solveOpts, "", func(ctx context.Context, gw bkgw.Client) (*bkgw.Result, error) { return container.export(ctx, gw, platformVariants) }, ch) if err != nil {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
return "", err } refName, err := reference.ParseNormalizedNamed(ref) if err != nil { return "", err } imageDigest, found := res.ExporterResponse[exptypes.ExporterImageDigestKey] if found { dig, err := digest.Parse(imageDigest) if err != nil { return "", fmt.Errorf("parse digest: %w", err) } withDig, err := reference.WithDigest(refName, dig) if err != nil { return "", fmt.Errorf("with digest: %w", err) } return withDig.String(), nil } return ref, nil } func (container *Container) Platform() (specs.Platform, error) { payload, err := container.ID.decode() if err != nil { return specs.Platform{}, err } return payload.Platform, nil } func (container *Container) Export( ctx context.Context, host *Host,
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
dest string, platformVariants []ContainerID, bkClient *bkclient.Client, solveOpts bkclient.SolveOpt, solveCh chan<- *bkclient.SolveStatus, ) error { dest, err := host.NormalizeDest(dest) if err != nil { return err } out, err := os.Create(dest) if err != nil { return err } defer out.Close() return host.Export(ctx, bkclient.ExportEntry{ Type: bkclient.ExporterOCI, Output: func(map[string]string) (io.WriteCloser, error) { return out, nil }, }, dest, bkClient, solveOpts, solveCh, func(ctx context.Context, gw bkgw.Client) (*bkgw.Result, error) { return container.export(ctx, gw, platformVariants) }) } func (container *Container) Hostname() (string, error) { payload, err := container.ID.decode() if err != nil { return "", err } return payload.Hostname, nil
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
} func (container *Container) Endpoint(port int, scheme string) (string, error) { payload, err := container.ID.decode() if err != nil { return "", err } if port == 0 { if len(payload.Ports) == 0 { return "", fmt.Errorf("no ports exposed") } port = payload.Ports[0].Port } endpoint := fmt.Sprintf("%s:%d", payload.Hostname, port) if scheme != "" { endpoint = scheme + ":" + endpoint } return endpoint, nil } func (container *Container) WithExposedPort(port ContainerPort) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } payload.Ports = append(payload.Ports, port) id, err := payload.Encode() if err != nil { return nil, fmt.Errorf("encode: %w", err) } return &Container{ID: id}, nil }
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
func (container *Container) WithoutExposedPort(port int, protocol NetworkProtocol) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err } filtered := []ContainerPort{} for _, p := range payload.Ports { if p.Port != port || p.Protocol != protocol { filtered = append(filtered, p) } } payload.Ports = filtered id, err := payload.Encode() if err != nil { return nil, fmt.Errorf("encode: %w", err) } return &Container{ID: id}, nil } func (container *Container) ExposedPorts() ([]ContainerPort, error) { payload, err := container.ID.decode() if err != nil { return nil, err } return payload.Ports, nil } func (container *Container) WithServiceDependency(svc *Container, alias string) (*Container, error) { payload, err := container.ID.decode() if err != nil { return nil, err }
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
payload.Services.Merge(ServiceBindings{ svc.ID: AliasSet{alias}, }) if alias != "" { hn, err := svc.Hostname() if err != nil { return nil, fmt.Errorf("get hostname: %w", err) } payload.HostAliases = append(payload.HostAliases, HostAlias{ Alias: alias, Target: hn, }) } id, err := payload.Encode() if err != nil { return nil, fmt.Errorf("encode: %w", err) } return &Container{ID: id}, nil } func (container *Container) export( ctx context.Context, gw bkgw.Client, platformVariants []ContainerID, ) (*bkgw.Result, error) { payloads := []*containerIDPayload{} services := ServiceBindings{} if container.ID != "" { payload, err := container.ID.decode() if err != nil { return nil, err
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
} if payload.FS != nil { payloads = append(payloads, payload) services.Merge(payload.Services) } } for _, id := range platformVariants { payload, err := id.decode() if err != nil { return nil, err } if payload.FS != nil { payloads = append(payloads, payload) services.Merge(payload.Services) } } if len(payloads) == 0 { return nil, errors.New("no containers to export") } return WithServices(ctx, gw, services, func() (*bkgw.Result, error) { if len(payloads) == 1 { payload := payloads[0] st, err := payload.FSState() if err != nil { return nil, err } stDef, err := st.Marshal(ctx, llb.Platform(payload.Platform)) if err != nil { return nil, err
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
} res, err := gw.Solve(ctx, bkgw.SolveRequest{ Evaluate: true, Definition: stDef.ToPB(), }) if err != nil { return nil, err } cfgBytes, err := json.Marshal(specs.Image{ Architecture: payload.Platform.Architecture, OS: payload.Platform.OS, OSVersion: payload.Platform.OSVersion, OSFeatures: payload.Platform.OSFeatures, Config: payload.Config, }) if err != nil { return nil, err } res.AddMeta(exptypes.ExporterImageConfigKey, cfgBytes) return res, nil } res := bkgw.NewResult() expPlatforms := &exptypes.Platforms{ Platforms: make([]exptypes.Platform, len(payloads)), } for i, payload := range payloads { st, err := payload.FSState() if err != nil { return nil, err }
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
stDef, err := st.Marshal(ctx, llb.Platform(payload.Platform)) if err != nil { return nil, err } r, err := gw.Solve(ctx, bkgw.SolveRequest{ Evaluate: true, Definition: stDef.ToPB(), }) if err != nil { return nil, err } ref, err := r.SingleRef() if err != nil { return nil, err } platformKey := platforms.Format(payload.Platform) res.AddRef(platformKey, ref) expPlatforms.Platforms[i] = exptypes.Platform{ ID: platformKey, Platform: payload.Platform, } cfgBytes, err := json.Marshal(specs.Image{ Architecture: payload.Platform.Architecture, OS: payload.Platform.OS, OSVersion: payload.Platform.OSVersion, OSFeatures: payload.Platform.OSFeatures, Config: payload.Config, }) if err != nil { return nil, err
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
} res.AddMeta(fmt.Sprintf("%s/%s", exptypes.ExporterImageConfigKey, platformKey), cfgBytes) } platformBytes, err := json.Marshal(expPlatforms) if err != nil { return nil, err } res.AddMeta(exptypes.ExporterPlatformsKey, platformBytes) return res, nil }) } func (container *Container) ImageRef(ctx context.Context, gw bkgw.Client) (string, error) { payload, err := container.ID.decode() if err != nil { return "", err } imgRef := payload.ImageRef if imgRef != "" { return imgRef, nil } return "", errors.Errorf("Image reference can only be retrieved immediately after the 'Container.From' call. Error in fetching imageRef as the container image is changed") } func (container *Container) containerFromPayload(payload *containerIDPayload) (*Container, error) { id, err := payload.Encode() if err != nil { return nil, err } return &Container{ID: id}, nil } type ContainerExecOpts struct {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
Args []string Stdin string RedirectStdout string RedirectStderr string ExperimentalPrivilegedNesting bool InsecureRootCapabilities bool } type BuildArg struct {
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/container.go
Name string `json:"name"` Value string `json:"value"` } func hostHash(val digest.Digest) string { b, err := hex.DecodeString(val.Encoded()) if err != nil { panic(err) } return b32(xxh3.Hash(b)) } func b32(n uint64) string { var sum [8]byte binary.BigEndian.PutUint64(sum[:], n) return base32.HexEncoding. WithPadding(base32.NoPadding). EncodeToString(sum[:]) }
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/errors.go
package core import "github.com/pkg/errors" var ErrHostRWDisabled = errors.New("host read/write is disabled")
closed
dagger/dagger
https://github.com/dagger/dagger
4,668
Lazy executions are confusing to understand and sometimes don't work as expected
## Summary Developers are often confused by a property of the Dagger engine called "laziness": pipelines are executed at the latest possible moment, to maximize performance. There are several dimensions to this problem; below is an overview of different dimensions, and status of possible solutions. | Issues | Proposals | | ------------------------------------------- | ------------------------ | | [No `withExec`](#with-exec) | <li>#4833</li> | | [`Dockerfile` build (without exec)](#build) | <li>#5065</li> | | [Implicit query execution](#implicit) | <li>#5065</li> | | [Multiple ways to execute](#multiple) | “Pipeline builder” model | | [Documentation](#docs) | <li>#3617</li> | ## <a name="with-exec"></a>Issue: no `withExec` We had some users report that part of their pipeline wasn't being executed, for which they had to add a `WithExec(nil)` statement for it to work: ```go _, err := c.Container().Build(src).ExitCode(ctx) // doesn't work _, err := c.Container().From("alpine").ExitCode(ctx) // same thing ``` ### Explanation Users may assume that since they know there’s an `Entrypoint`/`Cmd` in the docker image it should work, but it’s just updating the dagger container metadata. There’s nothing to run, it’s equivalent to the following: ```go _, err := ctr. WithEntrypoint([]string{}). WithDefaultArgs(dagger.ContainerWithDefaultArgsOpts{ Args: []string{"/bin/sh"}, }) ExitCode(ctx) // nothing to execute! ``` `ExitCode` and `Stdout` only return something for the **last executed command**. That means the equivalent of a `RUN` instruction in a `Dockerfile` or running a container with `docker run`. ### Workaround Add a `WithExec()` to tell dagger to execute the container: ```diff _, err := client.Container(). Build(src). + WithExec(nil). ExitCode(ctx) ``` The empty (`nil`) argument to `WithExec` will execute the **entrypoint and default args** configured in the dagger container. > **Note** > If you replace the `.ExitCode()` with a `Publish()`, you see that `Build()` is called and the image is published, because `Publish` doesn’t depend on execution but `Build` is still a dependency. The same is true for a bound service: ```diff db := client.Container().From("postgres"). WithExposedPort(5432). + WithExec(nil) ctr := app.WithServiceBinding("db", db) ``` Here, `WithServiceBinding` clearly needs to execute/run the *postgres* container so that *app* can connect to it, so we need the `WithExec` here too (with `nil` for default entrypoint and arguments). ### Proposals To avoid astonishment, a fix was added (#4716) to raise an error when fields like `.ExitCode` or `.WithServiceBinding` (that depend on `WithExec`) are used on a container that hasn’t been executed. However, perhaps a better solution is to implicitly execute the entrypoint and default arguments because if you’re using a field that depends on an execution, we can assume that you mean to execute the container. This is what #4833 proposes, meaning the following would now work as expected by users: ```go // ExitCode → needs execution so use default exec _, err := c.Container().From("alpine").ExitCode(ctx) // WithServiceBinding → needs execution so use default exec db := client.Container().From("postgres").WithExposedPort(5432) ctr := app.WithServiceBinding("db", db) ``` ```[tasklist] ### No `withExec` - [x] #4716 - [ ] #4833 ``` ## <a name="build"></a>Issue: `Dockerfile` build (without exec) Some users just want to test if a `Dockerfile` build succeeds or not, and **don’t want to execute the entrypoint** (e.g., long running executable): ```go _, err = client.Container().Build(src).ExitCode(ctx) ``` In this case users are just using `ExitCode` as a way to trigger the build when they also don’t want to `Publish`. It’s the same problem as above, but the intent is different. ### Workarounds With #4919, you’ll be able to skip the entrypoint: ```go _, err = client.Container(). Build(src). WithExec([]string{"/bin/true"}, dagger.ContainerWithExecOpts{ SkipEntrypoint: true, }). ExitCode(ctx) ``` But executing the container isn’t even needed to build, so `ExitCode` isn’t a good choice here. It’s just simpler to use another field such as: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Rootfs().Entries(ctx) ``` However this isn’t intuitive and is clearly a workaround (not meant for this). ### Proposal Perhaps the best solution is to use a general synchronization primitive (#5065) that simply forces resolving the laziness in the pipeline, especially since the result is discarded in the above workarounds: ```diff - _, err = client.Container().Build(src).ExitCode(ctx) + _, err = client.Container().Build(src).Sync(ctx) ``` ```[tasklist] ### `Dockerfile` build (without exec) - [x] #4919 - [ ] #5065 ``` ## <a name="implicit"></a>Issue: Implicit query execution Some functions are “lazy” and don’t result in a [query execution](http://spec.graphql.org/October2021/#sec-Execution) (e.g., `From`, `Build`, `WithXXX`), while others execute (e.g., `ExitCode`, `Stdout`, `Publish`). It’s not clear to some users which is which. ### Explanation The model is implicit, with a “rule of thumb” in each language to hint which ones execute: - **Go:** functions taking a context and returning an error - **Python** and **Node.js:** `async` functions that need an `await` Essentially, each SDK’s codegen (the feature that introspects the API and builds a dagger client that is idiomatic in each language) **transforms [leaf fields](http://spec.graphql.org/October2021/#sec-Leaf-Field-Selections) into an implicit API request** when called, and return the **value from the response**. So the “rule of thumb” is based on the need to make a request to the GraphQL server, the problem is that it may not be immediately clear and the syntax can vary depending on the language so there’s different “rules” to understand. This was discussed in: - #3555 - #3558 ### Proposal The same [Pipeline Synchronization](https://github.com/dagger/dagger/issues/5065) proposal from the previous issue helps make this a bit more explicit: ```go _, err := ctr.Sync(ctx) ``` ```[tasklist] ### Implicit query execution - [x] #3555 - [x] #3558 - [ ] #5065 ``` ## <a name="multiple"></a>Issue: Multiple ways to execute “Execution” sometimes mean different things: - **Container execution** (i.e., `Container.withExec`) - **[Query execution](http://spec.graphql.org/October2021/#sec-Execution)** (i.e., making a request to the GraphQL API) - **”Engine” execution** (i.e., doing actual work in BuildKit) The *ID* fields like `Container.ID` for example, make a request to the API, but don’t do any actual work building the container. We reduced the scope of the issue in the SDKs by avoiding passing IDs around (#3558), and keeping the pipeline as lazy as possible until an output is needed (see [Implicit query execution](#implicit) above). More importantly, users have been using `.ExitCode(ctx)` as the goto solution to “synchronize” the laziness, but as we’ve seen in the above issues, it triggers the container to execute and there’s cases where you don’t want to do that. However, adding the general `.Sync()` (#4205) to fix that may make people shift to using it as the goto solution to “resolve” the laziness instead (“synchronize”), which actually makes sense. The problem is that we now go back to needing `WithExec(nil)` because `.Sync()` can’t assume you want to execute the container. That’s a catch 22 situation! **There’s no single execute function** to “rule them all”. It requires the user to have a good enough grasp on these concepts and the Dagger model to chose the right function for each purpose: ```go // exec the container (build since it's a dependency) c.Container().Build(src).ExitCode(ctx) // just build (don't exec) c.Container().Build(src).Sync(ctx) ``` ### Proposal During the “implicit vs explicit” discussions, the proposal for the most explicit solution was for a “pipeline builder” model (https://github.com/dagger/dagger/issues/3555#issuecomment-1301327344). The idea was to make a clear separation between **building** the lazy pipeline and **executing** the query: ```go // ExitCode doesn't implicitly execute query here! Still lazy. // Just setting expected output, and adding exec as a dependency. // Build is a dependency for exec so it also runs. q := c.Container().Build(src).ExitCode() // Same as above but don't care about output, just exec. q := c.Container().Build(src).WithExec(nil) // Same as above but don't want to exec, just build. q := c.Container().Build(src) // Only one way to execute query! client.Query(q) ``` ### Downsides - It’s a big **breaking change** so it’s not seen as a viable solution now - No great solution to grab output values - More boilerplate for simple things ### Solution Embrace the laziness! ## Issue: <a name="docs"></a>Documentation We have a guide on [Lazy Evaluation](https://docs.dagger.io/api/975146/concepts#lazy-evaluation) but it’s focused on the GraphQL API and isn’t enough to explain the above issues. We need better documentation to help users understand the “lazy DAG” model (https://github.com/dagger/dagger/issues/3617). It’s even more important if the “pipeline builder” model above isn’t viable. ```[tasklist] ### Documentation - [x] #3622 - [ ] #3617 ``` ## Affected users These are only some examples of users that were affected by this: - from @RonanQuigley > DX or a Bug: In order to have a dockerfile's entrypoint executed, why did we need to use a dummy withExec? There was a unamious 😩 in our team call after we figured this out. - https://discord.com/channels/707636530424053791/708371226174685314/1079926439064911972 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - https://discord.com/channels/707636530424053791/1080160708123185264/1080174051965812766 - #5010
https://github.com/dagger/dagger/issues/4668
https://github.com/dagger/dagger/pull/4716
f2a62f276d36918b0e453389dc7c63cad195da59
ad722627391f3e7d5bf51534f846913afc95d555
2023-02-28T17:37:30Z
go
2023-03-07T23:54:56Z
core/integration/container_test.go
package core import ( "context" _ "embed" "encoding/base64" "errors" "fmt" "io" "net" "os" "path/filepath" "strings" "testing" "dagger.io/dagger" "github.com/dagger/dagger/core" "github.com/dagger/dagger/core/schema" "github.com/dagger/dagger/internal/testutil" "github.com/moby/buildkit/identity" "github.com/stretchr/testify/require" ) func TestContainerScratch(t *testing.T) { t.Parallel() res := struct {