Skip to content

An open-source, faster Devin alternative

TypeScript

awsvm: build a custom-template MicroVM image, mirroring deploy/microvm/publish.sh — the artifact is DERIVED from the pool image's own ZIP (swap only the Dockerfile) so the agent binaries are byte-identical to every pooled box, and base-image/build-role ARNs are read off the pool image's ACTIVE version rather than configured, so they cannot go stale when it is rebuilt; a failed build reports the reason from the build record plus its CloudWatch log group, since a bare CREATE_FAILED cannot distinguish a typo'd package from an x86 binary on an ARM-only platform

Brian Reardonf40b66e08636
diff --git a/internal/awsvm/client.go b/internal/awsvm/client.go
index 5ec559cd..e98d247c 100644
--- a/internal/awsvm/client.go
+++ b/internal/awsvm/client.go
@@ -93,6 +93,21 @@ type Config struct {
// avoid.
SizeImages map[int]string
+ // TemplateBaseImageArn and TemplateBuildRoleArn are the two ARNs
+ // create-microvm-image requires when building a CUSTOM TEMPLATE image.
+ //
+ // They mirror deploy/microvm/publish.sh (MICROVM_BASE_IMAGE_ARN defaulting
+ // to the AWS-owned al2023-1 base, and the build role it passes). The base
+ // is service-owned and snapshot-compatible, which is why a customer cannot
+ // choose their own FROM: the image must derive from it.
+ //
+ // TemplateBuildRoleArn is the role AWS assumes to RUN THE CUSTOMER'S
+ // DOCKERFILE. It is the one place customer-authored commands execute with
+ // credentials of ours, so it must carry the minimum needed to pull the
+ // artifact and write logs — never the role used elsewhere in this package.
+ TemplateBaseImageArn string
+ TemplateBuildRoleArn string
+
// ExecutionRoleArn is assumed by the MicroVM itself, for the guest's own AWS
// access. It is NOT the role this worker uses to call the API.
ExecutionRoleArn string
@@ -272,11 +287,27 @@ type API interface {
CreateMicrovmAuthToken(context.Context, *lambdamicrovms.CreateMicrovmAuthTokenInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.CreateMicrovmAuthTokenOutput, error)
}
+// ImageAPI is the image-MANAGEMENT surface, kept separate from API on purpose.
+//
+// API is the runtime surface every cell exercises on the hot path, and several
+// tests implement it in full. Image management is used only by the custom
+// template builder, so folding these in would force every existing fake to grow
+// four methods it never calls. A cell with no builder configured simply leaves
+// this nil.
+type ImageAPI interface {
+ CreateMicrovmImage(context.Context, *lambdamicrovms.CreateMicrovmImageInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.CreateMicrovmImageOutput, error)
+ GetMicrovmImage(context.Context, *lambdamicrovms.GetMicrovmImageInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmImageOutput, error)
+ GetMicrovmImageVersion(context.Context, *lambdamicrovms.GetMicrovmImageVersionInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmImageVersionOutput, error)
+ GetMicrovmImageBuild(context.Context, *lambdamicrovms.GetMicrovmImageBuildInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmImageBuildOutput, error)
+ DeleteMicrovmImage(context.Context, *lambdamicrovms.DeleteMicrovmImageInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.DeleteMicrovmImageOutput, error)
+}
+
// Client wraps the MicroVM API with the bits every caller needs: idempotent
// runs, a token cache, and state translation.
type Client struct {
- api API
- cfg Config
+ api API
+ imageAPI ImageAPI
+ cfg Config
mu sync.Mutex
tokens map[string]*cachedToken
@@ -291,10 +322,12 @@ type cachedToken struct {
// NewClient builds a Client from an already-resolved AWS config.
func NewClient(awsCfg aws.Config, cfg Config) *Client {
cfg.applyDefaults()
+ svc := lambdamicrovms.NewFromConfig(awsCfg)
return &Client{
- api: lambdamicrovms.NewFromConfig(awsCfg),
- cfg: cfg,
- tokens: make(map[string]*cachedToken),
+ api: svc,
+ imageAPI: svc,
+ cfg: cfg,
+ tokens: make(map[string]*cachedToken),
}
}
@@ -304,6 +337,13 @@ func NewClientWithAPI(api API, cfg Config) *Client {
return &Client{api: api, cfg: cfg, tokens: make(map[string]*cachedToken)}
}
+// WithImageAPI attaches the image-management surface. Separate from
+// NewClientWithAPI so existing fakes keep working unchanged.
+func (c *Client) WithImageAPI(api ImageAPI) *Client {
+ c.imageAPI = api
+ return c
+}
+
// Config exposes the resolved configuration (defaults applied).
func (c *Client) Config() Config { return c.cfg }
diff --git a/internal/awsvm/imagebuild.go b/internal/awsvm/imagebuild.go
new file mode 100644
index 00000000..41a595db
--- /dev/null
+++ b/internal/awsvm/imagebuild.go
@@ -0,0 +1,376 @@
+package awsvm
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "log"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+)
+
+// Building a custom-template image.
+//
+// This is the server-side equivalent of deploy/microvm/{build,publish}.sh, and
+// deliberately mirrors their parameters — a template image that differs from
+// the pool image in its hooks, architecture or memory floor is a box that
+// behaves differently from every other box on the fleet.
+//
+// The customer's Dockerfile is compiled elsewhere (api.RenderMicrovmDockerfile);
+// this takes the rendered text and turns it into an image ARN.
+
+// ObjectStore is the subset of S3 this needs. An interface rather than the
+// concrete client so the packaging logic is testable without AWS.
+type ObjectStore interface {
+ Get(ctx context.Context, uri string) ([]byte, error)
+ Put(ctx context.Context, uri string, body []byte) error
+}
+
+// TemplateBuildInput describes one custom-template image build.
+type TemplateBuildInput struct {
+ // ImageName is the AWS-side resource name. Must be unique per template and
+ // must be recognisably ours — see the naming note in Build.
+ ImageName string
+ // Dockerfile is the fully rendered image definition (base prologue +
+ // customer layers + agent epilogue).
+ Dockerfile string
+ // ContextFiles are extra files the Dockerfile's COPY lines reference,
+ // keyed by their path inside the build context.
+ ContextFiles map[string][]byte
+ // ArtifactURI is where the build context ZIP is uploaded, e.g.
+ // s3://bucket/templates/<id>.zip.
+ ArtifactURI string
+ // Tags are applied to the image resource. Ownership lives here.
+ Tags map[string]string
+}
+
+// BuildTemplateImage packages, creates and waits for a custom-template image,
+// returning its ARN.
+//
+// The wait is inline because the caller is an asynchronous job that already
+// owns a template row in 'processing'; a caller that wants to poll itself can
+// use CreateTemplateImage + WaitForImage directly.
+func (c *Client) BuildTemplateImage(ctx context.Context, store ObjectStore, in TemplateBuildInput) (string, error) {
+ if err := c.checkImageAPI(); err != nil {
+ return "", err
+ }
+ spec, err := c.resolveBaseImage(ctx)
+ if err != nil {
+ return "", err
+ }
+ if err := c.packageTemplateArtifact(ctx, store, in, spec.ArtifactURI); err != nil {
+ return "", err
+ }
+ arn, err := c.createTemplateImage(ctx, in, spec)
+ if err != nil {
+ return "", err
+ }
+ if err := c.WaitForImage(ctx, arn, in.ImageName); err != nil {
+ return "", err
+ }
+ return arn, nil
+}
+
+// packageTemplateArtifact builds the ZIP Lambda will run the Dockerfile from.
+//
+// The agent binaries are taken from the BASE image's own code artifact rather
+// than compiled here. Two reasons, and the second is the important one:
+//
+// - The control plane cannot cross-compile arm64 Go binaries at runtime, and
+// shipping a second copy alongside the server binary means two artifacts
+// that must be updated together.
+// - Reusing the base artifact makes the agent in a custom-template image
+// byte-identical to the agent in the pool image. Any other source lets the
+// two drift, and the failure mode is a template box whose agent does not
+// match the control plane that will talk to it.
+func (c *Client) packageTemplateArtifact(ctx context.Context, store ObjectStore, in TemplateBuildInput, baseURI string) error {
+ baseZip, err := store.Get(ctx, baseURI)
+ if err != nil {
+ return fmt.Errorf("read base artifact %s: %w", baseURI, err)
+ }
+ zr, err := zip.NewReader(bytes.NewReader(baseZip), int64(len(baseZip)))
+ if err != nil {
+ return fmt.Errorf("base artifact %s is not a zip: %w", baseURI, err)
+ }
+
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+
+ // Copy every entry EXCEPT the Dockerfile, which the customer's template
+ // replaces. Anything else in the base artifact (the binaries) carries over
+ // untouched.
+ var sawDockerfile bool
+ for _, f := range zr.File {
+ if f.Name == "Dockerfile" {
+ sawDockerfile = true
+ continue
+ }
+ if err := copyZipEntry(zw, f); err != nil {
+ return err
+ }
+ }
+ if !sawDockerfile {
+ // The base artifact is supposed to be Dockerfile + binaries. If there
+ // is no Dockerfile in it we are not looking at what we think we are,
+ // and silently shipping the customer's Dockerfile alongside unknown
+ // content is worse than refusing.
+ return fmt.Errorf("base artifact %s contains no Dockerfile — refusing to derive a template from it", baseURI)
+ }
+
+ if err := writeZipFile(zw, "Dockerfile", []byte(in.Dockerfile)); err != nil {
+ return err
+ }
+ for path, content := range in.ContextFiles {
+ if err := writeZipFile(zw, path, content); err != nil {
+ return err
+ }
+ }
+ if err := zw.Close(); err != nil {
+ return fmt.Errorf("finalize template artifact: %w", err)
+ }
+ return store.Put(ctx, in.ArtifactURI, buf.Bytes())
+}
+
+// baseImageSpec is everything a template build inherits from the pool image.
+type baseImageSpec struct {
+ ArtifactURI string
+ BaseImageArn string
+ BuildRoleArn string
+}
+
+// resolveBaseImage reads the pool image's active version and takes its build
+// parameters wholesale.
+//
+// Deriving rather than configuring is deliberate. These three values must match
+// what the pool image was built with — a template built from a different base or
+// a different artifact is a box that differs from the fleet in ways nothing
+// checks — and a separate set of env vars is a second source of truth that goes
+// stale silently the first time the pool image is rebuilt. Config overrides
+// exist for the cell that genuinely needs to differ, but the default is
+// "whatever the pool image says".
+func (c *Client) resolveBaseImage(ctx context.Context) (baseImageSpec, error) {
+ cfg := c.Config()
+ if cfg.ImageIdentifier == "" {
+ return baseImageSpec{}, fmt.Errorf("no base image configured — cannot derive a template build")
+ }
+ img, err := c.imageAPI.GetMicrovmImage(ctx, &lambdamicrovms.GetMicrovmImageInput{
+ ImageIdentifier: aws.String(cfg.ImageIdentifier),
+ })
+ if err != nil {
+ return baseImageSpec{}, fmt.Errorf("get base image %s: %w", cfg.ImageIdentifier, err)
+ }
+ // The ACTIVE version, not the latest: a base image whose newest build failed
+ // still serves the pool from its last good version, and a template must be
+ // built from what the fleet is actually running.
+ if img.LatestActiveImageVersion == nil || *img.LatestActiveImageVersion == "" {
+ return baseImageSpec{}, fmt.Errorf("base image %s has no active version to build from", cfg.ImageIdentifier)
+ }
+ ver, err := c.imageAPI.GetMicrovmImageVersion(ctx, &lambdamicrovms.GetMicrovmImageVersionInput{
+ ImageIdentifier: aws.String(cfg.ImageIdentifier),
+ ImageVersion: img.LatestActiveImageVersion,
+ })
+ if err != nil {
+ return baseImageSpec{}, fmt.Errorf("get base image %s version %s: %w",
+ cfg.ImageIdentifier, *img.LatestActiveImageVersion, err)
+ }
+ uri, ok := ver.CodeArtifact.(*types.CodeArtifactMemberUri)
+ if !ok || uri == nil || uri.Value == "" {
+ return baseImageSpec{}, fmt.Errorf("base image %s version %s has no code artifact URI",
+ cfg.ImageIdentifier, *img.LatestActiveImageVersion)
+ }
+ spec := baseImageSpec{
+ ArtifactURI: uri.Value,
+ BaseImageArn: aws.ToString(ver.BaseImageArn),
+ BuildRoleArn: aws.ToString(ver.BuildRoleArn),
+ }
+ if cfg.TemplateBaseImageArn != "" {
+ spec.BaseImageArn = cfg.TemplateBaseImageArn
+ }
+ if cfg.TemplateBuildRoleArn != "" {
+ spec.BuildRoleArn = cfg.TemplateBuildRoleArn
+ }
+ if spec.BaseImageArn == "" || spec.BuildRoleArn == "" {
+ return baseImageSpec{}, fmt.Errorf("base image %s reports no base-image/build-role ARN and none is configured",
+ cfg.ImageIdentifier)
+ }
+ return spec, nil
+}
+
+func (c *Client) createTemplateImage(ctx context.Context, in TemplateBuildInput, spec baseImageSpec) (string, error) {
+ cfg := c.Config()
+ mem := int32(cfg.DefaultMemoryMB)
+ if mem <= 0 {
+ mem = deliveredMicrovmMemoryMB
+ }
+
+ out, err := c.imageAPI.CreateMicrovmImage(ctx, &lambdamicrovms.CreateMicrovmImageInput{
+ Name: aws.String(in.ImageName),
+ BaseImageArn: aws.String(spec.BaseImageArn),
+ BuildRoleArn: aws.String(spec.BuildRoleArn),
+ CodeArtifact: &types.CodeArtifactMemberUri{Value: in.ArtifactURI},
+ // ARM_64 is the only architecture Lambda MicroVMs accepts, and the
+ // binaries inherited from the base artifact are arm64. Stating it
+ // keeps the two from drifting, exactly as publish.sh does.
+ CpuConfigurations: []types.CpuConfiguration{{Architecture: types.ArchitectureArm64}},
+ // Custom templates are pinned to the DEFAULT tier. Memory is a property
+ // of the image here, so offering N tiers per template would mean N
+ // images per template; until that is worth its cost, a template is one
+ // image at the default floor and the tier is chosen by the base image.
+ Resources: []types.Resources{{MinimumMemoryInMiB: aws.Int32(mem)}},
+ Hooks: templateHooks(),
+ Logging: &types.LoggingMemberCloudWatch{Value: types.CloudWatchLogging{LogGroup: aws.String(logGroupFor(in.ImageName))}},
+ Tags: in.Tags,
+ })
+ if err != nil {
+ return "", fmt.Errorf("create microvm image %s: %w", in.ImageName, err)
+ }
+ if out.ImageArn == nil || *out.ImageArn == "" {
+ return "", fmt.Errorf("create microvm image %s returned no ARN", in.ImageName)
+ }
+ return *out.ImageArn, nil
+}
+
+// templateHooks mirrors deploy/microvm/publish.sh exactly. The long ready and
+// validate timeouts are not padding: /validate deliberately exercises the exec
+// path to drive snapshot-region prefetch, and a custom template's extra layers
+// only make that slower.
+func templateHooks() *types.Hooks {
+ enabled := func(sec int32) *int32 { return aws.Int32(sec) }
+ return &types.Hooks{
+ Port: aws.Int32(8080),
+ MicrovmHooks: &types.MicrovmHooks{
+ Run: types.HookStateEnabled, RunTimeoutInSeconds: enabled(30),
+ Resume: types.HookStateEnabled, ResumeTimeoutInSeconds: enabled(30),
+ Suspend: types.HookStateEnabled, SuspendTimeoutInSeconds: enabled(30),
+ Terminate: types.HookStateEnabled, TerminateTimeoutInSeconds: enabled(30),
+ },
+ MicrovmImageHooks: &types.MicrovmImageHooks{
+ Ready: types.HookStateEnabled, ReadyTimeoutInSeconds: enabled(300),
+ Validate: types.HookStateEnabled, ValidateTimeoutInSeconds: enabled(300),
+ },
+ }
+}
+
+func logGroupFor(name string) string { return "/aws/lambda/microvms/" + name }
+
+// checkImageAPI turns "this cell has no image builder configured" into a clear
+// error at the entry point rather than a nil dereference several calls deep.
+func (c *Client) checkImageAPI() error {
+ if c.imageAPI == nil {
+ return fmt.Errorf("awsvm: image management is not configured on this client — custom templates are unavailable")
+ }
+ return nil
+}
+
+// WaitForImage blocks until the image leaves CREATING.
+//
+// A failed build surfaces as a bare CREATE_FAILED with no detail on the image
+// itself, which is unactionable — the customer cannot tell a typo'd package
+// from an x86 binary on an ARM-only platform. The reason lives on the BUILD
+// record, so fetch it and put it in the error, along with the log group where
+// the full output is.
+func (c *Client) WaitForImage(ctx context.Context, imageARN, imageName string) error {
+ const (
+ poll = 5 * time.Second
+ deadline = 30 * time.Minute
+ )
+ stop := time.Now().Add(deadline)
+ for {
+ out, err := c.imageAPI.GetMicrovmImage(ctx, &lambdamicrovms.GetMicrovmImageInput{
+ ImageIdentifier: aws.String(imageARN),
+ })
+ if err != nil {
+ return fmt.Errorf("poll image %s: %w", imageARN, err)
+ }
+ switch out.State {
+ case types.MicrovmImageStateCreated, types.MicrovmImageStateUpdated:
+ return nil
+ case types.MicrovmImageStateCreateFailed, types.MicrovmImageStateUpdateFailed:
+ return fmt.Errorf("image build failed (%s): %s; full output in CloudWatch log group %s",
+ out.State, c.buildFailureReason(ctx, imageARN, out.LatestFailedImageVersion), logGroupFor(imageName))
+ }
+ if time.Now().After(stop) {
+ return fmt.Errorf("image %s still %s after %s; see CloudWatch log group %s",
+ imageARN, out.State, deadline, logGroupFor(imageName))
+ }
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(poll):
+ }
+ }
+}
+
+// buildFailureReason is best-effort: it enriches an error that is already going
+// to be returned, so a failure to fetch the reason must not replace the real
+// one.
+func (c *Client) buildFailureReason(ctx context.Context, imageARN string, version *string) string {
+ if version == nil || *version == "" {
+ return "no failed build version reported"
+ }
+ out, err := c.imageAPI.GetMicrovmImageBuild(ctx, &lambdamicrovms.GetMicrovmImageBuildInput{
+ ImageIdentifier: aws.String(imageARN),
+ ImageVersion: version,
+ })
+ if err != nil {
+ log.Printf("awsvm: could not fetch build detail for %s v%s: %v", imageARN, *version, err)
+ return "build reason unavailable"
+ }
+ if out.StateReason == nil || *out.StateReason == "" {
+ return "build reported no reason"
+ }
+ return strings.TrimSpace(*out.StateReason)
+}
+
+// DeleteTemplateImage removes a custom-template image.
+//
+// Only ever called with an ARN read back from our own template registry. This
+// AWS account is shared with a customer-serving workload, and publish.sh is
+// careful never to touch an image it did not create; the same rule applies
+// here, which is why there is no "delete by name pattern" helper.
+func (c *Client) DeleteTemplateImage(ctx context.Context, imageARN string) error {
+ if err := c.checkImageAPI(); err != nil {
+ return err
+ }
+ _, err := c.imageAPI.DeleteMicrovmImage(ctx, &lambdamicrovms.DeleteMicrovmImageInput{
+ ImageIdentifier: aws.String(imageARN),
+ })
+ if err != nil {
+ return fmt.Errorf("delete microvm image %s: %w", imageARN, err)
+ }
+ return nil
+}
+
+func copyZipEntry(zw *zip.Writer, f *zip.File) error {
+ rc, err := f.Open()
+ if err != nil {
+ return fmt.Errorf("open %s in base artifact: %w", f.Name, err)
+ }
+ defer rc.Close()
+ hdr := f.FileHeader
+ w, err := zw.CreateHeader(&hdr)
+ if err != nil {
+ return fmt.Errorf("write %s: %w", f.Name, err)
+ }
+ if _, err := io.Copy(w, rc); err != nil {
+ return fmt.Errorf("copy %s: %w", f.Name, err)
+ }
+ return nil
+}
+
+func writeZipFile(zw *zip.Writer, name string, content []byte) error {
+ w, err := zw.Create(name)
+ if err != nil {
+ return fmt.Errorf("create %s in artifact: %w", name, err)
+ }
+ if _, err := w.Write(content); err != nil {
+ return fmt.Errorf("write %s in artifact: %w", name, err)
+ }
+ return nil
+}
diff --git a/internal/awsvm/imagebuild_test.go b/internal/awsvm/imagebuild_test.go
new file mode 100644
index 00000000..5e755021
--- /dev/null
+++ b/internal/awsvm/imagebuild_test.go
@@ -0,0 +1,298 @@
+package awsvm
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+)
+
+type fakeImageAPI struct {
+ created *lambdamicrovms.CreateMicrovmImageInput
+ states []types.MicrovmImageState // consumed one per GetMicrovmImage call
+ stateIdx int
+ failedVer string
+ reason string
+ deleted []string
+ noActive bool
+ noArtifact bool
+}
+
+func (f *fakeImageAPI) CreateMicrovmImage(_ context.Context, in *lambdamicrovms.CreateMicrovmImageInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.CreateMicrovmImageOutput, error) {
+ f.created = in
+ return &lambdamicrovms.CreateMicrovmImageOutput{ImageArn: aws.String("arn:aws:lambda:us-east-1:1:microvm-image:" + *in.Name)}, nil
+}
+
+// GetMicrovmImage serves TWO different callers: resolveBaseImage asks about the
+// base image, and WaitForImage polls the template image being built. Keying on
+// the identifier keeps the base lookup from consuming a state intended for the
+// build poll — which otherwise leaves WaitForImage polling an empty state until
+// its 30-minute deadline.
+func (f *fakeImageAPI) GetMicrovmImage(_ context.Context, in *lambdamicrovms.GetMicrovmImageInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmImageOutput, error) {
+ out := &lambdamicrovms.GetMicrovmImageOutput{}
+ if aws.ToString(in.ImageIdentifier) == "base-image" {
+ if !f.noActive {
+ out.LatestActiveImageVersion = aws.String("7")
+ }
+ return out, nil
+ }
+ if f.failedVer != "" {
+ out.LatestFailedImageVersion = aws.String(f.failedVer)
+ }
+ if f.stateIdx < len(f.states) {
+ out.State = f.states[f.stateIdx]
+ f.stateIdx++
+ } else if len(f.states) > 0 {
+ out.State = f.states[len(f.states)-1]
+ }
+ return out, nil
+}
+
+func (f *fakeImageAPI) GetMicrovmImageVersion(_ context.Context, _ *lambdamicrovms.GetMicrovmImageVersionInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmImageVersionOutput, error) {
+ out := &lambdamicrovms.GetMicrovmImageVersionOutput{
+ BaseImageArn: aws.String("arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1"),
+ BuildRoleArn: aws.String("arn:aws:iam::1:role/build"),
+ }
+ if !f.noArtifact {
+ out.CodeArtifact = &types.CodeArtifactMemberUri{Value: "s3://bucket/base.zip"}
+ }
+ return out, nil
+}
+
+func (f *fakeImageAPI) GetMicrovmImageBuild(_ context.Context, _ *lambdamicrovms.GetMicrovmImageBuildInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmImageBuildOutput, error) {
+ return &lambdamicrovms.GetMicrovmImageBuildOutput{StateReason: aws.String(f.reason)}, nil
+}
+
+func (f *fakeImageAPI) DeleteMicrovmImage(_ context.Context, in *lambdamicrovms.DeleteMicrovmImageInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.DeleteMicrovmImageOutput, error) {
+ f.deleted = append(f.deleted, *in.ImageIdentifier)
+ return &lambdamicrovms.DeleteMicrovmImageOutput{}, nil
+}
+
+type memStore struct {
+ objects map[string][]byte
+ put map[string][]byte
+}
+
+func (m *memStore) Get(_ context.Context, uri string) ([]byte, error) {
+ b, ok := m.objects[uri]
+ if !ok {
+ return nil, fmt.Errorf("no object %s", uri)
+ }
+ return b, nil
+}
+func (m *memStore) Put(_ context.Context, uri string, body []byte) error {
+ if m.put == nil {
+ m.put = map[string][]byte{}
+ }
+ m.put[uri] = body
+ return nil
+}
+
+func baseArtifact(t *testing.T, entries map[string]string) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ for name, content := range entries {
+ w, err := zw.Create(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.Write([]byte(content)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+func newTestClient(f *fakeImageAPI) *Client {
+ c := NewClientWithAPI(nil, Config{ImageIdentifier: "base-image", DefaultMemoryMB: 4096})
+ return c.WithImageAPI(f)
+}
+
+func unzip(t *testing.T, b []byte) map[string]string {
+ t.Helper()
+ zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := map[string]string{}
+ for _, f := range zr.File {
+ rc, err := f.Open()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var sb strings.Builder
+ if _, err := sb.Write(mustReadAll(t, rc)); err != nil {
+ t.Fatal(err)
+ }
+ rc.Close()
+ out[f.Name] = sb.String()
+ }
+ return out
+}
+
+func mustReadAll(t *testing.T, rc interface{ Read([]byte) (int, error) }) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ tmp := make([]byte, 512)
+ for {
+ n, err := rc.Read(tmp)
+ buf.Write(tmp[:n])
+ if err != nil {
+ break
+ }
+ }
+ return buf.Bytes()
+}
+
+// The agent binaries must be inherited from the base artifact byte-for-byte.
+// If a template image ever ships a different agent than the pool image, the
+// control plane is talking to a build it was not compiled against.
+func TestTemplateArtifactInheritsAgentBinariesAndReplacesDockerfile(t *testing.T) {
+ f := &fakeImageAPI{states: []types.MicrovmImageState{types.MicrovmImageStateCreated}}
+ store := &memStore{objects: map[string][]byte{
+ "s3://bucket/base.zip": baseArtifact(t, map[string]string{
+ "Dockerfile": "FROM base\nENTRYPOINT [\"/usr/local/bin/microvm-hooks\"]\n",
+ "osb-agent": "AGENT-BINARY",
+ "microvm-hooks": "HOOKS-BINARY",
+ }),
+ }}
+ c := newTestClient(f)
+
+ arn, err := c.BuildTemplateImage(context.Background(), store, TemplateBuildInput{
+ ImageName: "osb-tpl-abc",
+ Dockerfile: "FROM base\nRUN dnf install -y ffmpeg\nENTRYPOINT [\"/usr/local/bin/microvm-hooks\"]\n",
+ ContextFiles: map[string][]byte{"ctx/0/config.json": []byte(`{"k":1}`)},
+ ArtifactURI: "s3://bucket/templates/abc.zip",
+ Tags: map[string]string{"osb:org": "org-1"},
+ })
+ if err != nil {
+ t.Fatalf("build: %v", err)
+ }
+ if !strings.HasSuffix(arn, "osb-tpl-abc") {
+ t.Errorf("unexpected ARN %q", arn)
+ }
+
+ got := unzip(t, store.put["s3://bucket/templates/abc.zip"])
+ if got["osb-agent"] != "AGENT-BINARY" || got["microvm-hooks"] != "HOOKS-BINARY" {
+ t.Error("agent binaries were not inherited verbatim from the base artifact")
+ }
+ if !strings.Contains(got["Dockerfile"], "dnf install -y ffmpeg") {
+ t.Error("customer Dockerfile did not replace the base one")
+ }
+ if got["ctx/0/config.json"] != `{"k":1}` {
+ t.Errorf("context file missing or wrong: %q", got["ctx/0/config.json"])
+ }
+}
+
+// Build parameters are inherited from the pool image's ACTIVE version so a
+// template cannot be built against a different base or role than the fleet.
+func TestBuildParametersAreInheritedFromTheBaseImage(t *testing.T) {
+ f := &fakeImageAPI{states: []types.MicrovmImageState{types.MicrovmImageStateCreated}}
+ store := &memStore{objects: map[string][]byte{
+ "s3://bucket/base.zip": baseArtifact(t, map[string]string{"Dockerfile": "FROM base\n"}),
+ }}
+ if _, err := newTestClient(f).BuildTemplateImage(context.Background(), store, TemplateBuildInput{
+ ImageName: "t", Dockerfile: "FROM base\n", ArtifactURI: "s3://bucket/t.zip",
+ }); err != nil {
+ t.Fatalf("build: %v", err)
+ }
+ in := f.created
+ if aws.ToString(in.BaseImageArn) != "arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1" {
+ t.Errorf("base image ARN not inherited: %q", aws.ToString(in.BaseImageArn))
+ }
+ if aws.ToString(in.BuildRoleArn) != "arn:aws:iam::1:role/build" {
+ t.Errorf("build role not inherited: %q", aws.ToString(in.BuildRoleArn))
+ }
+ if len(in.CpuConfigurations) != 1 || in.CpuConfigurations[0].Architecture != types.ArchitectureArm64 {
+ t.Error("image must be pinned to ARM_64 — the only architecture Lambda MicroVMs accepts")
+ }
+ if len(in.Resources) != 1 || aws.ToInt32(in.Resources[0].MinimumMemoryInMiB) != 4096 {
+ t.Errorf("memory floor should match the default tier, got %v", in.Resources)
+ }
+ if in.Hooks == nil || aws.ToInt32(in.Hooks.Port) != 8080 {
+ t.Error("hooks must match publish.sh (port 8080)")
+ }
+}
+
+// An opaque CREATE_FAILED is unactionable: the reason lives on the build record
+// and the full output in CloudWatch. Both must reach the customer.
+func TestFailedBuildSurfacesReasonAndLogGroup(t *testing.T) {
+ f := &fakeImageAPI{
+ states: []types.MicrovmImageState{types.MicrovmImageStateCreateFailed},
+ failedVer: "8",
+ reason: "No match for argument: build-essential",
+ }
+ store := &memStore{objects: map[string][]byte{
+ "s3://bucket/base.zip": baseArtifact(t, map[string]string{"Dockerfile": "FROM base\n"}),
+ }}
+ _, err := newTestClient(f).BuildTemplateImage(context.Background(), store, TemplateBuildInput{
+ ImageName: "osb-tpl-xyz", Dockerfile: "FROM base\n", ArtifactURI: "s3://bucket/x.zip",
+ })
+ if err == nil {
+ t.Fatal("expected a build failure")
+ }
+ for _, want := range []string{"No match for argument", "/aws/lambda/microvms/osb-tpl-xyz", "CREATE_FAILED"} {
+ if !strings.Contains(err.Error(), want) {
+ t.Errorf("error missing %q: %v", want, err)
+ }
+ }
+}
+
+// A base artifact without a Dockerfile is not the artifact we think it is.
+func TestRefusesBaseArtifactWithoutDockerfile(t *testing.T) {
+ f := &fakeImageAPI{}
+ store := &memStore{objects: map[string][]byte{
+ "s3://bucket/base.zip": baseArtifact(t, map[string]string{"osb-agent": "X"}),
+ }}
+ _, err := newTestClient(f).BuildTemplateImage(context.Background(), store, TemplateBuildInput{
+ ImageName: "t", Dockerfile: "FROM base\n", ArtifactURI: "s3://bucket/t.zip",
+ })
+ if err == nil || !strings.Contains(err.Error(), "no Dockerfile") {
+ t.Fatalf("expected refusal, got %v", err)
+ }
+}
+
+// A base image whose newest build failed still serves the pool from its last
+// good version; templates must be built from that, not from nothing.
+func TestRefusesWhenBaseImageHasNoActiveVersion(t *testing.T) {
+ f := &fakeImageAPI{noActive: true}
+ store := &memStore{objects: map[string][]byte{}}
+ _, err := newTestClient(f).BuildTemplateImage(context.Background(), store, TemplateBuildInput{
+ ImageName: "t", Dockerfile: "FROM base\n", ArtifactURI: "s3://bucket/t.zip",
+ })
+ if err == nil || !strings.Contains(err.Error(), "no active version") {
+ t.Fatalf("expected refusal, got %v", err)
+ }
+}
+
+// A cell with no image API configured must say so, not nil-panic.
+func TestUnconfiguredImageAPIFailsClearly(t *testing.T) {
+ c := NewClientWithAPI(nil, Config{ImageIdentifier: "base"})
+ _, err := c.BuildTemplateImage(context.Background(), &memStore{}, TemplateBuildInput{})
+ if err == nil || !strings.Contains(err.Error(), "not configured") {
+ t.Fatalf("expected a clear configuration error, got %v", err)
+ }
+ if err := c.DeleteTemplateImage(context.Background(), "arn:x"); err == nil {
+ t.Fatal("delete should also refuse without an image API")
+ }
+}
+
+func TestDeleteTemplateImageUsesTheGivenARN(t *testing.T) {
+ f := &fakeImageAPI{}
+ if err := newTestClient(f).DeleteTemplateImage(context.Background(), "arn:aws:lambda:us-east-1:1:microvm-image:osb-tpl-1"); err != nil {
+ t.Fatalf("delete: %v", err)
+ }
+ if len(f.deleted) != 1 || f.deleted[0] != "arn:aws:lambda:us-east-1:1:microvm-image:osb-tpl-1" {
+ t.Errorf("unexpected deletions: %v", f.deleted)
+ }
+}
diff --git a/internal/awsvm/objectstore.go b/internal/awsvm/objectstore.go
new file mode 100644
index 00000000..c697cd68
--- /dev/null
+++ b/internal/awsvm/objectstore.go
@@ -0,0 +1,77 @@
+package awsvm
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "strings"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+)
+
+// S3Store is the ObjectStore the template builder reads and writes build
+// artifacts through.
+//
+// Deliberately tiny — Get and Put on an s3:// URI, nothing else. The builder
+// only ever fetches the base image's artifact and uploads a derived one, so a
+// broader surface would only be an invitation to reach for S3 from places that
+// should not.
+type S3Store struct {
+ api *s3.Client
+}
+
+// NewS3Store builds a store from the same aws.Config the MicroVM client uses,
+// so credentials and region cannot drift between the two.
+func NewS3Store(cfg aws.Config) *S3Store {
+ return &S3Store{api: s3.NewFromConfig(cfg)}
+}
+
+// parseS3URI splits s3://bucket/key.
+//
+// Returns an error rather than guessing: these URIs come from an AWS API
+// response (the base image's code artifact) and from config, and a silently
+// mis-parsed bucket would surface as a NoSuchBucket naming something the
+// operator never typed.
+func parseS3URI(uri string) (bucket, key string, err error) {
+ const scheme = "s3://"
+ if !strings.HasPrefix(uri, scheme) {
+ return "", "", fmt.Errorf("not an s3:// URI: %q", uri)
+ }
+ rest := strings.TrimPrefix(uri, scheme)
+ i := strings.Index(rest, "/")
+ if i <= 0 || i == len(rest)-1 {
+ return "", "", fmt.Errorf("s3 URI %q has no bucket/key split", uri)
+ }
+ return rest[:i], rest[i+1:], nil
+}
+
+func (s *S3Store) Get(ctx context.Context, uri string) ([]byte, error) {
+ bucket, key, err := parseS3URI(uri)
+ if err != nil {
+ return nil, err
+ }
+ out, err := s.api.GetObject(ctx, &s3.GetObjectInput{
+ Bucket: aws.String(bucket), Key: aws.String(key),
+ })
+ if err != nil {
+ return nil, fmt.Errorf("get %s: %w", uri, err)
+ }
+ defer out.Body.Close()
+ return io.ReadAll(out.Body)
+}
+
+func (s *S3Store) Put(ctx context.Context, uri string, body []byte) error {
+ bucket, key, err := parseS3URI(uri)
+ if err != nil {
+ return err
+ }
+ if _, err := s.api.PutObject(ctx, &s3.PutObjectInput{
+ Bucket: aws.String(bucket), Key: aws.String(key),
+ Body: bytes.NewReader(body),
+ }); err != nil {
+ return fmt.Errorf("put %s: %w", uri, err)
+ }
+ return nil
+}