-
Notifications
You must be signed in to change notification settings - Fork 47
Add Buildah support #585
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
Open
joaopapereira
wants to merge
9
commits into
carvel-dev:develop
Choose a base branch
from
joaopapereira:buildah
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add Buildah support #585
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
a7e8794
:tada: Build images with buildah
8e454a2
Remove the strict magic number linting
joaopapereira a83d47b
Major changes on implementation
joaopapereira a6157ff
Fix static string error
joaopapereira 920effd
Yet another try to fix the static string issue
joaopapereira b026a9e
Install buildah in our image for tests
joaopapereira 0f60150
Add 1024 to the allowed magic number list in linter
joaopapereira 08868bd
Minor refactor and add qemu package to allow buildah to execute
joaopapereira cb9acc5
Add cross compatibility for Buildah in Minikube
joaopapereira File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| // Copyright 2026 The Carvel Authors. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| // Package buildah provides a builder implementation using Buildah. | ||
| package buildah | ||
|
|
||
| import ( | ||
| "crypto/rand" | ||
| "encoding/hex" | ||
| "errors" | ||
| "fmt" | ||
| "io" | ||
| "os" | ||
| "os/exec" | ||
| "regexp" | ||
| "strings" | ||
|
|
||
| ctlb "carvel.dev/kbld/pkg/kbld/builder" | ||
| ctlconf "carvel.dev/kbld/pkg/kbld/config" | ||
| ctllog "carvel.dev/kbld/pkg/kbld/logger" | ||
| ) | ||
|
|
||
| var digestPattern = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`) | ||
|
|
||
| // Buildah struct to define the Builder | ||
| type Buildah struct { | ||
| logger ctllog.Logger | ||
| } | ||
|
|
||
| // New create a new Buildah builder | ||
| func New(logger ctllog.Logger) Buildah { | ||
| return Buildah{logger} | ||
| } | ||
|
|
||
| func ensureDirectory(directory string) error { | ||
| stat, err := os.Stat(directory) | ||
| if err != nil { | ||
| return fmt.Errorf( | ||
| "Checking if path '%s' is a directory: %s", directory, err) | ||
| } | ||
|
|
||
| // Provide explicit directory check error message because otherwise | ||
| // docker CLI outputs confusing msg | ||
| // 'error: fork/exec /usr/local/bin/docker: not a directory' | ||
| if !stat.IsDir() { | ||
| return fmt.Errorf( | ||
| "Expected path '%s' to be a directory, but was not", directory) | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| // Generate a name to store the image in local | ||
| // The local name is always new and random. | ||
| // The manifest is new each time and do not accumulate images. | ||
| func localImageName(configImageName string, | ||
| imgDest *ctlconf.ImageDestination) string { | ||
| if imgDest != nil { | ||
| configImageName = imgDest.NewImage | ||
| } | ||
| tb := ctlb.TagBuilder{} | ||
| randSuffix, err := tb.RandomStr50() | ||
| if err != nil { | ||
| return configImageName + ":kbld" | ||
| } | ||
| return configImageName + ":kbld-" + randSuffix | ||
| } | ||
|
|
||
| // BuildAndPushImage builds and pushed the images to the registry | ||
| func (b Buildah) BuildAndPushImage(image string, directory string, | ||
| imgDst *ctlconf.ImageDestination, | ||
| opts ctlconf.SourceBuildahOpts) (string, error) { | ||
| if imgDst == nil { | ||
| return "", errors.New( | ||
| "a destination is required to store the built image") | ||
| } | ||
|
|
||
| err := ensureDirectory(directory) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
|
|
||
| prefixedLogger := b.logger.NewPrefixedWriter(image + " build | ") | ||
| prefixedLogger.WriteStr("Start building using buildah") | ||
|
|
||
| localName := localImageName(image, imgDst) | ||
| cmdArgs := []string{"build", "--manifest=" + localName} | ||
|
|
||
| if opts.File != nil { | ||
| cmdArgs = append(cmdArgs, "--file="+*opts.File) | ||
| } | ||
| cmdArgs = append(cmdArgs, opts.Args()...) | ||
|
|
||
| // Use current directory as context | ||
| // cmdArgs = append(cmdArgs, "./") | ||
|
|
||
| prefixedLogger.WriteStr("=> buildah %s", strings.Join(cmdArgs, " ")) | ||
| { | ||
| cmd := exec.Command("buildah", cmdArgs...) | ||
| cmd.Dir = directory | ||
| cmd.Stdout = prefixedLogger | ||
| cmd.Stderr = io.MultiWriter(os.Stderr, prefixedLogger) | ||
|
|
||
| err := cmd.Run() | ||
| if err != nil { | ||
| prefixedLogger.WriteStr("error: %s", err) | ||
| return "", err | ||
| } | ||
| } | ||
|
|
||
| pushLogger := b.logger.NewPrefixedWriter(image + " push | ") | ||
| // Push using a temporary, random tag, | ||
| // and return a canonical digest reference. | ||
| tempTagBytes := make([]byte, 8) | ||
| if _, err := rand.Read(tempTagBytes); err != nil { | ||
| return "", fmt.Errorf("generating temporary tag: %w", err) | ||
| } | ||
| tempTag := hex.EncodeToString(tempTagBytes) | ||
| tempRemoteName := fmt.Sprintf("%s:%s", imgDst.NewImage, tempTag) | ||
| digest, pushErr := Push(localName, tempRemoteName, pushLogger) | ||
|
|
||
| if pushErr != nil { | ||
| return "", pushErr | ||
| } | ||
| remoteName := fmt.Sprintf("%s@%s", imgDst.NewImage, digest) | ||
| prefixedLogger.WriteStr("Image build : %s", remoteName) | ||
| return remoteName, nil | ||
| } | ||
|
|
||
| // Push the buildah manifest and return the digest | ||
| func Push(src string, dest string, | ||
| log *ctllog.PrefixWriter) (string, error) { | ||
| digestFile, digestErr := os.CreateTemp("", "buildah-") | ||
| if digestErr != nil { | ||
| return "", fmt.Errorf( | ||
| "cannot create digest file: %w", digestErr) | ||
| } | ||
| defer func() { | ||
| if err := digestFile.Close(); err != nil { | ||
| log.WriteStr("ERROR: Closing temp file %q: %v", | ||
| digestFile.Name(), err) | ||
| } | ||
| if err := os.Remove(digestFile.Name()); err != nil { | ||
| log.WriteStr("ERROR: Removing temp file %q: %v", | ||
| digestFile.Name(), err) | ||
| } | ||
| }() | ||
|
|
||
| // !!! with --digestfile, buildah will not return an error | ||
| // even if an authentication is required. | ||
| log.WriteStr( | ||
| "=> buildah manifest push --all --digestfile=%s %s docker://%s", | ||
| digestFile.Name(), src, dest) | ||
| pushCommand := exec.Command("buildah", "manifest", "push", "--all", | ||
| "--digestfile="+digestFile.Name(), src, "docker://"+dest) | ||
| pushCommand.Stdout = log | ||
| pushCommand.Stderr = log | ||
| pushErr := pushCommand.Run() | ||
| if pushErr != nil { | ||
| return "", fmt.Errorf( | ||
| "error pushing to %q (check if you are authenticated) : %w", | ||
| dest, pushErr) | ||
| } | ||
|
|
||
| digest, err := calculateDigest(digestFile) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| return digest, nil | ||
| } | ||
|
|
||
| func calculateDigest(digestFile *os.File) (string, error) { | ||
| digestBytes, readErr := os.ReadFile(digestFile.Name()) | ||
| if readErr != nil { | ||
| return "", fmt.Errorf( | ||
| "cannot read digest from temporary file %q: %w", | ||
| digestFile.Name(), readErr) | ||
| } | ||
|
|
||
| digest := strings.TrimSpace(string(digestBytes)) | ||
| if digest == "" { | ||
| return "", fmt.Errorf( | ||
| "no digest found in file %q", | ||
| digestFile.Name()) | ||
| } | ||
| if !digestPattern.MatchString(digest) { | ||
| return "", fmt.Errorf( | ||
| "invalid digest format %q in file %q", digest, digestFile.Name()) | ||
| } | ||
| return digest, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| // Copyright 2026 The Carvel Authors. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package config | ||
|
|
||
| import ( | ||
| "slices" | ||
| "strings" | ||
| ) | ||
|
|
||
| // ContainerFileOpts Options for builds using Containerfiles | ||
| // | ||
| // see https://github.com/containers/common/blob/main/docs/Containerfile.5.md | ||
| type ContainerFileOpts struct { | ||
| // Pull Always pull images | ||
| Pull *bool | ||
| // NoCache Do not use cache when building the image | ||
| NoCache *bool | ||
| // File containing instructions | ||
| // Docker will use "Dockerfile" as default | ||
| // Buildah can detect "Containerfile" or "Dockerfile" as default | ||
| File *string | ||
| // BuildArgs Option "--build-arg=K=V" | ||
| BuildArgs map[string]string `json:"buildArgs"` | ||
| // Target Set the target build stage to build. | ||
| Target *string | ||
| // Platforms to build for | ||
| Platforms []string | ||
| } | ||
|
|
||
| // SourceBuildahOpts specifies options for building images using Buildah. | ||
| type SourceBuildahOpts struct { | ||
| ContainerFileOpts | ||
| // More options | ||
| RawOptions *[]string `json:"rawOptions"` | ||
| } | ||
|
|
||
| // Args stringifies the options | ||
| // | ||
| //revive:disable-next-line:cognitive-complexity | ||
| func (opts SourceBuildahOpts) Args() []string { | ||
| args := []string{} | ||
|
|
||
| if opts.Pull != nil && *opts.Pull { | ||
| args = append(args, "--pull") | ||
| } | ||
| if opts.NoCache != nil && *opts.NoCache { | ||
| args = append(args, "--no-cache") | ||
| } | ||
|
|
||
| if opts.BuildArgs != nil { | ||
| args = opts.buildArgs() | ||
| } | ||
|
|
||
| if opts.Target != nil { | ||
| args = append(args, "--target="+*opts.Target) | ||
| } | ||
| if len(opts.Platforms) > 0 { | ||
| args = append(args, "--platform="+strings.Join(opts.Platforms, ",")) | ||
| } | ||
| if opts.RawOptions != nil { | ||
| args = append(args, *opts.RawOptions...) | ||
| } | ||
| return args | ||
| } | ||
|
|
||
| func (opts SourceBuildahOpts) buildArgs() []string { | ||
| var args []string | ||
| keys := make([]string, 0, len(opts.BuildArgs)) | ||
| for k := range opts.BuildArgs { | ||
| keys = append(keys, k) | ||
| } | ||
| slices.Sort(keys) | ||
| for _, arg := range keys { | ||
| value := opts.BuildArgs[arg] | ||
| args = append(args, "--build-arg="+arg+"="+value) | ||
| } | ||
| return args | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we need to export this function?