Skip to content

feat: embed binary in image when pushing image #234

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jun 24, 2024
34 changes: 34 additions & 0 deletions envbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"fmt"
"io"
"io/fs"
"log"
"maps"
"net"
"net/http"
Expand Down Expand Up @@ -342,6 +343,21 @@ func Run(ctx context.Context, options Options) error {
}
}

if options.PushImage {
// Copy the envbuilder binary into the build context.
buildParams.DockerfileContent = buildParams.DockerfileContent + "\n" +
fmt.Sprintf("COPY %s %s", ".envbuilder", "/.envbuilder")

log.Println("FIXME show me the Dockerfile now: " + buildParams.DockerfileContent)

binPath := filepath.Join(MagicDir, "bin", "envbuilder")
dst := filepath.Join(buildParams.BuildContext, binPath)
err := copyFile(binPath, dst)
if err != nil {
return fmt.Errorf("aaa : %v", err)
}
}

HijackLogrus(func(entry *logrus.Entry) {
for _, line := range strings.Split(entry.Message, "\r") {
options.Logger(notcodersdk.LogLevelInfo, "#%d: %s", stageNumber, color.HiBlackString(line))
Expand Down Expand Up @@ -1159,3 +1175,21 @@ func maybeDeleteFilesystem(log LoggerFunc, force bool) error {

return util.DeleteFilesystem()
}

func copyFile(src, dst string) error {
content, err := os.ReadFile(src)
if err != nil {
return xerrors.Errorf("read file failed: %w", err)
}

err = os.MkdirAll(filepath.Dir(dst), 0755)
if err != nil {
return xerrors.Errorf("mkdir all failed: %w", err)
}

err = os.WriteFile(dst, content, 0644)
if err != nil {
return xerrors.Errorf("write file failed: %w", err)
}
return nil
}
69 changes: 69 additions & 0 deletions integration/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"github.com/go-git/go-billy/v5/memfs"
Expand Down Expand Up @@ -1354,6 +1355,74 @@ COPY --from=a /root/date.txt /date.txt`, testImageAlpine, testImageAlpine),
})
}

func TestEmbedBinaryImage(t *testing.T) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would annotate this test file with given/when/then markers.

t.Parallel()

srv := createGitServer(t, gitServerOptions{
files: map[string]string{
".devcontainer/Dockerfile": fmt.Sprintf("FROM %s\nRUN date --utc > /root/date.txt", testImageAlpine),
".devcontainer/devcontainer.json": `{
"name": "Test",
"build": {
"dockerfile": "Dockerfile"
},
}`,
},
})

testReg := setupInMemoryRegistry(t, setupInMemoryRegistryOpts{})
testRepo := testReg + "/test-embed-binary-image"
ref, err := name.ParseReference(testRepo + ":latest")
require.NoError(t, err)

_, err = runEnvbuilder(t, options{env: []string{
envbuilderEnv("GIT_URL", srv.URL),
envbuilderEnv("CACHE_REPO", testRepo),
envbuilderEnv("PUSH_IMAGE", "1"),
}})
require.NoError(t, err)

_, err = remote.Image(ref)
require.NoError(t, err, "expected image to be present after build + push")

ctx := context.Background()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is not a problem at all, but a cleaner approach would be:

ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()

cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
require.NoError(t, err)
t.Cleanup(func() {
cli.Close()
})

// Pull the image we just built
rc, err := cli.ImagePull(ctx, ref.String(), image.PullOptions{})
require.NoError(t, err)
t.Cleanup(func() { _ = rc.Close() })
_, err = io.ReadAll(rc)
require.NoError(t, err)

// Run it
ctr, err := cli.ContainerCreate(ctx, &container.Config{
Image: ref.String(),
Cmd: []string{"sleep", "infinity"},
Labels: map[string]string{
testContainerLabel: "true",
},
}, nil, nil, nil, "")
require.NoError(t, err)
t.Cleanup(func() {
_ = cli.ContainerRemove(ctx, ctr.ID, container.RemoveOptions{
RemoveVolumes: true,
Force: true,
})
})
err = cli.ContainerStart(ctx, ctr.ID, container.StartOptions{})
require.NoError(t, err)

out := execContainer(t, ctr.ID, "[[ -f \"/.envbuilder/bin/envbuilder\" ]] && echo \"exists\"")
require.Equal(t, "exists", strings.TrimSpace(out))
out = execContainer(t, ctr.ID, "cat /root/date.txt")
require.NotEmpty(t, strings.TrimSpace(out))
}

type setupInMemoryRegistryOpts struct {
Username string
Password string
Expand Down