From d7e9c91b01115467e1f12d781b709e228dc230c6 Mon Sep 17 00:00:00 2001 From: Andrea Luzzardi Date: Wed, 17 Mar 2021 14:54:51 -0700 Subject: [PATCH] buildkit: wait for buildkitd to be ready before connecting Signed-off-by: Andrea Luzzardi --- pkg/buildkitd/buildkitd.go | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/pkg/buildkitd/buildkitd.go b/pkg/buildkitd/buildkitd.go index 7900762f..e3b93f82 100644 --- a/pkg/buildkitd/buildkitd.go +++ b/pkg/buildkitd/buildkitd.go @@ -2,11 +2,15 @@ package buildkitd import ( "context" + "errors" "fmt" "os/exec" "strings" + "time" "github.com/docker/distribution/reference" + bk "github.com/moby/buildkit/client" + _ "github.com/moby/buildkit/client/connhelper/dockercontainer" // import the container connection driver "github.com/rs/zerolog/log" ) @@ -120,7 +124,31 @@ func startBuildkit(ctx context.Context) error { Msg("unable to start buildkitd") return err } - return nil + return waitBuildkit(ctx) +} + +// waitBuildkit waits for the buildkit daemon to be responsive. +func waitBuildkit(ctx context.Context) error { + c, err := bk.New(ctx, "docker-container://"+containerName) + if err != nil { + return err + } + defer c.Close() + + // Try to connect every 100ms up to 50 times (5 seconds total) + const ( + retryPeriod = 100 * time.Millisecond + retryAttempts = 50 + ) + + for retry := 0; retry < retryAttempts; retry++ { + _, err = c.ListWorkers(ctx) + if err == nil { + return nil + } + time.Sleep(retryPeriod) + } + return errors.New("buildkit failed to respond") } func remvoveBuildkit(ctx context.Context) error {