Skip to content

Commit

Permalink
WIP bundle-images-command
Browse files Browse the repository at this point in the history
Signed-off-by: Tom Wieczorek <[email protected]>
  • Loading branch information
twz123 committed Dec 10, 2024
1 parent c0531e2 commit c0a84e4
Show file tree
Hide file tree
Showing 13 changed files with 716 additions and 96 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build-airgap-image-bundle.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,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 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
15 changes: 3 additions & 12 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -222,23 +222,16 @@ lint-go: .k0sbuild.docker-image.k0s go.sum bindata
.PHONY: lint
lint: lint-copyright lint-go

airgap-images.txt: k0s .k0sbuild.docker-image.k0s
airgap-images.txt: build .k0sbuild.docker-image.k0s
$(GO_ENV) ./k0s airgap list-images --all > '$@'

airgap-image-bundle-linux-amd64.tar: TARGET_PLATFORM := linux/amd64
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: build airgap-images.txt
./k0s airgap -v bundle-images -o '$@' from-file airgap-images.txt

.PHONY: $(smoketests)
check-airgap check-ap-airgap: airgap-image-bundle-linux-$(HOST_ARCH).tar
Expand Down Expand Up @@ -269,9 +262,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
5 changes: 4 additions & 1 deletion cmd/airgap/airgap.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package airgap

import (
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"

"github.com/k0sproject/k0s/pkg/config"
Expand All @@ -25,10 +26,12 @@ import (
func NewAirgapCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "airgap",
Short: "Manage airgap setup",
Short: "Tooling for airgapped installations",
}

log := logrus.StandardLogger()
cmd.AddCommand(NewAirgapListImagesCmd())
cmd.AddCommand(NewAirgapBundleImagesCmd(log))
cmd.PersistentFlags().AddFlagSet(config.FileInputFlag())
cmd.PersistentFlags().AddFlagSet(config.GetPersistentFlagSet())
return cmd
Expand Down
264 changes: 264 additions & 0 deletions cmd/airgap/bundleimages.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
/*
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"
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
"slices"
"strconv"
"strings"
"syscall"

"github.com/distribution/reference"
"github.com/k0sproject/k0s/internal/pkg/file"
"github.com/k0sproject/k0s/pkg/airgap"
"github.com/k0sproject/k0s/pkg/config"
"golang.org/x/term"

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

type imageBundleOpts struct {
bundler airgap.ImageBundler
outPath string
stdout func() io.Writer
}

func NewAirgapBundleImagesCmd(log logrus.FieldLogger) *cobra.Command {
opts := imageBundleOpts{
bundler: airgap.ImageBundler{
Log: log,
},
}

cmd := &cobra.Command{
Use: "bundle-images [flags] [file]",
Short: "Bundles images in a tarball needed for airgapped installations",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := config.CallParentPersistentPreRun(cmd, args); err != nil {
return err
}
if opts.outPath != "" {
return nil
}

return enforceNoTerminal(cmd.OutOrStdout())
},
}

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

opts.stdout = cmd.OutOrStdout
cmd.AddCommand(newFromConfigCommand(&opts))
cmd.AddCommand(newFromStdinCommand(&opts))
cmd.AddCommand(newFromFileCommand(&opts))
return cmd
}

func newFromConfigCommand(opts *imageBundleOpts) *cobra.Command {
var all bool

cmd := &cobra.Command{
Use: "from-config",
Short: "Bundles images for the current cluster configuration",
Long: `Bundles images for the current cluster configuration.
Builds the list of images in the same way as the list-images sub-command.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) (err error) {
cmdOpts, err := config.GetCmdOpts(cmd)
if err != nil {
return err
}

clusterConfig, err := cmdOpts.K0sVars.NodeConfig()
if err != nil {
return fmt.Errorf("failed to get config: %w", err)
}

var imageRefs []reference.Named
for image := range airgap.ImagesInSpec(clusterConfig.Spec, all) {
uri := image.URI()
ref, err := reference.ParseNormalizedNamed(uri)
if err != nil {
return fmt.Errorf("while parsing %q: %w", uri, err)
}
imageRefs = append(imageRefs, ref)
}

return opts.runBundler(cmd.Context(), imageRefs)
},
}

cmd.Flags().BoolVarP(&all, "all", "a", false, "include all images, even if they are not used in the current configuration")
return cmd
}

func newFromFileCommand(opts *imageBundleOpts) *cobra.Command {
return &cobra.Command{
Use: "from-file [flags] file",
Short: "Bundles images read from the given file",
Long: `Bundles images read from the given file, line by line. Surrounding whitespace is
ignored, lines whose first non-whitespace character is a # are ignored.`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) (err error) {
imageRefs, err := parseReferencesFromFile(args[0])
if err != nil {
return err
}
return opts.runBundler(cmd.Context(), imageRefs)
},
}
}

func newFromStdinCommand(opts *imageBundleOpts) *cobra.Command {
return &cobra.Command{
Use: "from-stdin",
Short: "Bundles images read from standard input",
Long: `Bundles images read from standard input, line by line. Surrounding whitespace is
ignored, lines whose first non-whitespace character is a # are ignored.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) (err error) {
imageRefs, err := parseReferencesFromReader(cmd.InOrStdin())
if err != nil {
return err
}
return opts.runBundler(cmd.Context(), imageRefs)
},
}
}

func parseReferencesFromFile(path string) (_ []reference.Named, err error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer func() { err = errors.Join(err, f.Close()) }()
return parseReferencesFromReader(f)
}

func parseReferencesFromReader(in io.Reader) ([]reference.Named, error) {
lines := bufio.NewScanner(in)

var (
imageRefs []reference.Named
lineNum uint
)
for lines.Scan() {
lineNum++
line := lines.Bytes()
if len(line) > 0 && line[0] != '#' {
image := string(line)
ref, err := reference.ParseNormalizedNamed(image)
if err != nil {
return nil, fmt.Errorf("while parsing line %d: %q: %w", lineNum, image, err)
}
imageRefs = append(imageRefs, ref)
}
}
if err := lines.Err(); err != nil {
return nil, err
}

return imageRefs, nil
}

func (o *imageBundleOpts) runBundler(ctx context.Context, refs []reference.Named) (err error) {
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer cancel()

var out io.Writer
if o.outPath == "" {
out = o.stdout()
if err := enforceNoTerminal(out); err != nil {
return err
}
} else {
f, err := file.AtomicWithTarget(o.outPath).Open()
if err != nil {
return err
}
defer func() {
if err == nil {
err = f.Finish()
} else if closeErr := f.Close(); closeErr != nil {
err = errors.Join(err, closeErr)
}
}()
out = f
}

buffered := bufio.NewWriter(out)
if err := o.bundler.Run(ctx, refs, out); err != nil {
return err
}
return buffered.Flush()
}

func enforceNoTerminal(out io.Writer) error {
var isTerm bool
if conn, ok := out.(syscall.Conn); ok {
if raw, err := conn.SyscallConn(); err == nil {
raw.Control(func(fd uintptr) {

Check failure on line 224 in cmd/airgap/bundleimages.go

View workflow job for this annotation

GitHub Actions / Lint

Error return value of `raw.Control` is not checked (errcheck)
isTerm = term.IsTerminal(int(fd))
})
}
}

if !isTerm {
return nil
}

return errors.New("cowardly refusing to write binary data to a terminal")
}

type insecureRegistryFlag airgap.InsecureRegistryKind

var insecureRegistryFlagValues = [...]string{
airgap.NoInsecureRegistry: "no",
airgap.SkipTLSVerifyRegistry: "skip-tls-verify",
airgap.PlainHTTPRegistry: "plain-http",
}

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 {
*i = insecureRegistryFlag(idx)
}

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

func (insecureRegistryFlag) Type() string {
return "string"
}
10 changes: 6 additions & 4 deletions cmd/airgap/listimages.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package airgap

import (
"bufio"
"errors"
"fmt"

Expand All @@ -31,7 +32,7 @@ func NewAirgapListImagesCmd() *cobra.Command {

cmd := &cobra.Command{
Use: "list-images",
Short: "List image names and version needed for air-gap install",
Short: "List image names and versions needed for airgapped installations",
Example: `k0s airgap list-images`,
RunE: func(cmd *cobra.Command, args []string) error {
opts, err := config.GetCmdOpts(cmd)
Expand All @@ -48,10 +49,11 @@ func NewAirgapListImagesCmd() *cobra.Command {
return fmt.Errorf("failed to get config: %w", err)
}

for _, uri := range airgap.GetImageURIs(clusterConfig.Spec, all) {
fmt.Fprintln(cmd.OutOrStdout(), uri)
out := bufio.NewWriter(cmd.OutOrStdout())
for image := range airgap.ImagesInSpec(clusterConfig.Spec, all) {
fmt.Fprintln(out, image.URI())
}
return nil
return out.Flush()
},
}
cmd.Flags().AddFlagSet(config.FileInputFlag())
Expand Down
Loading

0 comments on commit c0a84e4

Please sign in to comment.