Skip to content
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

Introduce k0s airgap bundle-artifacts #5360

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
8 changes: 7 additions & 1 deletion .github/workflows/build-airgap-image-bundle.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ jobs:
with:
persist-credentials: false

- name: "Download :: k0s"
uses: actions/download-artifact@v4
with:
name: k0s-linux-amd64

- name: "Download :: Airgap image list"
uses: actions/download-artifact@v4
with:
Expand All @@ -44,7 +49,7 @@ jobs:
- name: "Cache :: Airgap image bundle :: Calculate cache key"
id: cache-airgap-image-bundle-calc-key
env:
HASH_VALUE: ${{ hashFiles('Makefile', 'airgap-images.txt', 'hack/image-bundler/*') }}
HASH_VALUE: ${{ hashFiles('Makefile', 'airgap-images.txt', 'cmd/airgap/*', 'pkg/airgap/*') }}
run: |
printf 'cache-key=build-airgap-image-bundle-%s-%s-%s\n' "$TARGET_OS" "$TARGET_ARCH" "$HASH_VALUE" >> "$GITHUB_OUTPUT"

Expand All @@ -58,6 +63,7 @@ jobs:
- name: "Build :: Airgap image bundle"
if: steps.cache-airgap-image-bundle.outputs.cache-hit != 'true'
run: |
chmod +x k0s
mkdir -p "embedded-bins/staging/$TARGET_OS/bin"
make --touch airgap-images.txt
make "airgap-image-bundle-$TARGET_OS-$TARGET_ARCH.tar"
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ jobs:
id: cache-airgap-image-bundle
uses: actions/cache@v4
with:
key: airgap-image-bundle-linux-${{ matrix.arch }}-${{ hashFiles('Makefile', 'airgap-images.txt', 'hack/image-bundler/*') }}
key: airgap-image-bundle-linux-${{ matrix.arch }}-${{ hashFiles('Makefile', 'airgap-images.txt', 'cmd/airgap/*', 'pkg/airgap/*') }}
path: |
airgap-images.txt
airgap-image-bundle-linux-${{ matrix.arch }}.tar
Expand Down
13 changes: 2 additions & 11 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -238,15 +238,8 @@ airgap-image-bundle-linux-arm64.tar: TARGET_PLATFORM := linux/arm64
airgap-image-bundle-linux-arm.tar: TARGET_PLATFORM := linux/arm/v7
airgap-image-bundle-linux-amd64.tar \
airgap-image-bundle-linux-arm64.tar \
airgap-image-bundle-linux-arm.tar: .k0sbuild.image-bundler.stamp airgap-images.txt
$(DOCKER) run --rm -i --privileged \
-e TARGET_PLATFORM='$(TARGET_PLATFORM)' \
'$(shell cat .k0sbuild.image-bundler.stamp)' < airgap-images.txt > '$@'

.k0sbuild.image-bundler.stamp: hack/image-bundler/* embedded-bins/Makefile.variables
$(DOCKER) build --progress=plain --iidfile '$@' \
--build-arg ALPINE_VERSION=$(alpine_patch_version) \
-t k0sbuild.image-bundler -- hack/image-bundler
airgap-image-bundle-linux-arm.tar: k0s airgap-images.txt
./k0s airgap -v bundle-artifacts --platform='$(TARGET_PLATFORM)' -o '$@' <airgap-images.txt

.PHONY: $(smoketests)
check-airgap check-ap-airgap: airgap-image-bundle-linux-$(HOST_ARCH).tar
Expand Down Expand Up @@ -277,9 +270,7 @@ clean-docker-image:
$(clean-iid-files)

.PHONY: clean-airgap-image-bundles
clean-airgap-image-bundles: IID_FILES = .k0sbuild.image-bundler.stamp
clean-airgap-image-bundles:
$(clean-iid-files)
-rm airgap-images.txt
-rm airgap-image-bundle-linux-amd64.tar airgap-image-bundle-linux-arm64.tar airgap-image-bundle-linux-arm.tar

Expand Down
18 changes: 14 additions & 4 deletions cmd/airgap/airgap.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,28 @@ limitations under the License.
package airgap

import (
"github.com/spf13/cobra"

"github.com/k0sproject/k0s/pkg/config"

"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

func NewAirgapCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "airgap",
Short: "Manage airgap setup",
Short: "Tooling for airgapped installations",
Long: `Tooling for airgapped installations.

For example, to create an image bundle that contains the images required for
the current configuration, use the following command:

k0s airgap list-images | k0s airgap bundle-artifacts -v -o image-bundle.tar
`,
}

cmd.AddCommand(NewAirgapListImagesCmd())
log := logrus.StandardLogger()
cmd.AddCommand(newAirgapListImagesCmd())
cmd.AddCommand(newAirgapBundleArtifactsCmd(log, nil))
cmd.PersistentFlags().AddFlagSet(config.FileInputFlag())
cmd.PersistentFlags().AddFlagSet(config.GetPersistentFlagSet())
return cmd
Expand Down
192 changes: 192 additions & 0 deletions cmd/airgap/bundleartifacts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
/*
Copyright 2024 k0s authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package airgap

import (
"bufio"
"errors"
"fmt"
"io"
"iter"
"os"
"os/signal"
"slices"
"strconv"
"strings"
"syscall"

"github.com/k0sproject/k0s/internal/pkg/file"
"github.com/k0sproject/k0s/pkg/airgap"

"k8s.io/kubectl/pkg/util/term"

"github.com/containerd/platforms"
"github.com/distribution/reference"
imagespecv1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

func newAirgapBundleArtifactsCmd(log logrus.FieldLogger, rewriteBundleRef airgap.RewriteRefFunc) *cobra.Command {
var (
outPath string
platform = platforms.DefaultSpec()
bundler = airgap.OCIArtifactsBundler{
Log: log,
RewriteTarget: rewriteBundleRef,
}
)

cmd := &cobra.Command{
Use: "bundle-artifacts [flags] [names...]",
Short: "Bundles artifacts needed for airgapped installations into a tarball",
Long: `Bundles artifacts needed for airgapped installations into a tarball. Fetches the
artifacts from their OCI registries and bundles them into an OCI Image Layout
archive (written to standard output by default). Reads names from standard input
if no names are given on the command line.`,
RunE: func(cmd *cobra.Command, args []string) (err error) {
ctx := cmd.Context()
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer cancel()

cmd.SilenceUsage = true

bundler.PlatformMatcher = platforms.Only(platform)

var out io.Writer
if outPath == "" {
out = cmd.OutOrStdout()
if term.IsTerminal(out) {
return errors.New("cowardly refusing to write binary data to a terminal")
}
} else {
f, openErr := file.AtomicWithTarget(outPath).Open()
if openErr != nil {
return openErr
}
defer func() {
if err == nil {
err = f.Finish()
} else if closeErr := f.Close(); closeErr != nil {
err = errors.Join(err, closeErr)
}
}()
out = f
}

var refs []reference.Named
if len(args) > 0 {
refs, err = parseArtifactRefsFromSeq(slices.Values(args))
} else {
refs, err = parseArtifactRefsFromReader(cmd.InOrStdin())
}
if err != nil {
return err
}

buffered := bufio.NewWriter(out)
if err := bundler.Run(ctx, refs, out); err != nil {
return err
Copy link
Contributor

Choose a reason for hiding this comment

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

Error not wrapped.

Copy link
Member Author

Choose a reason for hiding this comment

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

I could change this to return fmt.Errorf("failed to bundle artifacts: %w", err), but I'm not sure if that adds any additional insights 🤔

}
return buffered.Flush()
},
}

cmd.Flags().StringVarP(&outPath, "output", "o", "", "output file path (writes to standard output if omitted)")
cmd.Flags().Var((*insecureRegistryFlag)(&bundler.InsecureRegistries), "insecure-registries", "one of "+strings.Join(insecureRegistryFlagValues[:], ", "))
cmd.Flags().Var((*platformFlag)(&platform), "platform", "the platform to export")
cmd.Flags().StringArrayVar(&bundler.RegistriesConfigPaths, "registries-config", nil, "paths to the authentication files for OCI registries (uses the standard Docker config if omitted)")

return cmd
}

func parseArtifactRefsFromReader(in io.Reader) ([]reference.Named, error) {
words := bufio.NewScanner(in)
words.Split(bufio.ScanWords)
refs, err := parseArtifactRefsFromSeq(func(yield func(string) bool) {
for words.Scan() {
if !yield(words.Text()) {
return
}
}
})
if err := errors.Join(err, words.Err()); err != nil {
return nil, err
}

return refs, nil
}

func parseArtifactRefsFromSeq(refs iter.Seq[string]) (collected []reference.Named, _ error) {
Copy link
Contributor

Choose a reason for hiding this comment

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

The _ error kind of looks like the return value can be ignored.

Copy link
Member Author

Choose a reason for hiding this comment

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

I'm not sure if I can follow. What would you suggest?

for ref := range refs {
parsed, err := reference.ParseNormalizedNamed(ref)
if err != nil {
return nil, fmt.Errorf("while parsing %s: %w", ref, err)
}
collected = append(collected, parsed)
}
return collected, nil
}

type insecureRegistryFlag airgap.InsecureOCIRegistryKind

var insecureRegistryFlagValues = [...]string{
airgap.NoInsecureOCIRegistry: "no",
airgap.SkipTLSVerifyOCIRegistry: "skip-tls-verify",
airgap.PlainHTTPOCIRegistry: "plain-http",
}

func (insecureRegistryFlag) Type() string {
return "string"
}

func (i insecureRegistryFlag) String() string {
if i := int(i); i < len(insecureRegistryFlagValues) {
return insecureRegistryFlagValues[i]
} else {
return strconv.Itoa(i)
}
}

func (i *insecureRegistryFlag) Set(value string) error {
idx := slices.Index(insecureRegistryFlagValues[:], value)
if idx >= 0 {
*(*airgap.InsecureOCIRegistryKind)(i) = airgap.InsecureOCIRegistryKind(idx)
return nil
}

return errors.New("must be one of " + strings.Join(insecureRegistryFlagValues[:], ", "))
}

type platformFlag imagespecv1.Platform

func (p *platformFlag) Type() string {
return "string"
}

func (p *platformFlag) String() string {
return platforms.FormatAll(*(*imagespecv1.Platform)(p))
}

func (p *platformFlag) Set(value string) error {
platform, err := platforms.Parse(value)
if err != nil {
return err
}
*(*imagespecv1.Platform)(p) = platform
return nil
}
Loading
Loading