diff --git a/internal/docker/docker.go b/internal/docker/docker.go index e249a39e..c7b878fb 100644 --- a/internal/docker/docker.go +++ b/internal/docker/docker.go @@ -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 { diff --git a/internal/docker/docker_test.go b/internal/docker/docker_test.go index 6f24c178..3718d3cb 100644 --- a/internal/docker/docker_test.go +++ b/internal/docker/docker_test.go @@ -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" @@ -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) + } +} diff --git a/internal/project/functions/python.go b/internal/project/functions/python.go index c3550726..6fcb4c98 100644 --- a/internal/project/functions/python.go +++ b/internal/project/functions/python.go @@ -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. @@ -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 { @@ -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), } if schemasTar != nil { opts = append(opts, docker.StartWithCopyFiles(schemasTar, "/")) @@ -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, } } diff --git a/internal/project/functions/python_integration_test.go b/internal/project/functions/python_integration_test.go index 57d12558..b25756da 100644 --- a/internal/project/functions/python_integration_test.go +++ b/internal/project/functions/python_integration_test.go @@ -20,6 +20,8 @@ package functions import ( "context" + "crypto/rand" + "net/http" "strings" "testing" @@ -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" @@ -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) @@ -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 { @@ -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 } diff --git a/internal/project/functions/testdata/python-function-deps/function/__init__.py b/internal/project/functions/testdata/python-function-deps/function/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/internal/project/functions/testdata/python-function-deps/function/main.py b/internal/project/functions/testdata/python-function-deps/function/main.py new file mode 100644 index 00000000..d9797e74 --- /dev/null +++ b/internal/project/functions/testdata/python-function-deps/function/main.py @@ -0,0 +1,6 @@ +import click + + +@click.command() +def main(): + click.echo("ok") diff --git a/internal/project/functions/testdata/python-function-deps/pyproject.toml b/internal/project/functions/testdata/python-function-deps/pyproject.toml new file mode 100644 index 00000000..842f9878 --- /dev/null +++ b/internal/project/functions/testdata/python-function-deps/pyproject.toml @@ -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"