Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions internal/docker/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,12 @@ type StartContainerOption func(*startContainerConfig)

// StartWithVolumeMount mounts a named Docker volume at the given path in the
// container, e.g. to give the container a cache that outlives it.
//
// The volume is mounted with NoCopy, so it holds only what containers write to
// it. Otherwise Docker seeds a new volume with whatever the image has at the
// mount path, and containers that mount the same new volume at once, as
// concurrent python function builds do with the shared pip cache, all seed it
// together and fail with "mkdir ...: file exists".
func StartWithVolumeMount(name, containerPath string) StartContainerOption {
return func(cfg *startContainerConfig) {
if cfg.hostConfig == nil {
Expand Down
16 changes: 16 additions & 0 deletions internal/docker/docker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/mount"
"github.com/moby/moby/client"

"github.com/crossplane/crossplane-runtime/v2/pkg/errors"
Expand Down Expand Up @@ -167,3 +168,18 @@ func TestRunWithLabels(t *testing.T) {
})
}
}

func TestStartWithVolumeMount(t *testing.T) {
cfg := &startContainerConfig{}
StartWithVolumeMount("cache", "/root/.cache/pip")(cfg)

want := []mount.Mount{{
Type: mount.TypeVolume,
Source: "cache",
Target: "/root/.cache/pip",
VolumeOptions: &mount.VolumeOptions{NoCopy: true},
}}
if diff := cmp.Diff(want, cfg.hostConfig.Mounts); diff != "" {
t.Errorf("\nStartWithVolumeMount(...): a named volume must be mounted with NoCopy, or concurrent containers race to seed it from the image: -want, +got:\n%s", diff)
}
}
17 changes: 17 additions & 0 deletions internal/project/functions/python.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@ for arch in $ARCHS ; do
/fn_$arch/lib/python$PY_VERSION/site-packages
done
`

// pythonPipCacheVolume is a Docker volume holding pip's HTTP cache. It's
// mounted into every python build container so that wheel downloads are
// shared across builds, functions, and projects rather than re-fetched
// each time. pip manages the contents; `docker volume rm` clears it.
pythonPipCacheVolume = "crossplane-python-pip-cache"

// pythonPipCacheDir is pip's default cache location for root, which is
// the user the build container runs as.
pythonPipCacheDir = "/root/.cache/pip"
)

// pythonBuilder builds Python composition functions.
Expand All @@ -102,6 +112,10 @@ type pythonBuilder struct {
runtimeImage string
transport http.RoundTripper
configStore xpkg.ConfigStore

// pipCacheVolume is the Docker volume mounted as pip's cache in the
// build container.
pipCacheVolume string
}

func (b *pythonBuilder) Name() string {
Expand Down Expand Up @@ -233,6 +247,7 @@ func (b *pythonBuilder) buildVenv(ctx context.Context, c BuildContext) (map[stri
),
docker.StartWithCommand([]string{"sh", "-c", pythonBuildScript}),
docker.StartWithWorkingDirectory("/" + filepath.ToSlash(c.FunctionPath)),
docker.StartWithVolumeMount(b.pipCacheVolume, pythonPipCacheDir),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fair point that the build container can write to the cache, and you're right that revalidation isn't an integrity boundary: on a 304, pip reuses the cached body. I'll fix that wording in the description.

I'd still keep one shared cache. It's the same trust model as pip's per-user cache on a host, which any pip install running a build backend can write to, and as BuildKit cache mounts, which builds on a builder share by default. Building a project already means running its code, and the build container is there to keep the build environment consistent, not to isolate projects from each other. On ephemeral CI runners every job gets a fresh daemon, so nothing carries over between repos.

If maintainers would rather scope it per project, I'm happy to key the volume on the project's directory in a follow-up.

CC @haarchri

}
if schemasTar != nil {
opts = append(opts, docker.StartWithCopyFiles(schemasTar, "/"))
Expand Down Expand Up @@ -311,5 +326,7 @@ func newPythonBuilder(imageConfigs []pkgv1beta1.ImageConfig) *pythonBuilder {
runtimeImage: images.Image(images.Python, images.ImageRuntime),
transport: registryTransport,
configStore: clixpkg.NewStaticImageConfigStore(imageConfigs),

pipCacheVolume: pythonPipCacheVolume,
}
}
164 changes: 137 additions & 27 deletions internal/project/functions/python_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ package functions

import (
"context"
"crypto/rand"
"net/http"
"strings"
"testing"

Expand All @@ -31,8 +33,11 @@ import (
"github.com/google/go-containerregistry/pkg/v1/random"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/types"
"github.com/moby/moby/client"
"github.com/spf13/afero"
"golang.org/x/sync/errgroup"

"github.com/crossplane/crossplane-runtime/v2/pkg/errors"
"github.com/crossplane/crossplane-runtime/v2/pkg/xpkg"

"github.com/crossplane/cli/v2/internal/docker"
Expand All @@ -53,6 +58,105 @@ func TestPythonBuildDeterministic(t *testing.T) {
t.Skipf("python builds need a Docker-compatible runtime: %v", err)
}

baseImageRef, transport := pushPythonTestBaseImage(t)
b := &pythonBuilder{
buildImage: images.Image(images.Python, images.ImageBuild),
runtimeImage: baseImageRef.String(),
transport: transport,
configStore: clixpkg.NewStaticImageConfigStore(nil),
pipCacheVolume: testPipCacheVolume(t),
}
bc := BuildContext{
ProjectFS: afero.NewBasePathFs(afero.NewOsFs(), "testdata"),
FunctionPath: "python-function",
Architectures: []string{"amd64"},
}

digests := make([]string, 2)
for i := range digests {
d, err := pythonBuildDigest(context.Background(), b, bc)
if err != nil {
t.Fatalf("Build() %d failed: %v", i, err)
}
digests[i] = d
}

if digests[0] != digests[1] {
t.Errorf("Build() is not deterministic: rebuilding an unchanged function produced %s, then %s", digests[0], digests[1])
}
}

// TestPythonBuildPipCache builds a python function that depends on a package
// from PyPI, first twice at once on an empty pip cache volume, then again once
// the cache is warm. Every build must succeed and produce the same image: the
// cache may save downloads, but never change what gets installed.
func TestPythonBuildPipCache(t *testing.T) {
t.Parallel()

if err := docker.Check(t.Context()); err != nil {
t.Skipf("python builds need a Docker-compatible runtime: %v", err)
}

baseImageRef, transport := pushPythonTestBaseImage(t)
b := &pythonBuilder{
buildImage: images.Image(images.Python, images.ImageBuild),
runtimeImage: baseImageRef.String(),
transport: transport,
configStore: clixpkg.NewStaticImageConfigStore(nil),
pipCacheVolume: testPipCacheVolume(t),
}
bc := BuildContext{
ProjectFS: afero.NewBasePathFs(afero.NewOsFs(), "testdata"),
FunctionPath: "python-function-deps",
Architectures: []string{"amd64"},
}

// A project's functions build concurrently, so their containers can all
// mount the cache volume before it exists.
cold := make([]string, 2)
eg, ctx := errgroup.WithContext(t.Context())
for i := range cold {
eg.Go(func() error {
d, err := pythonBuildDigest(ctx, b, bc)
cold[i] = d
return err
})
}
if err := eg.Wait(); err != nil {
t.Fatalf("concurrent Build() on an empty pip cache failed: %v", err)
}

// Unless pip wrote to the volume, the build below isn't a warm one.
cid, err := docker.StartContainer(t.Context(), "", b.buildImage,
docker.StartWithVolumeMount(b.pipCacheVolume, pythonPipCacheDir),
docker.StartWithCommand([]string{"sh", "-c", `find "$0" -type f | grep -q .`, pythonPipCacheDir}),
)
if err != nil {
t.Fatal(err)
}
err = docker.WaitForContainerByID(t.Context(), cid)
_ = docker.StopContainerByID(context.Background(), cid)
if err != nil {
t.Fatalf("pip cache volume is empty after building: %v", err)
}

warm, err := pythonBuildDigest(t.Context(), b, bc)
if err != nil {
t.Fatalf("Build() with a warm pip cache failed: %v", err)
}

if cold[0] != cold[1] || cold[0] != warm {
t.Errorf("Build() output depends on the pip cache: concurrent cold builds produced %s and %s, then a warm build produced %s", cold[0], cold[1], warm)
}
}

// pushPythonTestBaseImage pushes a stand-in for the distroless python runtime
// base to a throwaway registry, and returns its reference and the transport to
// reach it with. Its content doesn't matter, only that the venv layer appended
// onto it is reproducible.
func pushPythonTestBaseImage(t *testing.T) (name.Reference, http.RoundTripper) {
t.Helper()

regSrv, err := registry.TLS("localhost")
if err != nil {
t.Fatal(err)
Expand All @@ -63,8 +167,6 @@ func TestPythonBuildDeterministic(t *testing.T) {
t.Fatal(err)
}

// A stand-in for the distroless python runtime base: its content doesn't
// matter, only that the venv layer appended onto it is reproducible.
baseImageRef := testRegistry.Repo("unittest-base-image").Tag("latest")
baseImage, err := mutate.ConfigFile(empty.Image, &v1.ConfigFile{Architecture: "amd64"})
if err != nil {
Expand All @@ -85,35 +187,43 @@ func TestPythonBuildDeterministic(t *testing.T) {
t.Fatal(err)
}

b := &pythonBuilder{
buildImage: images.Image(images.Python, images.ImageBuild),
runtimeImage: baseImageRef.String(),
transport: regSrv.Client().Transport,
configStore: clixpkg.NewStaticImageConfigStore(nil),
}
bc := BuildContext{
ProjectFS: afero.NewBasePathFs(afero.NewOsFs(), "testdata"),
FunctionPath: "python-function",
Architectures: []string{"amd64"},
}
return baseImageRef, regSrv.Client().Transport
}

digests := make([]string, 2)
for i := range digests {
imgs, err := b.Build(context.Background(), bc)
// testPipCacheVolume returns the name of a pip cache volume private to the
// test, so the test starts from an empty cache and leaves the user's alone.
// Docker creates the volume on first mount; it's removed when the test ends.
func testPipCacheVolume(t *testing.T) string {
t.Helper()

vol := "crossplane-test-pip-cache-" + strings.ToLower(rand.Text())
t.Cleanup(func() {
cli, err := docker.NewClient()
if err != nil {
t.Fatalf("Build() %d failed: %v", i, err)
}
if len(imgs) != 1 {
t.Fatalf("Build() %d returned %d images, want 1", i, len(imgs))
t.Logf("cannot remove pip cache volume %q: %v", vol, err)
return
}
d, err := imgs[0].Digest()
if err != nil {
t.Fatal(err)
if _, err := cli.VolumeRemove(context.Background(), vol, client.VolumeRemoveOptions{Force: true}); err != nil {
t.Logf("cannot remove pip cache volume %q: %v", vol, err)
}
digests[i] = d.String()
}
})

if digests[0] != digests[1] {
t.Errorf("Build() is not deterministic: rebuilding an unchanged function produced %s, then %s", digests[0], digests[1])
return vol
}

// pythonBuildDigest builds the function for a single architecture and returns
// the digest of the resulting image.
func pythonBuildDigest(ctx context.Context, b *pythonBuilder, bc BuildContext) (string, error) {
imgs, err := b.Build(ctx, bc)
if err != nil {
return "", err
}
if len(imgs) != 1 {
return "", errors.Errorf("Build() returned %d images, want 1", len(imgs))
}
d, err := imgs[0].Digest()
if err != nil {
return "", err
}
return d.String(), nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import click


@click.command()
def main():
click.echo("ok")
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[project]
name = "function"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = ["click==8.3.2"]

[project.scripts]
function = "function.main:main"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
Loading