Skip to content

Container { exitCode } doesn't work if the command fails #3192

Closed as not planned

Description

@vito

We currently expose this API:

type Container {
  exitCode: Int
}

...but the only possible value returned here is null or 0. If the command exits nonzero Buildkit will error instead.

We could have the shim mask the exit status, but we would probably only want to do that if the user is requesting exitCode, but then that changes the underlying LLB. 🤔

The same is true for stdout and stderr that share the same underlying code.

Activity

  1. sipsma commented on Sep 30, 2022

    @sipsma
    Contributor

    Yeah this another one that's harder than it looks. I completely agree we can't have the shim exit 0 as that'll cache the failure.

    My immediate thought is to do something like:

    1. Have the shim check the error code and then write it to a mount (similar to the mounts used for stdout/stderr today).
    2. Have the shim then exit with that error too
    3. Use this mechanism to grab the FS changes after the error occurs: https://github.com/sipsma/buildkit/blob/61307b8f2e73d681721b51856c10cb8606e5ea70/client/build_test.go#L1284-L1284
    4. Use that to return the exit code

    I actually think we might end up needing to do something similar to fix this issue too: #3025

    Take this with a grain of salt, I haven't used that whole SolveError mechanism before and I also would love it if there was something simpler; this is just what comes to mind right away.

  2. sipsma commented on Sep 30, 2022

    @sipsma
    Contributor

    Another implication of the above is that the execop failure is no longer a graphql error like it is today. I think that's fine? But it is different than today.

    EDIT: I also just realized it's kind of contradictory with what I described in #3025 in that there I'm saying this information (stderr, exit code, etc.) should be included in the graphql error message, whereas here we are saying it just gets returned as selected.

    I suppose one other option is that an execop failing is not inherently an error, but if you try to do something that requires its success (i.e. read a file, do another exec, etc.) then that would be an error? Thinking out loud, not sure yet.

  3. aluzzardi commented on Sep 30, 2022

    @aluzzardi
    Contributor

    I was thinking eventually exec would take some options (e.g. continueOnFailure, in which case exitCode will be non-zero ... maybe at some point some retry options?)

    Main problem is what @sipsma pointed out -- if the shim exits with 0, then buildkit will cache the failure and not retry (e.g. apk add curl would end up "cached", even if there was a transient network issue, and will not attempt to retry)

  4. GiedriusS commented on Nov 9, 2022

    @GiedriusS

    This is probably the biggest blocker for me ATM. I have even resorted to doing something like this as a workaround:

    lint = lint.Exec(dagger.ContainerExecOpts{
      Args: []string{"/bin/sh", "-c", `/go/bin/golangci-lint run -v && printf OK > /ok || printf FAIL > /ok`},
    })
    
    f := lint.File("/ok")
    content, err := f.Contents(ctx)
    if err != nil {
      return err
    }
    if content != "OK" {
      return fmt.Errorf("linting failed (got %s)", content)
    }
  5. byungjoon72 commented on Nov 10, 2022

    @byungjoon72

    For some commands like gcloud that emit normal output to stderr (but exit with 0), I updated the above workaround a little.

    // ExecAndWait executes the given opts command and waits for its result.
    func ExecAndWait(ctx context.Context, container *dagger.Container, description string, opts dagger.ContainerExecOpts) (*dagger.Container, error) {
        opts.Args = append([]string{"/bin/sh", "-c"}, strings.Join(opts.Args, " ")+" 2>/tmp/fail.log || echo \"exit-code:$?\" >> /tmp/fail.log")
        container = container.Exec(opts)
    
        content, err := container.File("/tmp/fail.log").Contents(ctx)
        if err != nil {
            return container, fmt.Errorf("%v: error returned: %v content: %v", description, err, content)
        }
    
        exitCode, errLog := parseFailLog(content)
        if exitCode != 0 {
            return container, fmt.Errorf("%v: command failed: %v", description, fmt.Sprintf("%v", errLog))
        }
    
        return container, nil
    }
    
    // This is for some weird cases like gcloud. gcloud CLI returns output to stderr,
    // though the exit code itself is 0 (means no error)
    func parseFailLog(content string) (int, string) {
        var (
            failLog = make([]string, 0)
            // if there is no exit-code recorded in the given content, we consider that as non-error
            // because we only write the exit-code line when there is an error.
            exitCode = 0
        )
    
        scanner := bufio.NewScanner(strings.NewReader(content))
        for scanner.Scan() {
            txt := scanner.Text()
            if strings.Index(txt, "exit-code:") < 0 {
                failLog = append(failLog, txt)
            } else {
                c, err := strconv.Atoi(strings.Split(txt, ":")[1])
                if err != nil {
                    log.Fatalf("exit code value is not int: %v", err)
                }
                exitCode = c
                break
            }
        }
    
        return exitCode, strings.Join(failLog, "\n")
    }
    
  6. aluzzardi commented on Nov 10, 2022

    @aluzzardi
    Contributor

    This is probably the biggest blocker for me ATM. I have even resorted to doing something like this as a workaround:

    @GiedriusS As a workaround, what if you just let it fail on its own?

    _, err := lint.Exec(dagger.ContainerExecOpts{
      Args: []string{"/bin/sh", "-c", `/go/bin/golangci-lint run -v`},
    }).ExitCode()
    if err != nil {
      return err
    }

    In any case, logs are printed to the console (if using dagger.Connect(ctx, dagger.WithLogOutput(os.Stderr))), so you can get away without capturing stderr in code.

  7. added
    area/engine
    and removed on Dec 5, 2022
  8. aluzzardi commented on Dec 9, 2022

    @aluzzardi
    Contributor

    Bumping this is priority

    Here's a quick and dirty proposal:

    • Shim communicates with core
      • Perhaps we mount another gRPC service in containers. Or it could be a dumb HTTP POST, whatever
      • Shim reports back stdout, stderr, exitCode in addition to storing to /meta
      • We probably need an identifier to come back via gRPC so we know which container is talking to us. Could potentially pack it in HTTP_PROXY as @sipsma mentioned (as it won't bust the cache)
    • We add some new control options to WithExec
      • e.g. abortOnFailure?
      • In which case, when an exec operation fails, we don't fail the entire query and instead use stdout/stderr/exitCode from the shim

    Shortcomings:

    • This is not re-entrant: "streamed" shim metadata lives in memory. I think this could have a bunch of side effects as it's a very different model than what we have with Container ID
    • abortOnFailure is stranger than it looks with nesting
      • withExec("exit 1").WithExec("true").ExitCode() --> if we continue on failure, what is exit code even supposed to be?

    After typing this, I don't think this is a viable option.

  9. sipsma commented on Dec 9, 2022

    @sipsma
    Contributor

    @aluzzardi

    Perhaps we mount another gRPC service in containers. Or it could be a dumb HTTP POST, whatever

    I don't think we'd need this. If we allow an exec to fail without it being an actual error returned to the client (via abortOnFailure or similar) then we can just store all the metadata in /meta and have the shim exit 0. The real exit code (plus stdout/err) will be easily accessible still.

    The other thing is I think we can improve most of the questions we get around this by just including the output of the exec in the graphql error when it fails. That's simpler than trying to figure out how to allow for failure not result in a graphql error at all: #3025

  10. 22 remaining items

  11. helderco commented on Apr 10, 2023

    @helderco
    Contributor

    Just referencing another confused user in:

    Update: I'm currently writing a proposal to fix this in a backwards compatible way.

  12. helderco commented on Apr 10, 2023

    @helderco
    Contributor

    As I mentioned before, it seems to me that even though this has been flagged as a priority, it hasn't moved forward because we don't want to break users that have come to rely on the current behavior.

    Here's my proposal to fix that in a new call, and deprecate exitCode:

    I also recognize that this was marked as stuck by @mircubed in #3192 (comment), pending a summary on what the solution and current stop gaps are. The above proposal suggests an answer to that.

    However, I'm assuming in the proposal that we can solve this based on:

    Dropping a note from a conversation had with @sipsma in Discord: this should be easier to fix now that we have the plumbing for collecting the stdout/stderr/exit status that we added for better error messages.

    - Originally posted by @vito in #3192 (comment)

    Especially in a new encapsulating field, while making the current ones deprecated. However, I'm not entirely sure if @vito and @sipsma have considered the effect on cache that was raised by @aluzzardi here.

    Can you guys confirm we can technically fix this, with @aluzzardi's concerns addressed?

  13. itaischwartz commented on Apr 17, 2023

    @itaischwartz

    For me, this is a blocker for using Dagger in a local development environment.

  14. sipsma commented on Apr 19, 2023

    @sipsma
    Contributor

    Especially in a new encapsulating field, while making the current ones deprecated. However, I'm not entirely sure if @vito and @sipsma have considered the effect on cache that was raised by @aluzzardi here.

    Yeah we can implement the proposal you linked to with the desired caching behavior.

    That being said, there technically are two options for what the desired caching behavior is:

    1. Same behavior as today: non-zero exit code means the result will not be cached.
    2. New behavior: if you use this new api and exit non-zero, we will still cache the result

    I strongly prefer 1, maybe it's obvious, but seemed worth mentioning. I can technically imagine some very specific scenarios in which users could want caching of non-zero exits, but that's likely obscure and could also become a separate flag to toggle that behavior on/off at a later date if needed.


    To implement 1, we can re-use the mechanism here, which is an obscure buildkit feature that lets you take an ExecOp which failed and spin up a new gateway container that has all the filesystem modifications made by the exec up to the point of failure. That currently integrates with our shim here to enable grabbing stdout/stderr.

    We are actually already writing the exit code to the same mount next to stdout/stderr here, so we just need to add support for grabbing that value after the failure and plumbing it through to the new API you proposed @helderco. We probably need to tweak some things so that we can return actual values instead of just annotating the error message like we do today, but it shouldn't require anything radically different than the existing code.

  15. helderco commented on Apr 19, 2023

    @helderco
    Contributor

    Thanks for the feedback @vito (Discord) and @sipsma. I'm clear on the technical feasibility, but I'm not entirely sure on caching yet.

    • apk install: A failure in this kind of command could be due to a network issue, but also referencing a package that doesn't exist. You don't want to cache on the former but it's no use retrying on the latter.
    • go test: Or lint, etc... most common issue in these cases is that the source code under test needs fixing. In this case I'd want to cache. The run time can easily be long but the result will be the same so it's wasteful. On the other hand there could also be a bigger issue at hand and debugging it could be harder.

    It doesn't seem like it's possible to tell the difference in a smart way here, so what feels safest is to not cache by default, but add a flag to withExec to allow caching on failure. That would enable tuning performance for the cases where it makes sense, but it would need to be explicit (thinking about verbosity in the common case of running tests).

    After writing this I realize that's basically what you said for 1, @sipsma, so I agree. Just had to lay it out. 😁

  16. vito commented on Apr 19, 2023

    @vito
    ContributorAuthor

    +1 to not caching failures by default; seems like the most ergonomic choice when it comes to network flakes etc. In an ideal world we would be able to cache go test failures but I think that'd be an uphill battle with folks who want to just re-run on a test flake. (They should "just" fix the tests, but...)

    One use case I can think of for caching failures is if you're running a command that you expect to fail and you're using it almost like a conditional. For example, you might run ldd ./foo to make sure that you've built a static binary. In that case failure is success! I do this in Bass here, the downside being it shows a scary ldd "failure" in the progress output.

  17. helderco commented on Apr 19, 2023

    @helderco
    Contributor

    The proposal to create a new encapsulating field isn’t perfect (since I haven’t found a really good DX for explicitly selecting which leaf fields you want), but I think I have convincing arguments for why it’s worth it (I’ll update the proposals to add clarity on some things).

    Since most users have come to depend on the current behavior, it seems to me that the higher risk is in the breaking change by fixing the current exitCode, stdout and stderr fields.

    Unless there’s consensus that we should fix them anyway, this issue will remain stuck for a while longer until we have an approved design for a new pattern.

    I'll update the description with current workarounds in the meantime.

  18. gerhard commented on May 9, 2023

    @gerhard
    Contributor

    How does our today's discussion about your R&D work on exit codes affect this @helderco?

  19. helderco commented on May 10, 2023

    @helderco
    Contributor

    How does our today's discussion about your R&D work on exit codes affect this @helderco?

    I’ve withdrawn the #4921 proposal, suggesting now a different direction:

    That issue explains everything.

  20. gerhard commented on May 11, 2023

    @gerhard
    Contributor

    If you think @helderco that we should close this issue in favour of #5124, go for it! cc @mircubed

  21. helderco commented on May 25, 2023

    @helderco
    Contributor

    If I get agreement for deprecating exitCode, this issue can be closed.

  22. helderco commented on Jul 18, 2023

    @helderco
    Contributor

    Closing in favor of:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area/enginekind/bugkind/user-request

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions