From 84fec48b979d8269b73aa6ee4ac28a327b8c6e04 Mon Sep 17 00:00:00 2001 From: David Cassany Date: Thu, 22 Feb 2024 12:23:57 +0100 Subject: [PATCH] Move pkg/types/v2 to simply pkg/types This commit leaves the code with a single set of types and in refers to it as the types packge instead of v1 or v2. For the time being we do not foresee managing more than one single major version of type within the same code. Signed-off-by: David Cassany --- cmd/build-disk.go | 8 +- cmd/build-iso.go | 16 +- cmd/cloud-init.go | 4 +- cmd/config/config.go | 38 ++--- cmd/config/config_test.go | 24 +-- cmd/flags.go | 10 +- cmd/init.go | 4 +- cmd/install.go | 10 +- cmd/pull-image.go | 6 +- cmd/reset.go | 4 +- cmd/run-stage.go | 4 +- cmd/upgrade.go | 4 +- pkg/action/build-disk.go | 58 ++++---- pkg/action/build-iso.go | 20 +-- pkg/action/build_test.go | 38 ++--- pkg/action/common.go | 10 +- pkg/action/init.go | 4 +- pkg/action/init_test.go | 10 +- pkg/action/install.go | 30 ++-- pkg/action/install_test.go | 18 +-- pkg/action/mount.go | 28 ++-- pkg/action/mount_test.go | 32 ++-- pkg/action/reset.go | 26 ++-- pkg/action/reset_test.go | 16 +- pkg/action/upgrade.go | 32 ++-- pkg/action/upgrade_test.go | 32 ++-- pkg/bootloader/grub.go | 14 +- pkg/bootloader/grub_test.go | 8 +- pkg/cloudinit/cloudinit.go | 4 +- pkg/cloudinit/cloudinit_test.go | 20 +-- pkg/cloudinit/console.go | 20 +-- pkg/cloudinit/layout_plugin.go | 6 +- pkg/config/config.go | 188 ++++++++++++------------ pkg/config/config_test.go | 22 +-- pkg/elemental/elemental.go | 70 ++++----- pkg/elemental/elemental_test.go | 100 ++++++------- pkg/features/features.go | 6 +- pkg/http/client.go | 4 +- pkg/http/client_test.go | 6 +- pkg/mocks/bootloader_mock.go | 4 +- pkg/mocks/extractor_mock.go | 8 +- pkg/mocks/http_mock.go | 4 +- pkg/mocks/mounter_mock.go | 4 +- pkg/mocks/runner_mock.go | 8 +- pkg/mocks/utils.go | 4 +- pkg/partitioner/disk.go | 20 +-- pkg/partitioner/mkfs.go | 6 +- pkg/partitioner/options.go | 10 +- pkg/partitioner/parted.go | 6 +- pkg/partitioner/partitioner.go | 4 +- pkg/partitioner/partitioner_test.go | 8 +- pkg/partitioner/sgdisk.go | 8 +- pkg/snapshotter/btrfs.go | 42 +++--- pkg/snapshotter/btrfs_test.go | 26 ++-- pkg/snapshotter/common.go | 6 +- pkg/snapshotter/loopdevice.go | 36 ++--- pkg/snapshotter/loopdevice_test.go | 20 +-- pkg/systemd/unit.go | 6 +- pkg/types/{v2 => }/bootloader.go | 2 +- pkg/types/{v2 => }/cloud-init-runner.go | 2 +- pkg/types/{v2 => }/common.go | 2 +- pkg/types/{v2 => }/common_test.go | 36 ++--- pkg/types/{v2 => }/config.go | 2 +- pkg/types/{v2 => }/config_test.go | 162 ++++++++++---------- pkg/types/{v2 => }/errors.go | 2 +- pkg/types/{v2 => }/fs.go | 2 +- pkg/types/{v2 => }/grub.go | 2 +- pkg/types/{v2 => }/http.go | 2 +- pkg/types/{v2 => }/image.go | 10 +- pkg/types/{v2 => }/logger.go | 2 +- pkg/types/{v2 => }/logger_test.go | 20 +-- pkg/types/{v2 => }/mounter.go | 4 +- pkg/types/{v2 => }/platform.go | 2 +- pkg/types/{v2 => }/platform_test.go | 10 +- pkg/types/{v2 => }/runner.go | 2 +- pkg/types/{v2 => }/runner_test.go | 28 ++-- pkg/types/{v2 => }/snapshotter.go | 2 +- pkg/types/{v2 => }/syscall.go | 2 +- pkg/types/{v2 => }/syscall_test.go | 8 +- pkg/types/{v2 => }/types_suite_test.go | 2 +- pkg/utils/chroot.go | 8 +- pkg/utils/common.go | 58 ++++---- pkg/utils/fs.go | 26 ++-- pkg/utils/getpartitions.go | 12 +- pkg/utils/runstage.go | 8 +- pkg/utils/runstage_test.go | 10 +- pkg/utils/utils_test.go | 14 +- 87 files changed, 813 insertions(+), 813 deletions(-) rename pkg/types/{v2 => }/bootloader.go (98%) rename pkg/types/{v2 => }/cloud-init-runner.go (98%) rename pkg/types/{v2 => }/common.go (99%) rename pkg/types/{v2 => }/common_test.go (84%) rename pkg/types/{v2 => }/config.go (99%) rename pkg/types/{v2 => }/config_test.go (79%) rename pkg/types/{v2 => }/errors.go (98%) rename pkg/types/{v2 => }/fs.go (98%) rename pkg/types/{v2 => }/grub.go (99%) rename pkg/types/{v2 => }/http.go (97%) rename pkg/types/{v2 => }/image.go (87%) rename pkg/types/{v2 => }/logger.go (99%) rename pkg/types/{v2 => }/logger_test.go (79%) rename pkg/types/{v2 => }/mounter.go (91%) rename pkg/types/{v2 => }/platform.go (99%) rename pkg/types/{v2 => }/platform_test.go (85%) rename pkg/types/{v2 => }/runner.go (99%) rename pkg/types/{v2 => }/runner_test.go (81%) rename pkg/types/{v2 => }/snapshotter.go (99%) rename pkg/types/{v2 => }/syscall.go (98%) rename pkg/types/{v2 => }/syscall_test.go (92%) rename pkg/types/{v2 => }/types_suite_test.go (97%) diff --git a/cmd/build-disk.go b/cmd/build-disk.go index 0a116c769b3..6616b6a77f7 100644 --- a/cmd/build-disk.go +++ b/cmd/build-disk.go @@ -21,7 +21,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" eleError "github.com/rancher/elemental-toolkit/v2/pkg/error" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/spf13/cobra" "github.com/spf13/viper" @@ -45,8 +45,8 @@ func NewBuildDisk(root *cobra.Command, addCheckRoot bool) *cobra.Command { return nil }, RunE: func(cmd *cobra.Command, _ []string) (err error) { - var cfg *v2.BuildConfig - var spec *v2.DiskSpec + var cfg *types.BuildConfig + var spec *types.DiskSpec defer func() { if cfg != nil && err != nil { @@ -58,7 +58,7 @@ func NewBuildDisk(root *cobra.Command, addCheckRoot bool) *cobra.Command { if err != nil { return err } - mounter := v2.NewMounter(path) + mounter := types.NewMounter(path) flags := cmd.Flags() cfg, err = config.ReadConfigBuild(viper.GetString("config-dir"), flags, mounter) diff --git a/cmd/build-iso.go b/cmd/build-iso.go index 0d7a51ef8c8..a4d632f7339 100644 --- a/cmd/build-iso.go +++ b/cmd/build-iso.go @@ -26,7 +26,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/cmd/config" "github.com/rancher/elemental-toolkit/v2/pkg/action" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -53,7 +53,7 @@ func NewBuildISO(root *cobra.Command, addCheckRoot bool) *cobra.Command { if err != nil { return elementalError.NewFromError(err, elementalError.StatFile) } - mounter := v2.NewMounter(path) + mounter := types.NewMounter(path) cfg, err := config.ReadConfigBuild(viper.GetString("config-dir"), cmd.Flags(), mounter) if err != nil { @@ -78,12 +78,12 @@ func NewBuildISO(root *cobra.Command, addCheckRoot bool) *cobra.Command { } if len(args) == 1 { - imgSource, err := v2.NewSrcFromURI(args[0]) + imgSource, err := types.NewSrcFromURI(args[0]) if err != nil { cfg.Logger.Errorf("not a valid rootfs source image argument: %s", args[0]) return elementalError.NewFromError(err, elementalError.IdentifySource) } - spec.RootFS = []*v2.ImageSource{imgSource} + spec.RootFS = []*types.ImageSource{imgSource} } else if len(spec.RootFS) == 0 { errmsg := "rootfs source image for building ISO was not provided" cfg.Logger.Errorf(errmsg) @@ -98,7 +98,7 @@ func NewBuildISO(root *cobra.Command, addCheckRoot bool) *cobra.Command { if oRootfs != "" { if ok, err := utils.Exists(cfg.Fs, oRootfs); ok { - spec.RootFS = append(spec.RootFS, v2.NewDirSrc(oRootfs)) + spec.RootFS = append(spec.RootFS, types.NewDirSrc(oRootfs)) } else { msg := fmt.Sprintf("Invalid path '%s': %v", oRootfs, err) cfg.Logger.Errorf(msg) @@ -107,7 +107,7 @@ func NewBuildISO(root *cobra.Command, addCheckRoot bool) *cobra.Command { } if oUEFI != "" { if ok, err := utils.Exists(cfg.Fs, oUEFI); ok { - spec.UEFI = append(spec.UEFI, v2.NewDirSrc(oUEFI)) + spec.UEFI = append(spec.UEFI, types.NewDirSrc(oUEFI)) } else { msg := fmt.Sprintf("Invalid path '%s': %v", oUEFI, err) cfg.Logger.Errorf(msg) @@ -116,7 +116,7 @@ func NewBuildISO(root *cobra.Command, addCheckRoot bool) *cobra.Command { } if oISO != "" { if ok, err := utils.Exists(cfg.Fs, oISO); ok { - spec.Image = append(spec.Image, v2.NewDirSrc(oISO)) + spec.Image = append(spec.Image, types.NewDirSrc(oISO)) } else { msg := fmt.Sprintf("Invalid path '%s': %v", oISO, err) cfg.Logger.Errorf(msg) @@ -129,7 +129,7 @@ func NewBuildISO(root *cobra.Command, addCheckRoot bool) *cobra.Command { }, } - firmType := newEnumFlag([]string{v2.EFI}, v2.EFI) + firmType := newEnumFlag([]string{types.EFI}, types.EFI) root.AddCommand(c) c.Flags().StringP("name", "n", "", "Basename of the generated ISO file") diff --git a/cmd/cloud-init.go b/cmd/cloud-init.go index 984467e6a1f..a999b4dc70a 100644 --- a/cmd/cloud-init.go +++ b/cmd/cloud-init.go @@ -22,7 +22,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/cmd/config" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/yip/pkg/schema" "github.com/spf13/cobra" @@ -38,7 +38,7 @@ func NewCloudInitCmd(root *cobra.Command) *cobra.Command { _ = viper.BindPFlags(cmd.Flags()) }, RunE: func(cmd *cobra.Command, args []string) error { - cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), v2.NewDummyMounter()) + cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), types.NewDummyMounter()) if err != nil { return elementalError.NewFromError(err, elementalError.ReadingRunConfig) } diff --git a/cmd/config/config.go b/cmd/config/config.go index 708eca94ed8..db7c8dfdc69 100644 --- a/cmd/config/config.go +++ b/cmd/config/config.go @@ -34,7 +34,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/internal/version" "github.com/rancher/elemental-toolkit/v2/pkg/config" "github.com/rancher/elemental-toolkit/v2/pkg/constants" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -96,8 +96,8 @@ func bindGivenFlags(vp *viper.Viper, flagSet *pflag.FlagSet) { } } -func ReadConfigBuild(configDir string, flags *pflag.FlagSet, mounter v2.Mounter) (*v2.BuildConfig, error) { - logger := v2.NewLogger() +func ReadConfigBuild(configDir string, flags *pflag.FlagSet, mounter types.Mounter) (*types.BuildConfig, error) { + logger := types.NewLogger() cfg := config.NewBuildConfig( config.WithLogger(logger), @@ -142,9 +142,9 @@ func ReadConfigBuild(configDir string, flags *pflag.FlagSet, mounter v2.Mounter) return cfg, err } -func ReadConfigRun(configDir string, flags *pflag.FlagSet, mounter v2.Mounter) (*v2.RunConfig, error) { +func ReadConfigRun(configDir string, flags *pflag.FlagSet, mounter types.Mounter) (*types.RunConfig, error) { cfg := config.NewRunConfig( - config.WithLogger(v2.NewLogger()), + config.WithLogger(types.NewLogger()), config.WithMounter(mounter), config.WithOCIImageExtractor(), ) @@ -214,7 +214,7 @@ func ReadConfigRun(configDir string, flags *pflag.FlagSet, mounter v2.Mounter) ( return cfg, err } -func ReadInstallSpec(r *v2.RunConfig, flags *pflag.FlagSet) (*v2.InstallSpec, error) { +func ReadInstallSpec(r *types.RunConfig, flags *pflag.FlagSet) (*types.InstallSpec, error) { install := config.NewInstallSpec(r.Config) vp := viper.Sub("install") if vp == nil { @@ -234,7 +234,7 @@ func ReadInstallSpec(r *v2.RunConfig, flags *pflag.FlagSet) (*v2.InstallSpec, er return install, err } -func ReadInitSpec(r *v2.RunConfig, flags *pflag.FlagSet) (*v2.InitSpec, error) { +func ReadInitSpec(r *types.RunConfig, flags *pflag.FlagSet) (*types.InitSpec, error) { init := config.NewInitSpec() vp := viper.Sub("init") if vp == nil { @@ -252,7 +252,7 @@ func ReadInitSpec(r *v2.RunConfig, flags *pflag.FlagSet) (*v2.InitSpec, error) { return init, err } -func ReadMountSpec(r *v2.RunConfig, flags *pflag.FlagSet) (*v2.MountSpec, error) { +func ReadMountSpec(r *types.RunConfig, flags *pflag.FlagSet) (*types.MountSpec, error) { mount := config.NewMountSpec() vp := viper.Sub("mount") @@ -285,7 +285,7 @@ func ReadMountSpec(r *v2.RunConfig, flags *pflag.FlagSet) (*v2.MountSpec, error) return mount, err } -func applyKernelCmdline(r *v2.RunConfig, mount *v2.MountSpec) error { +func applyKernelCmdline(r *types.RunConfig, mount *types.MountSpec) error { cmdline, err := r.Config.Fs.ReadFile("/proc/cmdline") if err != nil { r.Logger.Errorf("Error reading /proc/cmdline: %s", err.Error()) @@ -322,7 +322,7 @@ func applyKernelCmdline(r *v2.RunConfig, mount *v2.MountSpec) error { } case "elemental.oemlabel": oemdev := fmt.Sprintf("LABEL=%s", val) - var mnt *v2.VolumeMount + var mnt *types.VolumeMount for _, mnt = range mount.Volumes { if mnt.Mountpoint == constants.OEMPath { mnt.Device = oemdev @@ -330,7 +330,7 @@ func applyKernelCmdline(r *v2.RunConfig, mount *v2.MountSpec) error { } } if mnt == nil { - mount.Volumes = append(mount.Volumes, &v2.VolumeMount{ + mount.Volumes = append(mount.Volumes, &types.VolumeMount{ Mountpoint: constants.OEMPath, Device: oemdev, Options: []string{"rw", "defaults"}, @@ -342,7 +342,7 @@ func applyKernelCmdline(r *v2.RunConfig, mount *v2.MountSpec) error { return nil } -func applyMountEnvVars(r *v2.RunConfig, mount *v2.MountSpec) error { +func applyMountEnvVars(r *types.RunConfig, mount *types.MountSpec) error { r.Logger.Debugf("Applying mount env-vars") overlay := os.Getenv("OVERLAY") @@ -376,7 +376,7 @@ func applyMountEnvVars(r *v2.RunConfig, mount *v2.MountSpec) error { return nil } -func applyMountOverlay(mount *v2.MountSpec, overlay string) error { +func applyMountOverlay(mount *types.MountSpec, overlay string) error { split := strings.Split(overlay, ":") if len(split) == 2 && split[0] == constants.Tmpfs { @@ -406,7 +406,7 @@ func applyMountOverlay(mount *v2.MountSpec, overlay string) error { return nil } -func ReadResetSpec(r *v2.RunConfig, flags *pflag.FlagSet) (*v2.ResetSpec, error) { +func ReadResetSpec(r *types.RunConfig, flags *pflag.FlagSet) (*types.ResetSpec, error) { reset, err := config.NewResetSpec(r.Config) if err != nil { return nil, fmt.Errorf("failed initializing reset spec: %v", err) @@ -429,7 +429,7 @@ func ReadResetSpec(r *v2.RunConfig, flags *pflag.FlagSet) (*v2.ResetSpec, error) return reset, err } -func ReadUpgradeSpec(r *v2.RunConfig, flags *pflag.FlagSet, recoveryOnly bool) (*v2.UpgradeSpec, error) { +func ReadUpgradeSpec(r *types.RunConfig, flags *pflag.FlagSet, recoveryOnly bool) (*types.UpgradeSpec, error) { upgrade, err := config.NewUpgradeSpec(r.Config) if err != nil { return nil, fmt.Errorf("failed initializing upgrade spec: %v", err) @@ -457,7 +457,7 @@ func ReadUpgradeSpec(r *v2.RunConfig, flags *pflag.FlagSet, recoveryOnly bool) ( return upgrade, err } -func ReadBuildISO(b *v2.BuildConfig, flags *pflag.FlagSet) (*v2.LiveISO, error) { +func ReadBuildISO(b *types.BuildConfig, flags *pflag.FlagSet) (*types.LiveISO, error) { iso := config.NewISO() vp := viper.Sub("iso") if vp == nil { @@ -477,7 +477,7 @@ func ReadBuildISO(b *v2.BuildConfig, flags *pflag.FlagSet) (*v2.LiveISO, error) return iso, err } -func ReadBuildDisk(b *v2.BuildConfig, flags *pflag.FlagSet) (*v2.DiskSpec, error) { +func ReadBuildDisk(b *types.BuildConfig, flags *pflag.FlagSet) (*types.DiskSpec, error) { disk := config.NewDisk(b) vp := viper.Sub("disk") if vp == nil { @@ -497,10 +497,10 @@ func ReadBuildDisk(b *v2.BuildConfig, flags *pflag.FlagSet) (*v2.DiskSpec, error return disk, err } -func configLogger(log v2.Logger, vfs v2.FS) { +func configLogger(log types.Logger, vfs types.FS) { // Set debug level if viper.GetBool("debug") { - log.SetLevel(v2.DebugLevel()) + log.SetLevel(types.DebugLevel()) } // Set formatter so both file and stdout format are equal diff --git a/cmd/config/config_test.go b/cmd/config/config_test.go index 29d6766d3f3..6fb0b6612b2 100644 --- a/cmd/config/config_test.go +++ b/cmd/config/config_test.go @@ -38,7 +38,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) var _ = Describe("Config", Label("config"), func() { @@ -58,7 +58,7 @@ var _ = Describe("Config", Label("config"), func() { Expect(err).ShouldNot(HaveOccurred()) Expect(cfg.Snapshotter.MaxSnaps).To(Equal(7), litter.Sdump(cfg)) Expect(cfg.Snapshotter.Type).To(Equal(constants.LoopDeviceSnapshotterType), litter.Sdump(cfg)) - loop, ok := cfg.Snapshotter.Config.(*v2.LoopDeviceConfig) + loop, ok := cfg.Snapshotter.Config.(*types.LoopDeviceConfig) Expect(ok).To(BeTrue()) Expect(loop.Size).To(Equal(uint(2000))) @@ -132,10 +132,10 @@ var _ = Describe("Config", Label("config"), func() { }) Describe("Read build specs", Label("build"), func() { - var cfg *v2.BuildConfig + var cfg *types.BuildConfig var runner *v2mock.FakeRunner var fs vfs.FS - var logger v2.Logger + var logger types.Logger var mounter *v2mock.FakeMounter var syscall *v2mock.FakeSyscall var client *v2mock.FakeHTTPClient @@ -150,7 +150,7 @@ var _ = Describe("Config", Label("config"), func() { mounter = v2mock.NewFakeMounter() client = &v2mock.FakeHTTPClient{} memLog = &bytes.Buffer{} - logger = v2.NewBufferLogger(memLog) + logger = types.NewBufferLogger(memLog) cloudInit = &v2mock.FakeCloudInitRunner{} fs, cleanup, err = vfst.NewTestFS(map[string]interface{}{}) @@ -219,7 +219,7 @@ var _ = Describe("Config", Label("config"), func() { Expect(cfg.Mounter == mounter).To(BeTrue()) // Sets a RealRunner instance by default Expect(cfg.Runner != nil).To(BeTrue()) - _, ok := cfg.Runner.(*v2.RealRunner) + _, ok := cfg.Runner.(*types.RealRunner) Expect(ok).To(BeTrue()) }) It("uses provided configs and flags, flags have priority", func() { @@ -257,7 +257,7 @@ var _ = Describe("Config", Label("config"), func() { Expect(cfg.Reboot).To(BeTrue()) Expect(cfg.Snapshotter.Type).To(Equal(constants.LoopDeviceSnapshotterType)) Expect(cfg.Snapshotter.MaxSnaps).To(Equal(constants.LoopDeviceMaxSnaps)) - snapshooterCfg, ok := cfg.Snapshotter.Config.(*v2.LoopDeviceConfig) + snapshooterCfg, ok := cfg.Snapshotter.Config.(*types.LoopDeviceConfig) Expect(ok).To(BeTrue()) Expect(snapshooterCfg.FS).To(Equal("xfs")) Expect(snapshooterCfg.Size).To(Equal(uint(1024))) @@ -274,10 +274,10 @@ var _ = Describe("Config", Label("config"), func() { }) }) Describe("Read runtime specs", Label("spec"), func() { - var cfg *v2.RunConfig + var cfg *types.RunConfig var runner *v2mock.FakeRunner var fs vfs.FS - var logger v2.Logger + var logger types.Logger var mounter *v2mock.FakeMounter var syscall *v2mock.FakeSyscall var client *v2mock.FakeHTTPClient @@ -292,7 +292,7 @@ var _ = Describe("Config", Label("config"), func() { mounter = v2mock.NewFakeMounter() client = &v2mock.FakeHTTPClient{} memLog = &bytes.Buffer{} - logger = v2.NewBufferLogger(memLog) + logger = types.NewBufferLogger(memLog) cloudInit = &v2mock.FakeCloudInitRunner{} fs, cleanup, err = vfst.NewTestFS(map[string]interface{}{}) @@ -329,8 +329,8 @@ var _ = Describe("Config", Label("config"), func() { spec, err := ReadInstallSpec(cfg, nil) Expect(err).ShouldNot(HaveOccurred()) Expect(spec.Target == "") - Expect(spec.PartTable == v2.GPT) - Expect(spec.Firmware == v2.BIOS) + Expect(spec.PartTable == types.GPT) + Expect(spec.Firmware == types.BIOS) Expect(spec.NoFormat == false) }) It("inits an install spec according to given configs", func() { diff --git a/cmd/flags.go b/cmd/flags.go index 082f5d09066..e30d317676e 100644 --- a/cmd/flags.go +++ b/cmd/flags.go @@ -25,7 +25,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/pflag" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) // addCosignFlags adds flags related to cosign @@ -90,7 +90,7 @@ func adaptDockerImageAndDirectoryFlagsToSystem(flags *pflag.FlagSet) { } } -func validateCosignFlags(log v2.Logger, flags *pflag.FlagSet) error { +func validateCosignFlags(log types.Logger, flags *pflag.FlagSet) error { cosignKey, _ := flags.GetString("cosign-key") cosign, _ := flags.GetBool("cosign") @@ -104,7 +104,7 @@ func validateCosignFlags(log v2.Logger, flags *pflag.FlagSet) error { return nil } -func validateSourceFlags(_ v2.Logger, flags *pflag.FlagSet) error { +func validateSourceFlags(_ types.Logger, flags *pflag.FlagSet) error { msg := "flags docker-image, directory and system are mutually exclusive, please only set one of them" system, _ := flags.GetString("system") directory, _ := flags.GetString("directory") @@ -119,7 +119,7 @@ func validateSourceFlags(_ v2.Logger, flags *pflag.FlagSet) error { return nil } -func validatePowerFlags(_ v2.Logger, flags *pflag.FlagSet) error { +func validatePowerFlags(_ types.Logger, flags *pflag.FlagSet) error { reboot, _ := flags.GetBool("reboot") poweroff, _ := flags.GetBool("poweroff") if reboot && poweroff { @@ -129,7 +129,7 @@ func validatePowerFlags(_ v2.Logger, flags *pflag.FlagSet) error { } // validateUpgradeFlags is a helper call to check all the flags for the upgrade command -func validateInstallUpgradeFlags(log v2.Logger, flags *pflag.FlagSet) error { +func validateInstallUpgradeFlags(log types.Logger, flags *pflag.FlagSet) error { if err := validateSourceFlags(log, flags); err != nil { return err } diff --git a/cmd/init.go b/cmd/init.go index 566f8544095..bd076f7775f 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -26,7 +26,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/action" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" "github.com/rancher/elemental-toolkit/v2/pkg/features" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) func InitCmd(root *cobra.Command) *cobra.Command { @@ -39,7 +39,7 @@ func InitCmd(root *cobra.Command) *cobra.Command { " Defaults to all", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), v2.NewDummyMounter()) + cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), types.NewDummyMounter()) if err != nil { cfg.Logger.Errorf("Error reading config: %s\n", err) return elementalError.NewFromError(err, elementalError.ReadingRunConfig) diff --git a/cmd/install.go b/cmd/install.go index 0db90528940..0210c3371cf 100644 --- a/cmd/install.go +++ b/cmd/install.go @@ -26,8 +26,8 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/action" "github.com/rancher/elemental-toolkit/v2/pkg/constants" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" - "github.com/rancher/elemental-toolkit/v2pkg/utils" + "github.com/rancher/elemental-toolkit/v2/pkg/types" + "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) // NewInstallCmd returns a new instance of the install subcommand and appends it to @@ -49,7 +49,7 @@ func NewInstallCmd(root *cobra.Command, addCheckRoot bool) *cobra.Command { if err != nil { return err } - mounter := v2.NewMounter(path) + mounter := types.NewMounter(path) cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), mounter) if err != nil { @@ -93,8 +93,8 @@ func NewInstallCmd(root *cobra.Command, addCheckRoot bool) *cobra.Command { return install.Run() }, } - firmType := newEnumFlag([]string{v2.EFI}, v2.EFI) - pTableType := newEnumFlag([]string{v2.GPT}, v2.GPT) + firmType := newEnumFlag([]string{types.EFI}, types.EFI) + pTableType := newEnumFlag([]string{types.GPT}, types.GPT) snapshotterType := newEnumFlag( []string{constants.LoopDeviceSnapshotterType, constants.BtrfsSnapshotterType}, constants.LoopDeviceSnapshotterType, diff --git a/cmd/pull-image.go b/cmd/pull-image.go index 7020b6141f2..01dee7f0e3b 100644 --- a/cmd/pull-image.go +++ b/cmd/pull-image.go @@ -24,7 +24,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/cmd/config" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) func NewPullImageCmd(root *cobra.Command, addCheckRoot bool) *cobra.Command { @@ -39,7 +39,7 @@ func NewPullImageCmd(root *cobra.Command, addCheckRoot bool) *cobra.Command { return nil }, RunE: func(cmd *cobra.Command, args []string) error { - cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), v2.NewDummyMounter()) + cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), types.NewDummyMounter()) if err != nil { cfg.Logger.Errorf("Error reading config: %s\n", err) return elementalError.NewFromError(err, elementalError.ReadingRunConfig) @@ -65,7 +65,7 @@ func NewPullImageCmd(root *cobra.Command, addCheckRoot bool) *cobra.Command { cfg.Logger.Infof("Pulling image %s platform %s", image, cfg.Platform.String()) var digest string - e := v2.OCIImageExtractor{} + e := types.OCIImageExtractor{} if digest, err = e.ExtractImage(image, destination, cfg.Platform.String(), local); err != nil { cfg.Logger.Error(err.Error()) return elementalError.NewFromError(err, elementalError.UnpackImage) diff --git a/cmd/reset.go b/cmd/reset.go index 700553146d5..a34a44e9a9a 100644 --- a/cmd/reset.go +++ b/cmd/reset.go @@ -25,7 +25,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/cmd/config" "github.com/rancher/elemental-toolkit/v2/pkg/action" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) func NewResetCmd(root *cobra.Command, addCheckRoot bool) *cobra.Command { @@ -44,7 +44,7 @@ func NewResetCmd(root *cobra.Command, addCheckRoot bool) *cobra.Command { if err != nil { return err } - mounter := v2.NewMounter(path) + mounter := types.NewMounter(path) cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), mounter) if err != nil { diff --git a/cmd/run-stage.go b/cmd/run-stage.go index dbb3a7acb7d..ffb0ec29d9c 100644 --- a/cmd/run-stage.go +++ b/cmd/run-stage.go @@ -22,7 +22,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/cmd/config" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -32,7 +32,7 @@ func NewRunStage(root *cobra.Command) *cobra.Command { Short: "Run stage from cloud-init", Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), v2.NewDummyMounter()) + cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), types.NewDummyMounter()) if err != nil { cfg.Logger.Errorf("Error reading config: %s\n", err) return elementalError.NewFromError(err, elementalError.ReadingRunConfig) diff --git a/cmd/upgrade.go b/cmd/upgrade.go index 2f12d4807a0..19c72a80bcf 100644 --- a/cmd/upgrade.go +++ b/cmd/upgrade.go @@ -25,7 +25,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/cmd/config" "github.com/rancher/elemental-toolkit/v2/pkg/action" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) // NewUpgradeCmd returns a new instance of the upgrade subcommand and appends it to @@ -48,7 +48,7 @@ func NewUpgradeCmd(root *cobra.Command, addCheckRoot bool) *cobra.Command { if err != nil { return err } - mounter := v2.NewMounter(path) + mounter := types.NewMounter(path) cfg, err := config.ReadConfigRun(viper.GetString("config-dir"), cmd.Flags(), mounter) if err != nil { diff --git a/pkg/action/build-disk.go b/pkg/action/build-disk.go index 0a7333de523..39767658ebc 100644 --- a/pkg/action/build-disk.go +++ b/pkg/action/build-disk.go @@ -35,7 +35,7 @@ import ( elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" "github.com/rancher/elemental-toolkit/v2/pkg/partitioner" "github.com/rancher/elemental-toolkit/v2/pkg/snapshotter" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -51,18 +51,18 @@ const ( ) type BuildDiskAction struct { - cfg *v2.BuildConfig - spec *v2.DiskSpec - bootloader v2.Bootloader - snapshotter v2.Snapshotter - snapshot *v2.Snapshot + cfg *types.BuildConfig + spec *types.DiskSpec + bootloader types.Bootloader + snapshotter types.Snapshotter + snapshot *types.Snapshot // holds the root path within the working directory of all partitions roots map[string]string } type BuildDiskActionOption func(b *BuildDiskAction) error -func NewBuildDiskAction(cfg *v2.BuildConfig, spec *v2.DiskSpec, opts ...BuildDiskActionOption) (*BuildDiskAction, error) { +func NewBuildDiskAction(cfg *types.BuildConfig, spec *types.DiskSpec, opts ...BuildDiskActionOption) (*BuildDiskAction, error) { var err error b := &BuildDiskAction{cfg: cfg, spec: spec} @@ -93,7 +93,7 @@ func NewBuildDiskAction(cfg *v2.BuildConfig, spec *v2.DiskSpec, opts ...BuildDis return b, err } -func WithDiskBootloader(bootloader v2.Bootloader) BuildDiskActionOption { +func WithDiskBootloader(bootloader types.Bootloader) BuildDiskActionOption { return func(b *BuildDiskAction) error { b.bootloader = bootloader return nil @@ -111,14 +111,14 @@ func (b *BuildDiskAction) buildDiskChrootHook(hook string, root string) error { func (b *BuildDiskAction) preparePartitionsRoot() error { var err error - var excludes []*v2.Partition + var excludes []*types.Partition rootMap := map[string]string{} if b.spec.Expandable { excludes = append(excludes, b.spec.Partitions.Persistent, b.spec.Partitions.State) } - for _, part := range b.spec.Partitions.PartitionsByInstallOrder(v2.PartitionList{}, excludes...) { + for _, part := range b.spec.Partitions.PartitionsByInstallOrder(types.PartitionList{}, excludes...) { rootMap[part.Name] = strings.TrimSuffix(part.Path, filepath.Ext(part.Path)) err = utils.MkdirAll(b.cfg.Fs, rootMap[part.Name], constants.DirPerm) if err != nil { @@ -326,10 +326,10 @@ func (b *BuildDiskAction) CreateRAWDisk(rawImg string) error { } // CreatePartitionImage creates partition image files and returns a slice of the created images -func (b *BuildDiskAction) CreatePartitionImages() ([]*v2.Image, error) { +func (b *BuildDiskAction) CreatePartitionImages() ([]*types.Image, error) { var err error - var img, stateImg *v2.Image - var images []*v2.Image + var img, stateImg *types.Image + var images []*types.Image // Create state partition first to compute snapshot metadata if any if !b.spec.Expandable { @@ -356,7 +356,7 @@ func (b *BuildDiskAction) CreatePartitionImages() ([]*v2.Image, error) { } images = append(images, img) - for _, part := range []*v1.Partition{b.spec.Partitions.OEM, b.spec.Partitions.Recovery} { + for _, part := range []*types.Partition{b.spec.Partitions.OEM, b.spec.Partitions.Recovery} { b.cfg.Logger.Infof("Creating %s partition image", part.Name) img = part.ToImage() err = elemental.CreateImageFromTree( @@ -391,7 +391,7 @@ func (b *BuildDiskAction) CreatePartitionImages() ([]*v2.Image, error) { } // createStatePartitionImage creates the State partitions for the configured snapshotter -func (b *BuildDiskAction) createStatePartitionImage() (*v2.Image, error) { +func (b *BuildDiskAction) createStatePartitionImage() (*types.Image, error) { stateImg := b.spec.Partitions.State.ToImage() err := elemental.CreateFileSystemImage(b.cfg.Config, stateImg, "", false) @@ -458,7 +458,7 @@ func (b *BuildDiskAction) createStatePartitionImage() (*v2.Image, error) { } // createEFIPartitionImage creates the EFI partition image -func (b *BuildDiskAction) createEFIPartitionImage() (*v2.Image, error) { +func (b *BuildDiskAction) createEFIPartitionImage() (*types.Image, error) { img := b.spec.Partitions.EFI.ToImage() err := elemental.CreateFileSystemImage(b.cfg.Config, img, "", false) if err != nil { @@ -491,7 +491,7 @@ func (b *BuildDiskAction) createEFIPartitionImage() (*v2.Image, error) { // CreateDiskImage creates the final image by truncating the image with the proper size and // concatenating the contents of the given partitions. No partition table is written -func (b *BuildDiskAction) CreateDiskImage(rawDiskFile string, partImgs ...*v2.Image) error { +func (b *BuildDiskAction) CreateDiskImage(rawDiskFile string, partImgs ...*types.Image) error { var initDiskFile, endDiskFile string var err error var partFiles []string @@ -545,7 +545,7 @@ func (b *BuildDiskAction) CreateDiskImage(rawDiskFile string, partImgs ...*v2.Im // Raw2Gce transforms an image from RAW format into GCE format // THIS REMOVES THE SOURCE IMAGE BY DEFAULT -func Raw2Gce(source string, fs v2.FS, logger v2.Logger, keepOldImage bool) error { +func Raw2Gce(source string, fs types.FS, logger types.Logger, keepOldImage bool) error { // The RAW image file must have a size in an increment of 1 GB. For example, the file must be either 10 GB or 11 GB but not 10.5 GB. // The disk image filename must be disk.raw. // The compressed file must be a .tar.gz file that uses gzip compression and the --format=oldgnu option for the tar utility. @@ -617,7 +617,7 @@ func Raw2Gce(source string, fs v2.FS, logger v2.Logger, keepOldImage bool) error // Raw2Azure transforms an image from RAW format into Azure format // THIS REMOVES THE SOURCE IMAGE BY DEFAULT -func Raw2Azure(source string, fs v2.FS, logger v2.Logger, keepOldImage bool) error { +func Raw2Azure(source string, fs types.FS, logger types.Logger, keepOldImage bool) error { // All VHDs on Azure must have a virtual size aligned to 1 MB (1024 × 1024 bytes) // The Hyper-V virtual hard disk (VHDX) format isn't supported in Azure, only fixed VHD logger.Info("Transforming raw image into azure format") @@ -655,7 +655,7 @@ func Raw2Azure(source string, fs v2.FS, logger v2.Logger, keepOldImage bool) err func (b *BuildDiskAction) CreateDiskPartitionTable(disk string) error { var secSize, startS, sizeS uint - var excludes v2.PartitionList + var excludes types.PartitionList gd := partitioner.NewPartitioner(disk, b.cfg.Runner, partitioner.Gdisk) dData, err := gd.Print() @@ -671,7 +671,7 @@ func (b *BuildDiskAction) CreateDiskPartitionTable(disk string) error { if b.spec.Expandable { excludes = append(excludes, b.spec.Partitions.State, b.spec.Partitions.Persistent) } - elParts := b.spec.Partitions.PartitionsByInstallOrder(v2.PartitionList{}, excludes...) + elParts := b.spec.Partitions.PartitionsByInstallOrder(types.PartitionList{}, excludes...) for i, part := range elParts { if i == 0 { //First partition is aligned at 1MiB @@ -720,26 +720,26 @@ func (b *BuildDiskAction) createBuildDiskStateYaml(stateRoot, recoveryRoot strin return fmt.Errorf("undefined state partition") } - snapshots := map[int]*v2.SystemState{} + snapshots := map[int]*types.SystemState{} if !b.spec.Expandable { - snapshots[b.snapshot.ID] = &v2.SystemState{ + snapshots[b.snapshot.ID] = &types.SystemState{ Source: b.spec.System, Digest: b.spec.System.GetDigest(), Active: true, } } - installState := &v2.InstallState{ + installState := &types.InstallState{ Date: time.Now().Format(time.RFC3339), Snapshotter: b.cfg.Snapshotter, - Partitions: map[string]*v2.PartitionState{ + Partitions: map[string]*types.PartitionState{ constants.StatePartName: { FSLabel: b.spec.Partitions.State.FilesystemLabel, Snapshots: snapshots, }, constants.RecoveryPartName: { FSLabel: b.spec.Partitions.Recovery.FilesystemLabel, - RecoveryImage: &v2.SystemState{ + RecoveryImage: &types.SystemState{ Source: b.spec.RecoverySystem.Source, Digest: b.spec.RecoverySystem.Source.GetDigest(), Label: b.spec.RecoverySystem.Label, @@ -750,17 +750,17 @@ func (b *BuildDiskAction) createBuildDiskStateYaml(stateRoot, recoveryRoot strin } if b.spec.Partitions.OEM != nil { - installState.Partitions[constants.OEMPartName] = &v2.PartitionState{ + installState.Partitions[constants.OEMPartName] = &types.PartitionState{ FSLabel: b.spec.Partitions.OEM.FilesystemLabel, } } if b.spec.Partitions.Persistent != nil { - installState.Partitions[constants.PersistentPartName] = &v2.PartitionState{ + installState.Partitions[constants.PersistentPartName] = &types.PartitionState{ FSLabel: b.spec.Partitions.Persistent.FilesystemLabel, } } if b.spec.Partitions.EFI != nil { - installState.Partitions[constants.EfiPartName] = &v2.PartitionState{ + installState.Partitions[constants.EfiPartName] = &types.PartitionState{ FSLabel: b.spec.Partitions.EFI.FilesystemLabel, } } diff --git a/pkg/action/build-iso.go b/pkg/action/build-iso.go index 6b205cb1df7..670c3bdb1c8 100644 --- a/pkg/action/build-iso.go +++ b/pkg/action/build-iso.go @@ -25,7 +25,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" "github.com/rancher/elemental-toolkit/v2/pkg/elemental" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -49,20 +49,20 @@ func grubCfgTemplate(arch string) string { } type BuildISOAction struct { - cfg *v2.BuildConfig - spec *v2.LiveISO - bootloader v2.Bootloader + cfg *types.BuildConfig + spec *types.LiveISO + bootloader types.Bootloader } type BuildISOActionOption func(a *BuildISOAction) -func WithLiveBootloader(b v2.Bootloader) BuildISOActionOption { +func WithLiveBootloader(b types.Bootloader) BuildISOActionOption { return func(a *BuildISOAction) { a.bootloader = b } } -func NewBuildISOAction(cfg *v2.BuildConfig, spec *v2.LiveISO, opts ...BuildISOActionOption) *BuildISOAction { +func NewBuildISOAction(cfg *types.BuildConfig, spec *types.LiveISO, opts ...BuildISOActionOption) *BuildISOAction { b := &BuildISOAction{ cfg: cfg, spec: spec, @@ -131,7 +131,7 @@ func (b *BuildISOAction) ISORun() error { return elementalError.NewFromError(err, elementalError.CreateDir) } - if b.spec.Firmware == v2.EFI { + if b.spec.Firmware == types.EFI { b.cfg.Logger.Infof("Preparing EFI image...") if b.spec.BootloaderInRootFs { err = b.PrepareEFI(rootDir, uefiDir) @@ -167,7 +167,7 @@ func (b *BuildISOAction) ISORun() error { return err } - if b.spec.Firmware == v2.EFI { + if b.spec.Firmware == types.EFI { b.cfg.Logger.Info("Creating EFI image...") err = b.createEFI(uefiDir, filepath.Join(isoTmpDir, constants.ISOEFIImg)) if err != nil { @@ -251,7 +251,7 @@ func (b BuildISOAction) createEFI(root string, img string) error { align := int64(4 * 1024 * 1024) efiSizeMB := (efiSize/align*align + align) / (1024 * 1024) - err = elemental.CreateFileSystemImage(b.cfg.Config, &v2.Image{ + err = elemental.CreateFileSystemImage(b.cfg.Config, &types.Image{ File: img, Size: uint(efiSizeMB), FS: constants.EfiFs, @@ -327,7 +327,7 @@ func (b BuildISOAction) burnISO(root, efiImg string) error { return nil } -func (b BuildISOAction) applySources(target string, sources ...*v2.ImageSource) error { +func (b BuildISOAction) applySources(target string, sources ...*types.ImageSource) error { for _, src := range sources { err := elemental.DumpSource(b.cfg.Config, target, src) if err != nil { diff --git a/pkg/action/build_test.go b/pkg/action/build_test.go index 9b1a7fa14a7..4322f8b58d2 100644 --- a/pkg/action/build_test.go +++ b/pkg/action/build_test.go @@ -35,15 +35,15 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/config" "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) var _ = Describe("Build Actions", func() { - var cfg *v2.BuildConfig + var cfg *types.BuildConfig var runner *v2mock.FakeRunner var fs vfs.FS - var logger v2.Logger + var logger types.Logger var mounter *v2mock.FakeMounter var syscall *v2mock.FakeSyscall var client *v2mock.FakeHTTPClient @@ -60,7 +60,7 @@ var _ = Describe("Build Actions", func() { client = &v2mock.FakeHTTPClient{} memLog = &bytes.Buffer{} bootloader = &v2mock.FakeBootloader{} - logger = v2.NewBufferLogger(memLog) + logger = types.NewBufferLogger(memLog) logger.SetLevel(logrus.DebugLevel) extractor = v2mock.NewFakeImageExtractor(logger) cloudInit = &v2mock.FakeCloudInitRunner{} @@ -82,7 +82,7 @@ var _ = Describe("Build Actions", func() { cleanup() }) Describe("Build ISO", Label("iso"), func() { - var iso *v2.LiveISO + var iso *types.LiveISO BeforeEach(func() { iso = config.NewISO() @@ -103,8 +103,8 @@ var _ = Describe("Build Actions", func() { } }) It("Successfully builds an ISO from an OCI image", func() { - rootSrc, _ := v2.NewSrcFromURI("oci:elementalos:latest") - iso.RootFS = []*v2.ImageSource{rootSrc} + rootSrc, _ := types.NewSrcFromURI("oci:elementalos:latest") + iso.RootFS = []*types.ImageSource{rootSrc} extractor.SideEffect = func(_, destination, platform string, _ bool) (string, error) { bootDir := filepath.Join(destination, "boot") @@ -134,7 +134,7 @@ var _ = Describe("Build Actions", func() { It("Fails on prepare EFI", func() { iso.BootloaderInRootFs = true - rootSrc, _ := v2.NewSrcFromURI("oci:elementalos:latest") + rootSrc, _ := types.NewSrcFromURI("oci:elementalos:latest") iso.RootFS = append(iso.RootFS, rootSrc) buildISO := action.NewBuildISOAction(cfg, iso, action.WithLiveBootloader(bootloader)) @@ -144,7 +144,7 @@ var _ = Describe("Build Actions", func() { It("Fails on prepare ISO", func() { iso.BootloaderInRootFs = true - rootSrc, _ := v2.NewSrcFromURI("channel:system/elemental") + rootSrc, _ := types.NewSrcFromURI("channel:system/elemental") iso.RootFS = append(iso.RootFS, rootSrc) buildISO := action.NewBuildISOAction(cfg, iso, action.WithLiveBootloader(bootloader)) @@ -153,8 +153,8 @@ var _ = Describe("Build Actions", func() { Expect(err).Should(HaveOccurred()) }) It("Fails if kernel or initrd is not found in rootfs", func() { - rootSrc, _ := v2.NewSrcFromURI("dir:/local/dir") - iso.RootFS = []*v2.ImageSource{rootSrc} + rootSrc, _ := types.NewSrcFromURI("dir:/local/dir") + iso.RootFS = []*types.ImageSource{rootSrc} err := utils.MkdirAll(fs, "/local/dir/boot", constants.DirPerm) Expect(err).ShouldNot(HaveOccurred()) @@ -172,18 +172,18 @@ var _ = Describe("Build Actions", func() { Expect(err).Should(HaveOccurred()) }) It("Fails installing uefi sources", func() { - rootSrc, _ := v2.NewSrcFromURI("docker:elemental:latest") - iso.RootFS = []*v2.ImageSource{rootSrc} - uefiSrc, _ := v2.NewSrcFromURI("dir:/overlay/efi") - iso.UEFI = []*v2.ImageSource{uefiSrc} + rootSrc, _ := types.NewSrcFromURI("docker:elemental:latest") + iso.RootFS = []*types.ImageSource{rootSrc} + uefiSrc, _ := types.NewSrcFromURI("dir:/overlay/efi") + iso.UEFI = []*types.ImageSource{uefiSrc} buildISO := action.NewBuildISOAction(cfg, iso) err := buildISO.ISORun() Expect(err).Should(HaveOccurred()) }) It("Fails on ISO filesystem creation", func() { - rootSrc, _ := v2.NewSrcFromURI("oci:elementalos:latest") - iso.RootFS = []*v2.ImageSource{rootSrc} + rootSrc, _ := types.NewSrcFromURI("oci:elementalos:latest") + iso.RootFS = []*types.ImageSource{rootSrc} runner.SideEffect = func(command string, args ...string) ([]byte, error) { if command == "xorriso" { @@ -199,7 +199,7 @@ var _ = Describe("Build Actions", func() { }) }) Describe("Build disk", Label("disk", "build"), func() { - var disk *v2.DiskSpec + var disk *types.DiskSpec BeforeEach(func() { tmpDir, err := utils.TempDir(fs, "", "test") @@ -208,7 +208,7 @@ var _ = Describe("Build Actions", func() { cfg.Date = false cfg.OutDir = tmpDir disk = config.NewDisk(cfg) - disk.System = v2.NewDockerSrc("some/image/ref:tag") + disk.System = types.NewDockerSrc("some/image/ref:tag") disk.RecoverySystem.Source = disk.System disk.Partitions.Recovery.Size = constants.MinPartSize disk.Partitions.State.Size = constants.MinPartSize diff --git a/pkg/action/common.go b/pkg/action/common.go index 8dbd970f68c..c1a01250ea8 100644 --- a/pkg/action/common.go +++ b/pkg/action/common.go @@ -20,13 +20,13 @@ import ( "github.com/sirupsen/logrus" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) // Hook is RunStage wrapper that only adds logic to ignore errors -// in case v2.RunConfig.Strict is set to false -func Hook(config *v2.Config, hook string, strict bool, cloudInitPaths ...string) error { +// in case types.RunConfig.Strict is set to false +func Hook(config *types.Config, hook string, strict bool, cloudInitPaths ...string) error { config.Logger.Infof("Running %s hook", hook) oldLevel := config.Logger.GetLevel() config.Logger.SetLevel(logrus.ErrorLevel) @@ -39,7 +39,7 @@ func Hook(config *v2.Config, hook string, strict bool, cloudInitPaths ...string) } // ChrootHook executes Hook inside a chroot environment -func ChrootHook(config *v2.Config, hook string, strict bool, chrootDir string, bindMounts map[string]string, cloudInitPaths ...string) (err error) { +func ChrootHook(config *types.Config, hook string, strict bool, chrootDir string, bindMounts map[string]string, cloudInitPaths ...string) (err error) { callback := func() error { return Hook(config, hook, strict, cloudInitPaths...) } @@ -48,7 +48,7 @@ func ChrootHook(config *v2.Config, hook string, strict bool, chrootDir string, b // PowerAction executes a power-action (Reboot/PowerOff) after completed // install or upgrade and returns any encountered error. -func PowerAction(cfg *v2.RunConfig) error { +func PowerAction(cfg *types.RunConfig) error { // Reboot, poweroff or nothing var ( err error diff --git a/pkg/action/init.go b/pkg/action/init.go index 2092216be09..41968247777 100644 --- a/pkg/action/init.go +++ b/pkg/action/init.go @@ -23,11 +23,11 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" "github.com/rancher/elemental-toolkit/v2/pkg/features" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) -func RunInit(cfg *v2.RunConfig, spec *v2.InitSpec) error { +func RunInit(cfg *types.RunConfig, spec *types.InitSpec) error { if exists, _ := utils.Exists(cfg.Fs, "/.dockerenv"); !exists && !spec.Force { return elementalError.New("running outside of container, pass --force to run anyway", elementalError.StatFile) } diff --git a/pkg/action/init_test.go b/pkg/action/init_test.go index 0f291430f1a..53e026462bf 100644 --- a/pkg/action/init_test.go +++ b/pkg/action/init_test.go @@ -31,15 +31,15 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" "github.com/rancher/elemental-toolkit/v2/pkg/features" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) var _ = Describe("Init Action", func() { - var cfg *v2.RunConfig + var cfg *types.RunConfig var runner *v2mock.FakeRunner var fs vfs.FS - var logger v2.Logger + var logger types.Logger var cleanup func() var memLog *bytes.Buffer var expectedNumUnits int @@ -47,7 +47,7 @@ var _ = Describe("Init Action", func() { BeforeEach(func() { runner = v2mock.NewFakeRunner() memLog = &bytes.Buffer{} - logger = v2.NewBufferLogger(memLog) + logger = types.NewBufferLogger(memLog) logger.SetLevel(logrus.DebugLevel) fs, cleanup, _ = vfst.NewTestFS(map[string]interface{}{}) cfg = config.NewRunConfig( @@ -68,7 +68,7 @@ var _ = Describe("Init Action", func() { cleanup() }) Describe("Init System", Label("init"), func() { - var spec *v2.InitSpec + var spec *types.InitSpec var enabledUnits []string var errCmd, initrdFile string diff --git a/pkg/action/install.go b/pkg/action/install.go index a52a6493148..f0ad1054781 100644 --- a/pkg/action/install.go +++ b/pkg/action/install.go @@ -27,28 +27,28 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/elemental" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" "github.com/rancher/elemental-toolkit/v2/pkg/snapshotter" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) type InstallAction struct { - cfg *v2.RunConfig - spec *v2.InstallSpec - bootloader v2.Bootloader - snapshotter v2.Snapshotter - snapshot *v2.Snapshot + cfg *types.RunConfig + spec *types.InstallSpec + bootloader types.Bootloader + snapshotter types.Snapshotter + snapshot *types.Snapshot } type InstallActionOption func(i *InstallAction) error -func WithInstallBootloader(bootloader v2.Bootloader) func(i *InstallAction) error { +func WithInstallBootloader(bootloader types.Bootloader) func(i *InstallAction) error { return func(i *InstallAction) error { i.bootloader = bootloader return nil } } -func NewInstallAction(cfg *v2.RunConfig, spec *v2.InstallSpec, opts ...InstallActionOption) (*InstallAction, error) { +func NewInstallAction(cfg *types.RunConfig, spec *types.InstallSpec, opts ...InstallActionOption) (*InstallAction, error) { var err error i := &InstallAction{cfg: cfg, spec: spec} @@ -105,13 +105,13 @@ func (i *InstallAction) createInstallStateYaml() error { return fmt.Errorf("undefined installed snapshot") } - installState := &v2.InstallState{ + installState := &types.InstallState{ Date: time.Now().Format(time.RFC3339), Snapshotter: i.cfg.Snapshotter, - Partitions: map[string]*v2.PartitionState{ + Partitions: map[string]*types.PartitionState{ cnst.StatePartName: { FSLabel: i.spec.Partitions.State.FilesystemLabel, - Snapshots: map[int]*v2.SystemState{ + Snapshots: map[int]*types.SystemState{ i.snapshot.ID: { Source: i.spec.System, Digest: i.spec.System.GetDigest(), @@ -121,7 +121,7 @@ func (i *InstallAction) createInstallStateYaml() error { }, cnst.RecoveryPartName: { FSLabel: i.spec.Partitions.Recovery.FilesystemLabel, - RecoveryImage: &v2.SystemState{ + RecoveryImage: &types.SystemState{ Source: i.spec.RecoverySystem.Source, Digest: i.spec.RecoverySystem.Source.GetDigest(), Label: i.spec.RecoverySystem.Label, @@ -132,17 +132,17 @@ func (i *InstallAction) createInstallStateYaml() error { } if i.spec.Partitions.OEM != nil { - installState.Partitions[cnst.OEMPartName] = &v2.PartitionState{ + installState.Partitions[cnst.OEMPartName] = &types.PartitionState{ FSLabel: i.spec.Partitions.OEM.FilesystemLabel, } } if i.spec.Partitions.Persistent != nil { - installState.Partitions[cnst.PersistentPartName] = &v2.PartitionState{ + installState.Partitions[cnst.PersistentPartName] = &types.PartitionState{ FSLabel: i.spec.Partitions.Persistent.FilesystemLabel, } } if i.spec.Partitions.EFI != nil { - installState.Partitions[cnst.EfiPartName] = &v2.PartitionState{ + installState.Partitions[cnst.EfiPartName] = &types.PartitionState{ FSLabel: i.spec.Partitions.EFI.FilesystemLabel, } } diff --git a/pkg/action/install_test.go b/pkg/action/install_test.go index 9d158b14b55..618465e97b6 100644 --- a/pkg/action/install_test.go +++ b/pkg/action/install_test.go @@ -33,7 +33,7 @@ import ( conf "github.com/rancher/elemental-toolkit/v2/pkg/config" "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -43,10 +43,10 @@ const partTmpl = ` %d:%ss:%ss:2048s:ext4::type=83;` var _ = Describe("Install action tests", func() { - var config *v2.RunConfig + var config *types.RunConfig var runner *v2mock.FakeRunner var fs vfs.FS - var logger v2.Logger + var logger types.Logger var mounter *v2mock.FakeMounter var syscall *v2mock.FakeSyscall var client *v2mock.FakeHTTPClient @@ -63,8 +63,8 @@ var _ = Describe("Install action tests", func() { mounter = v2mock.NewFakeMounter() client = &v2mock.FakeHTTPClient{} memLog = &bytes.Buffer{} - logger = v2.NewBufferLogger(memLog) - logger.SetLevel(v2.DebugLevel()) + logger = types.NewBufferLogger(memLog) + logger.SetLevel(types.DebugLevel()) extractor = v2mock.NewFakeImageExtractor(logger) var err error fs, cleanup, err = vfst.NewTestFS(map[string]interface{}{}) @@ -92,7 +92,7 @@ var _ = Describe("Install action tests", func() { var device, cmdFail string var err error var cmdline func() ([]byte, error) - var spec *v2.InstallSpec + var spec *types.InstallSpec var installer *action.InstallAction BeforeEach(func() { @@ -150,13 +150,13 @@ var _ = Describe("Install action tests", func() { Expect(utils.MkdirAll(fs, constants.ISOBaseTree, constants.DirPerm)).To(Succeed()) spec = conf.NewInstallSpec(config.Config) - loopCfg, ok := config.Snapshotter.Config.(*v2.LoopDeviceConfig) + loopCfg, ok := config.Snapshotter.Config.(*types.LoopDeviceConfig) Expect(ok).To(BeTrue()) loopCfg.Size = 16 Expect(spec.System.Value()).To(Equal(constants.ISOBaseTree)) Expect(spec.System.IsDir()).To(BeTrue()) Expect(spec.RecoverySystem.Source.Value()).To(Equal(constants.ISOBaseTree)) - //spec.System = v2.NewDockerSrc("fake/image:tag") + //spec.System = types.NewDockerSrc("fake/image:tag") grubCfg := filepath.Join(constants.WorkingImgDir, constants.GrubCfgPath, constants.GrubCfg) Expect(utils.MkdirAll(fs, filepath.Dir(grubCfg), constants.DirPerm)).To(Succeed()) @@ -261,7 +261,7 @@ var _ = Describe("Install action tests", func() { It("Successfully installs a docker image", Label("docker"), func() { spec.Target = device - spec.System = v2.NewDockerSrc("my/image:latest") + spec.System = types.NewDockerSrc("my/image:latest") Expect(installer.Run()).To(BeNil()) }) diff --git a/pkg/action/mount.go b/pkg/action/mount.go index 14d34b3c4af..738877ff744 100644 --- a/pkg/action/mount.go +++ b/pkg/action/mount.go @@ -26,7 +26,7 @@ import ( "github.com/hashicorp/go-multierror" "github.com/rancher/elemental-toolkit/v2/pkg/constants" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -41,7 +41,7 @@ const diskByPartLabel = diskBy + "partlabel" const diskByUUID = diskBy + "uuid" const runPath = "/run" -func RunMount(cfg *v2.RunConfig, spec *v2.MountSpec) error { +func RunMount(cfg *types.RunConfig, spec *types.MountSpec) error { var fstabData string var err error @@ -85,10 +85,10 @@ func RunMount(cfg *v2.RunConfig, spec *v2.MountSpec) error { return nil } -func MountVolumes(cfg *v2.RunConfig, spec *v2.MountSpec) error { +func MountVolumes(cfg *types.RunConfig, spec *types.MountSpec) error { var errs error - volumes := map[string]*v2.VolumeMount{} + volumes := map[string]*types.VolumeMount{} keys := []string{} if spec.HasPersistent() { volumes[spec.Persistent.Volume.Mountpoint] = &spec.Persistent.Volume @@ -145,7 +145,7 @@ func MountVolumes(cfg *v2.RunConfig, spec *v2.MountSpec) error { return errs } -func MountEphemeral(cfg *v2.RunConfig, sysroot string, overlay v2.EphemeralMounts) error { +func MountEphemeral(cfg *types.RunConfig, sysroot string, overlay types.EphemeralMounts) error { if err := utils.MkdirAll(cfg.Config.Fs, constants.OverlayDir, constants.DirPerm); err != nil { cfg.Logger.Errorf("Error creating directory %s: %s", constants.OverlayDir, err.Error()) return err @@ -186,7 +186,7 @@ func MountEphemeral(cfg *v2.RunConfig, sysroot string, overlay v2.EphemeralMount return nil } -func MountPersistent(cfg *v2.RunConfig, spec *v2.MountSpec) error { +func MountPersistent(cfg *types.RunConfig, spec *types.MountSpec) error { mountFunc := MountOverlayPath if spec.Persistent.Mode == "bind" { mountFunc = MountBindPath @@ -210,9 +210,9 @@ func MountPersistent(cfg *v2.RunConfig, spec *v2.MountSpec) error { return nil } -type MountFunc func(cfg *v2.RunConfig, sysroot, overlayDir, path string) error +type MountFunc func(cfg *types.RunConfig, sysroot, overlayDir, path string) error -func MountBindPath(cfg *v2.RunConfig, sysroot, overlayDir, path string) error { +func MountBindPath(cfg *types.RunConfig, sysroot, overlayDir, path string) error { cfg.Logger.Debugf("Mounting bind path %s", path) base := filepath.Join(sysroot, path) @@ -243,7 +243,7 @@ func MountBindPath(cfg *v2.RunConfig, sysroot, overlayDir, path string) error { return nil } -func MountOverlayPath(cfg *v2.RunConfig, sysroot, overlayDir, path string) error { +func MountOverlayPath(cfg *types.RunConfig, sysroot, overlayDir, path string) error { cfg.Logger.Debugf("Mounting overlay path %s", path) lower := filepath.Join(sysroot, path) @@ -280,7 +280,7 @@ func MountOverlayPath(cfg *v2.RunConfig, sysroot, overlayDir, path string) error return nil } -func WriteFstab(cfg *v2.RunConfig, spec *v2.MountSpec, data string) error { +func WriteFstab(cfg *types.RunConfig, spec *types.MountSpec, data string) error { var errs error if !spec.WriteFstab { @@ -322,7 +322,7 @@ func WriteFstab(cfg *v2.RunConfig, spec *v2.MountSpec, data string) error { return cfg.Config.Fs.WriteFile(filepath.Join(spec.Sysroot, "/etc/fstab"), []byte(data), 0644) } -func InitialFstabData(runner v2.Runner, sysroot string) (string, error) { +func InitialFstabData(runner types.Runner, sysroot string) (string, error) { var data string mounts, err := findmnt(runner, "/") @@ -355,8 +355,8 @@ func fstab(device, path, fstype string, flags []string) string { return fmt.Sprintf("%s\t%s\t%s\t%s\t0\t0\n", device, path, fstype, strings.Join(flags, ",")) } -func findmnt(runner v2.Runner, mountpoint string) ([]*v2.VolumeMount, error) { - mounts := []*v2.VolumeMount{} +func findmnt(runner types.Runner, mountpoint string) ([]*types.VolumeMount, error) { + mounts := []*types.VolumeMount{} output, err := runner.Run("findmnt", "-Rrfno", "SOURCE,TARGET,FSTYPE,OPTIONS", mountpoint) if err != nil { return nil, err @@ -374,7 +374,7 @@ func findmnt(runner v2.Runner, mountpoint string) ([]*v2.VolumeMount, error) { lineFields[0] = match[1] } } - mounts = append(mounts, &v2.VolumeMount{ + mounts = append(mounts, &types.VolumeMount{ Device: lineFields[0], Mountpoint: lineFields[1], Options: strings.Split(lineFields[3], ","), diff --git a/pkg/action/mount_test.go b/pkg/action/mount_test.go index f3e357b8d97..fdd4d1b3fd1 100644 --- a/pkg/action/mount_test.go +++ b/pkg/action/mount_test.go @@ -31,24 +31,24 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/config" "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) var _ = Describe("Mount Action", func() { - var cfg *v2.RunConfig + var cfg *types.RunConfig var mounter *v2mock.FakeMounter var runner *v2mock.FakeRunner var fs vfs.FS - var logger v2.Logger + var logger types.Logger var cleanup func() var memLog *bytes.Buffer - var spec *v2.MountSpec + var spec *types.MountSpec BeforeEach(func() { mounter = v2mock.NewFakeMounter() memLog = &bytes.Buffer{} - logger = v2.NewBufferLogger(memLog) + logger = types.NewBufferLogger(memLog) runner = v2mock.NewFakeRunner() logger.SetLevel(logrus.DebugLevel) fs, cleanup, _ = vfst.NewTestFS(map[string]interface{}{}) @@ -72,22 +72,22 @@ var _ = Describe("Mount Action", func() { } } - spec = &v2.MountSpec{ + spec = &types.MountSpec{ Sysroot: "/sysroot", WriteFstab: true, - Ephemeral: v2.EphemeralMounts{ + Ephemeral: types.EphemeralMounts{ Type: "tmpfs", Size: "30%", }, - Persistent: v2.PersistentMounts{ + Persistent: types.PersistentMounts{ Mode: constants.BindMode, Paths: []string{"/some/path"}, - Volume: v2.VolumeMount{ + Volume: types.VolumeMount{ Mountpoint: constants.PersistentDir, Device: "/dev/persistentdev", }, }, - Volumes: []*v2.VolumeMount{ + Volumes: []*types.VolumeMount{ { Mountpoint: "/run/elemental", Device: "/dev/somedevice", @@ -147,9 +147,9 @@ var _ = Describe("Mount Action", func() { }) It("Does not write fstab if not requested", func() { - spec := &v2.MountSpec{ + spec := &types.MountSpec{ WriteFstab: false, - Ephemeral: v2.EphemeralMounts{ + Ephemeral: types.EphemeralMounts{ Size: "30%", }, } @@ -164,13 +164,13 @@ var _ = Describe("Mount Action", func() { Describe("Mount Volumes", func() { It("mounts expected volumes without errors", func() { spec.Volumes = append(spec.Volumes, - &v2.VolumeMount{ + &types.VolumeMount{ Device: "LABEL=TEST", Mountpoint: "/a/path", - }, &v2.VolumeMount{ + }, &types.VolumeMount{ Device: "PARTLABEL=partitionlabel", Mountpoint: "/a/different/path", - }, &v2.VolumeMount{ + }, &types.VolumeMount{ Device: "UUID=someuuidgoeshere", Mountpoint: "/a/path", }, @@ -191,7 +191,7 @@ var _ = Describe("Mount Action", func() { }) It("fails to understand a non supported device reference", func() { spec.Volumes = append(spec.Volumes, - &v2.VolumeMount{ + &types.VolumeMount{ Device: "ThisIsNotADevice", Mountpoint: "/a/path", }, diff --git a/pkg/action/reset.go b/pkg/action/reset.go index cf0e9ccab9d..29f9f36af0a 100644 --- a/pkg/action/reset.go +++ b/pkg/action/reset.go @@ -27,7 +27,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/elemental" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" "github.com/rancher/elemental-toolkit/v2/pkg/snapshotter" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -50,7 +50,7 @@ func (r *ResetAction) resetChrootHook(hook string, root string) error { type ResetActionOption func(r *ResetAction) error -func WithResetBootloader(bootloader v2.Bootloader) func(r *ResetAction) error { +func WithResetBootloader(bootloader types.Bootloader) func(r *ResetAction) error { return func(i *ResetAction) error { i.bootloader = bootloader return nil @@ -58,14 +58,14 @@ func WithResetBootloader(bootloader v2.Bootloader) func(r *ResetAction) error { } type ResetAction struct { - cfg *v2.RunConfig - spec *v2.ResetSpec - bootloader v2.Bootloader - snapshotter v2.Snapshotter - snapshot *v2.Snapshot + cfg *types.RunConfig + spec *types.ResetSpec + bootloader types.Bootloader + snapshotter types.Snapshotter + snapshot *types.Snapshot } -func NewResetAction(cfg *v2.RunConfig, spec *v2.ResetSpec, opts ...ResetActionOption) (*ResetAction, error) { +func NewResetAction(cfg *types.RunConfig, spec *types.ResetSpec, opts ...ResetActionOption) (*ResetAction, error) { var err error r := &ResetAction{cfg: cfg, spec: spec} @@ -122,13 +122,13 @@ func (r *ResetAction) updateInstallState(cleanup *utils.CleanStack) error { } } - installState := &v2.InstallState{ + installState := &types.InstallState{ Date: time.Now().Format(time.RFC3339), Snapshotter: r.cfg.Snapshotter, - Partitions: map[string]*v2.PartitionState{ + Partitions: map[string]*types.PartitionState{ constants.StatePartName: { FSLabel: r.spec.Partitions.State.FilesystemLabel, - Snapshots: map[int]*v2.SystemState{ + Snapshots: map[int]*types.SystemState{ r.snapshot.ID: { Source: src, Digest: src.GetDigest(), @@ -139,12 +139,12 @@ func (r *ResetAction) updateInstallState(cleanup *utils.CleanStack) error { }, } if r.spec.Partitions.OEM != nil { - installState.Partitions[constants.OEMPartName] = &v2.PartitionState{ + installState.Partitions[constants.OEMPartName] = &types.PartitionState{ FSLabel: r.spec.Partitions.OEM.FilesystemLabel, } } if r.spec.Partitions.Persistent != nil { - installState.Partitions[constants.PersistentPartName] = &v2.PartitionState{ + installState.Partitions[constants.PersistentPartName] = &types.PartitionState{ FSLabel: r.spec.Partitions.Persistent.FilesystemLabel, } } diff --git a/pkg/action/reset_test.go b/pkg/action/reset_test.go index 27c0381b4a5..0b6e22ade24 100644 --- a/pkg/action/reset_test.go +++ b/pkg/action/reset_test.go @@ -31,15 +31,15 @@ import ( conf "github.com/rancher/elemental-toolkit/v2/pkg/config" "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) var _ = Describe("Reset action tests", func() { - var config *v2.RunConfig + var config *types.RunConfig var runner *v2mock.FakeRunner var fs vfs.FS - var logger v2.Logger + var logger types.Logger var mounter *v2mock.FakeMounter var syscall *v2mock.FakeSyscall var client *v2mock.FakeHTTPClient @@ -56,7 +56,7 @@ var _ = Describe("Reset action tests", func() { mounter = v2mock.NewFakeMounter() client = &v2mock.FakeHTTPClient{} memLog = &bytes.Buffer{} - logger = v2.NewBufferLogger(memLog) + logger = types.NewBufferLogger(memLog) extractor = v2mock.NewFakeImageExtractor(logger) var err error fs, cleanup, err = vfst.NewTestFS(map[string]interface{}{}) @@ -78,7 +78,7 @@ var _ = Describe("Reset action tests", func() { AfterEach(func() { cleanup() }) Describe("Reset Action", Label("reset"), func() { - var spec *v2.ResetSpec + var spec *types.ResetSpec var reset *action.ResetAction var cmdFail, bootedFrom string var err error @@ -144,7 +144,7 @@ var _ = Describe("Reset action tests", func() { Expect(err).ShouldNot(HaveOccurred()) Expect(spec.System.IsEmpty()).To(BeFalse()) - loopCfg, ok := config.Snapshotter.Config.(*v2.LoopDeviceConfig) + loopCfg, ok := config.Snapshotter.Config.(*types.LoopDeviceConfig) Expect(ok).To(BeTrue()) loopCfg.Size = 16 @@ -177,7 +177,7 @@ var _ = Describe("Reset action tests", func() { It("Successfully resets from a squashfs recovery image", Label("channel"), func() { err := utils.MkdirAll(config.Fs, constants.ISOBaseTree, constants.DirPerm) Expect(err).ShouldNot(HaveOccurred()) - spec.System = v2.NewDirSrc(constants.ISOBaseTree) + spec.System = types.NewDirSrc(constants.ISOBaseTree) Expect(reset.Run()).To(BeNil()) }) It("Successfully resets despite having errors on hooks", func() { @@ -185,7 +185,7 @@ var _ = Describe("Reset action tests", func() { Expect(reset.Run()).To(BeNil()) }) It("Successfully resets from a docker image", Label("docker"), func() { - spec.System = v2.NewDockerSrc("my/image:latest") + spec.System = types.NewDockerSrc("my/image:latest") Expect(reset.Run()).To(BeNil()) }) It("Successfully resets from a channel package", Label("channel"), func() { diff --git a/pkg/action/upgrade.go b/pkg/action/upgrade.go index e493752a52c..4e7b47affa7 100644 --- a/pkg/action/upgrade.go +++ b/pkg/action/upgrade.go @@ -27,29 +27,29 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/elemental" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" "github.com/rancher/elemental-toolkit/v2/pkg/snapshotter" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) // UpgradeAction represents the struct that will run the upgrade from start to finish type UpgradeAction struct { - cfg *v2.RunConfig - spec *v2.UpgradeSpec - bootloader v2.Bootloader - snapshotter v2.Snapshotter - snapshot *v2.Snapshot + cfg *types.RunConfig + spec *types.UpgradeSpec + bootloader types.Bootloader + snapshotter types.Snapshotter + snapshot *types.Snapshot } type UpgradeActionOption func(r *UpgradeAction) error -func WithUpgradeBootloader(bootloader v2.Bootloader) func(u *UpgradeAction) error { +func WithUpgradeBootloader(bootloader types.Bootloader) func(u *UpgradeAction) error { return func(u *UpgradeAction) error { u.bootloader = bootloader return nil } } -func NewUpgradeAction(config *v2.RunConfig, spec *v2.UpgradeSpec, opts ...UpgradeActionOption) (*UpgradeAction, error) { +func NewUpgradeAction(config *types.RunConfig, spec *types.UpgradeSpec, opts ...UpgradeActionOption) (*UpgradeAction, error) { var err error u := &UpgradeAction{cfg: config, spec: spec} @@ -137,8 +137,8 @@ func (u *UpgradeAction) upgradeInstallStateYaml() error { } if u.spec.State == nil { - u.spec.State = &v2.InstallState{ - Partitions: map[string]*v2.PartitionState{}, + u.spec.State = &types.InstallState{ + Partitions: map[string]*types.PartitionState{}, } } @@ -147,14 +147,14 @@ func (u *UpgradeAction) upgradeInstallStateYaml() error { statePart := u.spec.State.Partitions[constants.StatePartName] if statePart == nil { - statePart = &v2.PartitionState{ + statePart = &types.PartitionState{ FSLabel: u.spec.Partitions.State.FilesystemLabel, - Snapshots: map[int]*v2.SystemState{}, + Snapshots: map[int]*types.SystemState{}, } } if statePart.Snapshots == nil { - statePart.Snapshots = map[int]*v2.SystemState{} + statePart.Snapshots = map[int]*types.SystemState{} } for id, state := range statePart.Snapshots { @@ -166,7 +166,7 @@ func (u *UpgradeAction) upgradeInstallStateYaml() error { } } - statePart.Snapshots[u.snapshot.ID] = &v2.SystemState{ + statePart.Snapshots[u.snapshot.ID] = &types.SystemState{ Source: u.spec.System, Digest: u.spec.System.GetDigest(), Active: true, @@ -185,9 +185,9 @@ func (u *UpgradeAction) upgradeInstallStateYaml() error { if u.spec.RecoveryUpgrade { recoveryPart := u.spec.State.Partitions[constants.RecoveryPartName] if recoveryPart == nil { - recoveryPart = &v2.PartitionState{ + recoveryPart = &types.PartitionState{ FSLabel: u.spec.Partitions.Recovery.FilesystemLabel, - RecoveryImage: &v2.SystemState{ + RecoveryImage: &types.SystemState{ FS: u.spec.RecoverySystem.FS, Label: u.spec.RecoverySystem.Label, Source: u.spec.RecoverySystem.Source, diff --git a/pkg/action/upgrade_test.go b/pkg/action/upgrade_test.go index 60632b9e03b..930b3c4c27c 100644 --- a/pkg/action/upgrade_test.go +++ b/pkg/action/upgrade_test.go @@ -32,15 +32,15 @@ import ( conf "github.com/rancher/elemental-toolkit/v2/pkg/config" "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) var _ = Describe("Runtime Actions", func() { - var config *v2.RunConfig + var config *types.RunConfig var runner *v2mock.FakeRunner var fs vfs.FS - var logger v2.Logger + var logger types.Logger var mounter *v2mock.FakeMounter var syscall *v2mock.FakeSyscall var client *v2mock.FakeHTTPClient @@ -57,7 +57,7 @@ var _ = Describe("Runtime Actions", func() { mounter = v2mock.NewFakeMounter() client = &v2mock.FakeHTTPClient{} memLog = &bytes.Buffer{} - logger = v2.NewBufferLogger(memLog) + logger = types.NewBufferLogger(memLog) bootloader = &v2mock.FakeBootloader{} extractor = v2mock.NewFakeImageExtractor(logger) var err error @@ -81,13 +81,13 @@ var _ = Describe("Runtime Actions", func() { AfterEach(func() { cleanup() }) Describe("Upgrade Action", Label("upgrade"), func() { - var spec *v2.UpgradeSpec + var spec *types.UpgradeSpec var upgrade *action.UpgradeAction var memLog *bytes.Buffer BeforeEach(func() { memLog = &bytes.Buffer{} - logger = v2.NewBufferLogger(memLog) + logger = types.NewBufferLogger(memLog) config.Logger = logger logger.SetLevel(logrus.DebugLevel) @@ -139,8 +139,8 @@ var _ = Describe("Runtime Actions", func() { spec, err = conf.NewUpgradeSpec(config.Config) Expect(err).ShouldNot(HaveOccurred()) - spec.System = v2.NewDockerSrc("alpine") - loopCfg, ok := config.Snapshotter.Config.(*v2.LoopDeviceConfig) + spec.System = types.NewDockerSrc("alpine") + loopCfg, ok := config.Snapshotter.Config.(*types.LoopDeviceConfig) Expect(ok).To(BeTrue()) loopCfg.Size = 16 @@ -188,18 +188,18 @@ var _ = Describe("Runtime Actions", func() { Expect(v2mock.FakeLoopDeviceSnapshotsStatus(fs, constants.RunningStateDir, 2)).To(Succeed()) // Create installState with previous install state statePath := filepath.Join(constants.RunningStateDir, constants.InstallStateFile) - installState := &v2.InstallState{ - Partitions: map[string]*v2.PartitionState{ + installState := &types.InstallState{ + Partitions: map[string]*types.PartitionState{ constants.StatePartName: { FSLabel: "COS_STATE", - Snapshots: map[int]*v2.SystemState{ + Snapshots: map[int]*types.SystemState{ 2: { - Source: v2.NewDockerSrc("some/image:v2"), + Source: types.NewDockerSrc("some/image:v2"), Digest: "somehash2", Active: true, }, 1: { - Source: v2.NewDockerSrc("some/image:v1"), + Source: types.NewDockerSrc("some/image:v1"), Digest: "somehash", }, }, @@ -215,7 +215,7 @@ var _ = Describe("Runtime Actions", func() { // Create a new spec to load state yaml spec, err = conf.NewUpgradeSpec(config.Config) - spec.System = v2.NewDockerSrc("alpine") + spec.System = types.NewDockerSrc("alpine") upgrade, err = action.NewUpgradeAction(config, spec) Expect(err).NotTo(HaveOccurred()) err := upgrade.Run() @@ -257,7 +257,7 @@ var _ = Describe("Runtime Actions", func() { }) It("Successfully reboots after upgrade from docker image", func() { Expect(v2mock.FakeLoopDeviceSnapshotsStatus(fs, constants.RunningStateDir, 1)).To(Succeed()) - spec.System = v2.NewDockerSrc("alpine") + spec.System = types.NewDockerSrc("alpine") config.Reboot = true upgrade, err = action.NewUpgradeAction(config, spec) Expect(err).NotTo(HaveOccurred()) @@ -276,7 +276,7 @@ var _ = Describe("Runtime Actions", func() { }) It("Successfully powers off after upgrade from docker image", func() { Expect(v2mock.FakeLoopDeviceSnapshotsStatus(fs, constants.RunningStateDir, 1)).To(Succeed()) - spec.System = v2.NewDockerSrc("alpine") + spec.System = types.NewDockerSrc("alpine") config.PowerOff = true upgrade, err = action.NewUpgradeAction(config, spec) Expect(err).NotTo(HaveOccurred()) diff --git a/pkg/bootloader/grub.go b/pkg/bootloader/grub.go index 051464db4d5..ba0a0a6eaa2 100644 --- a/pkg/bootloader/grub.go +++ b/pkg/bootloader/grub.go @@ -23,7 +23,7 @@ import ( "regexp" "github.com/rancher/elemental-toolkit/v2/pkg/constants" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" efilib "github.com/canonical/go-efilib" @@ -48,10 +48,10 @@ func getGModulePatterns(module string) []string { } type Grub struct { - logger v2.Logger - fs v2.FS - runner v2.Runner - platform *v2.Platform + logger types.Logger + fs types.FS + runner types.Runner + platform *types.Platform shimImg string grubEfiImg string @@ -66,11 +66,11 @@ type Grub struct { secureBoot bool } -var _ v2.Bootloader = (*Grub)(nil) +var _ types.Bootloader = (*Grub)(nil) type GrubOptions func(g *Grub) error -func NewGrub(cfg *v2.Config, opts ...GrubOptions) *Grub { +func NewGrub(cfg *types.Config, opts ...GrubOptions) *Grub { secureBoot := true if cfg.Platform.Arch == constants.ArchRiscV64 { // There is no secure boot for riscv64 for the time being (Dec 2023) diff --git a/pkg/bootloader/grub_test.go b/pkg/bootloader/grub_test.go index 418ef242bc5..31ccc5e2f64 100644 --- a/pkg/bootloader/grub_test.go +++ b/pkg/bootloader/grub_test.go @@ -31,27 +31,27 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" eleefi "github.com/rancher/elemental-toolkit/v2/pkg/efi" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" "github.com/twpayne/go-vfs/v4" "github.com/twpayne/go-vfs/v4/vfst" ) var _ = Describe("Booloader", Label("bootloader", "grub"), func() { - var logger v2.Logger + var logger types.Logger var fs vfs.FS var runner *v2mock.FakeRunner var cleanup func() var err error var grub *bootloader.Grub - var cfg *v2.Config + var cfg *types.Config var rootDir, efiDir string var grubCfg, osRelease []byte var efivars eleefi.Variables var relativeTo string BeforeEach(func() { - logger = v2.NewNullLogger() + logger = types.NewNullLogger() fs, cleanup, err = vfst.NewTestFS(map[string]interface{}{}) Expect(err).Should(BeNil()) runner = v2mock.NewFakeRunner() diff --git a/pkg/cloudinit/cloudinit.go b/pkg/cloudinit/cloudinit.go index a0a79f1182c..3614c3721fd 100644 --- a/pkg/cloudinit/cloudinit.go +++ b/pkg/cloudinit/cloudinit.go @@ -28,7 +28,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" "github.com/rancher/elemental-toolkit/v2/pkg/utils" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) type YipCloudInitRunner struct { @@ -39,7 +39,7 @@ type YipCloudInitRunner struct { // NewYipCloudInitRunner returns a default yip cloud init executor with the Elemental plugin set. // It accepts a logger which is used inside the runner. -func NewYipCloudInitRunner(l v2.Logger, r v2.Runner, fs vfs.FS) *YipCloudInitRunner { +func NewYipCloudInitRunner(l types.Logger, r types.Runner, fs vfs.FS) *YipCloudInitRunner { y := &YipCloudInitRunner{ fs: fs, console: newCloudInitConsole(l, r), } diff --git a/pkg/cloudinit/cloudinit_test.go b/pkg/cloudinit/cloudinit_test.go index cc860f8ebac..737bcc52d28 100644 --- a/pkg/cloudinit/cloudinit_test.go +++ b/pkg/cloudinit/cloudinit_test.go @@ -33,7 +33,7 @@ import ( . "github.com/rancher/elemental-toolkit/v2/pkg/cloudinit" "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" . "github.com/onsi/ginkgo/v2" @@ -50,12 +50,12 @@ const printOutput = `BYT; var _ = Describe("CloudRunner", Label("CloudRunner", "types", "cloud-init"), func() { // unit test stolen from yip Describe("loading yaml files", func() { - var logger v2.Logger + var logger types.Logger var buffer *bytes.Buffer BeforeEach(func() { buffer = bytes.NewBuffer([]byte{}) - logger = v2.NewBufferLogger(buffer) - logger.SetLevel(v2.DebugLevel()) + logger = types.NewBufferLogger(buffer) + logger.SetLevel(types.DebugLevel()) }) It("executes commands", func() { @@ -91,7 +91,7 @@ stages: err = fs2.WriteFile("/tmp/test/bar", []byte(`boo`), os.ModePerm) Expect(err).Should(BeNil()) - runner := NewYipCloudInitRunner(logger, &v2.RealRunner{}, fs) + runner := NewYipCloudInitRunner(logger, &types.RealRunner{}, fs) err = runner.Run("test", "/some/yip") Expect(err).Should(BeNil()) @@ -108,17 +108,17 @@ stages: }) Describe("writing yaml files", func() { var fs *vfst.TestFS - var logger v2.Logger + var logger types.Logger var cleanup func() var err error var yipRunner *YipCloudInitRunner var tempDir string BeforeEach(func() { - logger = v2.NewNullLogger() + logger = types.NewNullLogger() fs, cleanup, err = vfst.NewTestFS(map[string]interface{}{}) Expect(err).Should(BeNil()) - yipRunner = NewYipCloudInitRunner(logger, &v2.RealRunner{}, fs) + yipRunner = NewYipCloudInitRunner(logger, &types.RealRunner{}, fs) tempDir = fs.TempDir() }) @@ -163,7 +163,7 @@ stages: } Expect(utils.MkdirAll(fs, "/output", constants.DirPerm)).To(Succeed()) roFS := vfs.NewReadOnlyFS(fs) - yipRunner = NewYipCloudInitRunner(logger, &v2.RealRunner{}, roFS) + yipRunner = NewYipCloudInitRunner(logger, &types.RealRunner{}, roFS) Expect(yipRunner.CloudInitFileRender("/conf/exmaple.yaml", conf)).NotTo(Succeed()) }) }) @@ -173,7 +173,7 @@ stages: var device, cmdFail string var partNum int var cleanup func() - logger := v2.NewNullLogger() + logger := types.NewNullLogger() BeforeEach(func() { afs, cleanup, _ = vfst.NewTestFS(nil) err := utils.MkdirAll(afs, "/some/yip", constants.DirPerm) diff --git a/pkg/cloudinit/console.go b/pkg/cloudinit/console.go index bdb8bc87445..643501223ad 100644 --- a/pkg/cloudinit/console.go +++ b/pkg/cloudinit/console.go @@ -22,28 +22,28 @@ import ( "github.com/hashicorp/go-multierror" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) // cloudInitConsole represents a yip's Console implementations using -// the elemental v2.Runner interface. +// the elemental types.Runner interface. type cloudInitConsole struct { - runner v2.Runner - logger v2.Logger + runner types.Runner + logger types.Logger } // newCloudInitConsole returns an instance of the cloudInitConsole based on the -// given v2.Runner and v2.Logger. -func newCloudInitConsole(l v2.Logger, r v2.Runner) *cloudInitConsole { +// given types.Runner and types.Logger. +func newCloudInitConsole(l types.Logger, r types.Runner) *cloudInitConsole { return &cloudInitConsole{logger: l, runner: r} } // getRunner returns the internal runner used within this Console -func (c cloudInitConsole) getRunner() v2.Runner { +func (c cloudInitConsole) getRunner() types.Runner { return c.runner } -// Run runs a command using the v2.Runner internal instance +// Run runs a command using the types.Runner internal instance func (c cloudInitConsole) Run(command string, opts ...func(cmd *exec.Cmd)) (string, error) { c.logger.Debugf("running command `%s`", command) cmd := c.runner.InitCmd("sh", "-c", command) @@ -58,7 +58,7 @@ func (c cloudInitConsole) Run(command string, opts ...func(cmd *exec.Cmd)) (stri return string(out), err } -// Start runs a non blocking command using the v2.Runner internal instance +// Start runs a non blocking command using the types.Runner internal instance func (c cloudInitConsole) Start(cmd *exec.Cmd, opts ...func(cmd *exec.Cmd)) error { c.logger.Debugf("running command `%s`", cmd) for _, o := range opts { @@ -67,7 +67,7 @@ func (c cloudInitConsole) Start(cmd *exec.Cmd, opts ...func(cmd *exec.Cmd)) erro return cmd.Run() } -// RunTemplate runs a sequence of non-blocking templated commands using the v2.Runner internal instance +// RunTemplate runs a sequence of non-blocking templated commands using the types.Runner internal instance func (c cloudInitConsole) RunTemplate(st []string, template string) error { var errs error diff --git a/pkg/cloudinit/layout_plugin.go b/pkg/cloudinit/layout_plugin.go index 89c565764a8..9de7fb62525 100644 --- a/pkg/cloudinit/layout_plugin.go +++ b/pkg/cloudinit/layout_plugin.go @@ -29,7 +29,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" "github.com/rancher/elemental-toolkit/v2/pkg/partitioner" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -46,9 +46,9 @@ func layoutPlugin(l logger.Interface, s schema.Stage, fs vfs.FS, console plugins return errors.New("provided console is not an instance of 'cloudInitConsole' type") } runner := elemConsole.getRunner() - log, ok := l.(v2.Logger) + log, ok := l.(types.Logger) if !ok { - return errors.New("provided logger is not implementing v2.Logger interface") + return errors.New("provided logger is not implementing types.Logger interface") } if len(strings.TrimSpace(s.Layout.Device.Label)) > 0 { diff --git a/pkg/config/config.go b/pkg/config/config.go index aac25075ffb..a61d7fd0ee4 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -28,7 +28,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" "github.com/rancher/elemental-toolkit/v2/pkg/features" "github.com/rancher/elemental-toolkit/v2/pkg/http" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -37,92 +37,92 @@ const ( mountSuffix = ".mount" ) -type GenericOptions func(a *v2.Config) error +type GenericOptions func(a *types.Config) error -func WithFs(fs v2.FS) func(r *v2.Config) error { - return func(r *v2.Config) error { +func WithFs(fs types.FS) func(r *types.Config) error { + return func(r *types.Config) error { r.Fs = fs return nil } } -func WithLogger(logger v2.Logger) func(r *v2.Config) error { - return func(r *v2.Config) error { +func WithLogger(logger types.Logger) func(r *types.Config) error { + return func(r *types.Config) error { r.Logger = logger return nil } } -func WithSyscall(syscall v2.SyscallInterface) func(r *v2.Config) error { - return func(r *v2.Config) error { +func WithSyscall(syscall types.SyscallInterface) func(r *types.Config) error { + return func(r *types.Config) error { r.Syscall = syscall return nil } } -func WithMounter(mounter v2.Mounter) func(r *v2.Config) error { - return func(r *v2.Config) error { +func WithMounter(mounter types.Mounter) func(r *types.Config) error { + return func(r *types.Config) error { r.Mounter = mounter return nil } } -func WithRunner(runner v2.Runner) func(r *v2.Config) error { - return func(r *v2.Config) error { +func WithRunner(runner types.Runner) func(r *types.Config) error { + return func(r *types.Config) error { r.Runner = runner return nil } } -func WithClient(client v2.HTTPClient) func(r *v2.Config) error { - return func(r *v2.Config) error { +func WithClient(client types.HTTPClient) func(r *types.Config) error { + return func(r *types.Config) error { r.Client = client return nil } } -func WithCloudInitRunner(ci v2.CloudInitRunner) func(r *v2.Config) error { - return func(r *v2.Config) error { +func WithCloudInitRunner(ci types.CloudInitRunner) func(r *types.Config) error { + return func(r *types.Config) error { r.CloudInitRunner = ci return nil } } -func WithPlatform(platform string) func(r *v2.Config) error { - return func(r *v2.Config) error { - p, err := v2.ParsePlatform(platform) +func WithPlatform(platform string) func(r *types.Config) error { + return func(r *types.Config) error { + p, err := types.ParsePlatform(platform) r.Platform = p return err } } -func WithOCIImageExtractor() func(r *v2.Config) error { - return func(r *v2.Config) error { - r.ImageExtractor = v2.OCIImageExtractor{} +func WithOCIImageExtractor() func(r *types.Config) error { + return func(r *types.Config) error { + r.ImageExtractor = types.OCIImageExtractor{} return nil } } -func WithImageExtractor(extractor v2.ImageExtractor) func(r *v2.Config) error { - return func(r *v2.Config) error { +func WithImageExtractor(extractor types.ImageExtractor) func(r *types.Config) error { + return func(r *types.Config) error { r.ImageExtractor = extractor return nil } } -func NewConfig(opts ...GenericOptions) *v2.Config { - log := v2.NewLogger() +func NewConfig(opts ...GenericOptions) *types.Config { + log := types.NewLogger() - defaultPlatform, err := v2.NewPlatformFromArch(runtime.GOARCH) + defaultPlatform, err := types.NewPlatformFromArch(runtime.GOARCH) if err != nil { log.Errorf("error parsing default platform (%s): %s", runtime.GOARCH, err.Error()) return nil } - c := &v2.Config{ + c := &types.Config{ Fs: vfs.OSFS, Logger: log, - Syscall: &v2.RealSyscall{}, + Syscall: &types.RealSyscall{}, Client: http.NewClient(), Platform: defaultPlatform, SquashFsCompressionConfig: constants.GetDefaultSquashfsCompressionOptions(), @@ -137,7 +137,7 @@ func NewConfig(opts ...GenericOptions) *v2.Config { // delay runner creation after we have run over the options in case we use WithRunner if c.Runner == nil { - c.Runner = &v2.RealRunner{Logger: c.Logger} + c.Runner = &types.RealRunner{Logger: c.Logger} } // Now check if the runner has a logger inside, otherwise point our logger into it @@ -154,16 +154,16 @@ func NewConfig(opts ...GenericOptions) *v2.Config { } if c.Mounter == nil { - c.Mounter = v2.NewMounter(constants.MountBinary) + c.Mounter = types.NewMounter(constants.MountBinary) } return c } -func NewRunConfig(opts ...GenericOptions) *v2.RunConfig { +func NewRunConfig(opts ...GenericOptions) *types.RunConfig { config := NewConfig(opts...) - snapshotter := v1.NewLoopDevice() + snapshotter := types.NewLoopDevice() // Load snapshotter setup from state.yaml for reset and upgrade installState, _ := config.LoadInstallState() @@ -171,7 +171,7 @@ func NewRunConfig(opts ...GenericOptions) *v2.RunConfig { snapshotter = installState.Snapshotter } - r := &v2.RunConfig{ + r := &types.RunConfig{ Snapshotter: snapshotter, Config: *config, } @@ -179,17 +179,17 @@ func NewRunConfig(opts ...GenericOptions) *v2.RunConfig { } // NewInstallSpec returns an InstallSpec struct all based on defaults and basic host checks (e.g. EFI vs BIOS) -func NewInstallSpec(cfg v2.Config) *v2.InstallSpec { - var system *v2.ImageSource - var recoverySystem v2.Image +func NewInstallSpec(cfg types.Config) *types.InstallSpec { + var system *types.ImageSource + var recoverySystem types.Image // Check the default ISO installation media is available isoRootExists, _ := utils.Exists(cfg.Fs, constants.ISOBaseTree) if isoRootExists { - system = v2.NewDirSrc(constants.ISOBaseTree) + system = types.NewDirSrc(constants.ISOBaseTree) } else { - system = v2.NewEmptySrc() + system = types.NewEmptySrc() } recoverySystem.Source = system @@ -198,9 +198,9 @@ func NewInstallSpec(cfg v2.Config) *v2.InstallSpec { recoverySystem.File = filepath.Join(constants.RecoveryDir, constants.RecoveryImgFile) recoverySystem.MountPoint = constants.TransitionDir - return &v2.InstallSpec{ - Firmware: v2.EFI, - PartTable: v2.GPT, + return &types.InstallSpec{ + Firmware: types.EFI, + PartTable: types.GPT, Partitions: NewInstallElementalPartitions(), System: system, RecoverySystem: recoverySystem, @@ -208,19 +208,19 @@ func NewInstallSpec(cfg v2.Config) *v2.InstallSpec { } // NewInitSpec returns an InitSpec struct all based on defaults -func NewInitSpec() *v2.InitSpec { - return &v2.InitSpec{ +func NewInitSpec() *types.InitSpec { + return &types.InitSpec{ Mkinitrd: true, Force: false, Features: features.All, } } -func NewMountSpec() *v2.MountSpec { - return &v2.MountSpec{ +func NewMountSpec() *types.MountSpec { + return &types.MountSpec{ Sysroot: "/sysroot", WriteFstab: true, - Volumes: []*v2.VolumeMount{ + Volumes: []*types.VolumeMount{ { Mountpoint: constants.OEMPath, Device: fmt.Sprintf("PARTLABEL=%s", constants.OEMPartName), @@ -231,15 +231,15 @@ func NewMountSpec() *v2.MountSpec { Options: []string{"ro", "defaults"}, }, }, - Ephemeral: v2.EphemeralMounts{ + Ephemeral: types.EphemeralMounts{ Type: constants.Tmpfs, Size: "25%", Paths: []string{"/var", "/etc", "/srv"}, }, - Persistent: v2.PersistentMounts{ + Persistent: types.PersistentMounts{ Mode: constants.OverlayMode, Paths: []string{"/etc/systemd", "/etc/ssh", "/home", "/opt", "/root", "/var/log"}, - Volume: v2.VolumeMount{ + Volume: types.VolumeMount{ Mountpoint: constants.PersistentDir, Device: fmt.Sprintf("PARTLABEL=%s", constants.PersistentPartName), Options: []string{"rw", "defaults"}, @@ -248,9 +248,9 @@ func NewMountSpec() *v2.MountSpec { } } -func NewInstallElementalPartitions() v2.ElementalPartitions { - partitions := v2.ElementalPartitions{} - partitions.OEM = &v2.Partition{ +func NewInstallElementalPartitions() types.ElementalPartitions { + partitions := types.ElementalPartitions{} + partitions.OEM = &types.Partition{ FilesystemLabel: constants.OEMLabel, Size: constants.OEMSize, Name: constants.OEMPartName, @@ -259,7 +259,7 @@ func NewInstallElementalPartitions() v2.ElementalPartitions { Flags: []string{}, } - partitions.Recovery = &v2.Partition{ + partitions.Recovery = &types.Partition{ FilesystemLabel: constants.RecoveryLabel, Size: constants.RecoverySize, Name: constants.RecoveryPartName, @@ -268,7 +268,7 @@ func NewInstallElementalPartitions() v2.ElementalPartitions { Flags: []string{}, } - partitions.State = &v2.Partition{ + partitions.State = &types.Partition{ FilesystemLabel: constants.StateLabel, Size: constants.StateSize, Name: constants.StatePartName, @@ -277,7 +277,7 @@ func NewInstallElementalPartitions() v2.ElementalPartitions { Flags: []string{}, } - partitions.Persistent = &v2.Partition{ + partitions.Persistent = &types.Partition{ FilesystemLabel: constants.PersistentLabel, Size: constants.PersistentSize, Name: constants.PersistentPartName, @@ -286,15 +286,15 @@ func NewInstallElementalPartitions() v2.ElementalPartitions { Flags: []string{}, } - _ = partitions.SetFirmwarePartitions(v2.EFI, v2.GPT) + _ = partitions.SetFirmwarePartitions(types.EFI, types.GPT) return partitions } // getRecoveryState returns recovery state from a given install state. It // returns default values for any missing field. -func getRecoveryState(state *v2.InstallState) (recovery *v2.SystemState) { - recovery = &v2.SystemState{ +func getRecoveryState(state *types.InstallState) (recovery *types.SystemState) { + recovery = &types.SystemState{ FS: constants.SquashFs, Label: constants.SystemLabel, } @@ -312,9 +312,9 @@ func getRecoveryState(state *v2.InstallState) (recovery *v2.SystemState) { } // NewUpgradeSpec returns an UpgradeSpec struct all based on defaults and current host state -func NewUpgradeSpec(cfg v2.Config) (*v2.UpgradeSpec, error) { - var rState *v2.SystemState - var recovery v2.Image +func NewUpgradeSpec(cfg types.Config) (*types.UpgradeSpec, error) { + var rState *types.SystemState + var recovery types.Image installState, err := cfg.LoadInstallState() if err != nil { @@ -327,20 +327,20 @@ func NewUpgradeSpec(cfg v2.Config) (*v2.UpgradeSpec, error) { if err != nil { return nil, fmt.Errorf("could not read host partitions") } - ep := v2.NewElementalPartitionsFromList(parts, installState) + ep := types.NewElementalPartitionsFromList(parts, installState) if ep.Recovery != nil { if ep.Recovery.MountPoint == "" { ep.Recovery.MountPoint = constants.RecoveryDir } - recovery = v2.Image{ + recovery = types.Image{ File: filepath.Join(ep.Recovery.MountPoint, constants.TransitionImgFile), Size: constants.ImgSize, Label: rState.Label, FS: rState.FS, MountPoint: constants.TransitionDir, - Source: v2.NewEmptySrc(), + Source: types.NewEmptySrc(), } } @@ -365,8 +365,8 @@ func NewUpgradeSpec(cfg v2.Config) (*v2.UpgradeSpec, error) { } } - return &v2.UpgradeSpec{ - System: v2.NewEmptySrc(), + return &types.UpgradeSpec{ + System: types.NewEmptySrc(), RecoverySystem: recovery, Partitions: ep, State: installState, @@ -374,8 +374,8 @@ func NewUpgradeSpec(cfg v2.Config) (*v2.UpgradeSpec, error) { } // NewResetSpec returns a ResetSpec struct all based on defaults and current host state -func NewResetSpec(cfg v2.Config) (*v2.ResetSpec, error) { - var imgSource *v2.ImageSource +func NewResetSpec(cfg types.Config) (*types.ResetSpec, error) { + var imgSource *types.ImageSource if !utils.BootedFrom(cfg.Runner, constants.RecoveryImgName) { return nil, fmt.Errorf("reset can only be called from the recovery system") @@ -392,7 +392,7 @@ func NewResetSpec(cfg v2.Config) (*v2.ResetSpec, error) { if err != nil { return nil, fmt.Errorf("could not read host partitions") } - ep := v2.NewElementalPartitionsFromList(parts, installState) + ep := types.NewElementalPartitionsFromList(parts, installState) if efiExists { if ep.EFI == nil { @@ -444,12 +444,12 @@ func NewResetSpec(cfg v2.Config) (*v2.ResetSpec, error) { recoveryImg := filepath.Join(constants.RunningStateDir, constants.RecoveryImgFile) if exists, _ := utils.Exists(cfg.Fs, recoveryImg); exists { - imgSource = v2.NewFileSrc(recoveryImg) + imgSource = types.NewFileSrc(recoveryImg) } else { - imgSource = v2.NewEmptySrc() + imgSource = types.NewEmptySrc() } - return &v2.ResetSpec{ + return &types.ResetSpec{ Target: target, Partitions: ep, Efi: efiExists, @@ -459,14 +459,14 @@ func NewResetSpec(cfg v2.Config) (*v2.ResetSpec, error) { }, nil } -func NewDiskElementalPartitions(workdir string) v2.ElementalPartitions { - partitions := v2.ElementalPartitions{} +func NewDiskElementalPartitions(workdir string) types.ElementalPartitions { + partitions := types.ElementalPartitions{} - // does not return error on v2.EFI use case - _ = partitions.SetFirmwarePartitions(v2.EFI, v2.GPT) + // does not return error on types.EFI use case + _ = partitions.SetFirmwarePartitions(types.EFI, types.GPT) partitions.EFI.Path = filepath.Join(workdir, constants.EfiPartName+partSuffix) - partitions.OEM = &v2.Partition{ + partitions.OEM = &types.Partition{ FilesystemLabel: constants.OEMLabel, Size: constants.OEMSize, Name: constants.OEMPartName, @@ -476,7 +476,7 @@ func NewDiskElementalPartitions(workdir string) v2.ElementalPartitions { Flags: []string{}, } - partitions.Recovery = &v2.Partition{ + partitions.Recovery = &types.Partition{ FilesystemLabel: constants.RecoveryLabel, Size: constants.RecoverySize, Name: constants.RecoveryPartName, @@ -486,7 +486,7 @@ func NewDiskElementalPartitions(workdir string) v2.ElementalPartitions { Flags: []string{}, } - partitions.State = &v2.Partition{ + partitions.State = &types.Partition{ FilesystemLabel: constants.StateLabel, Size: constants.StateSize, Name: constants.StatePartName, @@ -496,7 +496,7 @@ func NewDiskElementalPartitions(workdir string) v2.ElementalPartitions { Flags: []string{}, } - partitions.Persistent = &v2.Partition{ + partitions.Persistent = &types.Partition{ FilesystemLabel: constants.PersistentLabel, Size: constants.PersistentSize, Name: constants.PersistentPartName, @@ -508,9 +508,9 @@ func NewDiskElementalPartitions(workdir string) v2.ElementalPartitions { return partitions } -func NewDisk(cfg *v2.BuildConfig) *v2.DiskSpec { +func NewDisk(cfg *types.BuildConfig) *types.DiskSpec { var workdir string - var recoveryImg v2.Image + var recoveryImg types.Image workdir = filepath.Join(cfg.OutDir, constants.DiskWorkDir) @@ -518,38 +518,38 @@ func NewDisk(cfg *v2.BuildConfig) *v2.DiskSpec { recoveryImg.File = filepath.Join(workdir, constants.RecoveryPartName, constants.RecoveryImgFile) recoveryImg.FS = constants.LinuxImgFs recoveryImg.Label = constants.SystemLabel - recoveryImg.Source = v2.NewEmptySrc() + recoveryImg.Source = types.NewEmptySrc() recoveryImg.MountPoint = filepath.Join( workdir, strings.TrimSuffix( constants.RecoveryImgFile, filepath.Ext(constants.RecoveryImgFile), )+mountSuffix, ) - return &v2.DiskSpec{ + return &types.DiskSpec{ Partitions: NewDiskElementalPartitions(workdir), GrubConf: filepath.Join(constants.GrubCfgPath, constants.GrubCfg), - System: v2.NewEmptySrc(), + System: types.NewEmptySrc(), RecoverySystem: recoveryImg, Type: constants.RawType, DeployCmd: []string{"elemental", "--debug", "reset", "--reboot"}, } } -func NewISO() *v2.LiveISO { - return &v2.LiveISO{ +func NewISO() *types.LiveISO { + return &types.LiveISO{ Label: constants.ISOLabel, GrubEntry: constants.GrubDefEntry, - UEFI: []*v2.ImageSource{}, - Image: []*v2.ImageSource{}, - Firmware: v2.EFI, + UEFI: []*types.ImageSource{}, + Image: []*types.ImageSource{}, + Firmware: types.EFI, } } -func NewBuildConfig(opts ...GenericOptions) *v2.BuildConfig { - b := &v1.BuildConfig{ +func NewBuildConfig(opts ...GenericOptions) *types.BuildConfig { + b := &types.BuildConfig{ Config: *NewConfig(opts...), Name: constants.BuildImgName, - Snapshotter: v2.NewLoopDevice(), + Snapshotter: types.NewLoopDevice(), } return b } diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 1264822455f..3ddd2a324fd 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -27,7 +27,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/config" "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -40,9 +40,9 @@ var _ = Describe("Types", Label("types", "config"), func() { var runner *v2mock.FakeRunner var client *v2mock.FakeHTTPClient var sysc *v2mock.FakeSyscall - var logger v2.Logger + var logger types.Logger var ci *v2mock.FakeCloudInitRunner - var c *v2.Config + var c *types.Config BeforeEach(func() { fs, cleanup, err = vfst.NewTestFS(nil) Expect(err).ToNot(HaveOccurred()) @@ -50,7 +50,7 @@ var _ = Describe("Types", Label("types", "config"), func() { runner = v2mock.NewFakeRunner() client = &v2mock.FakeHTTPClient{} sysc = &v2mock.FakeSyscall{} - logger = v2.NewNullLogger() + logger = types.NewNullLogger() ci = &v2mock.FakeCloudInitRunner{} c = config.NewConfig( config.WithFs(fs), @@ -92,13 +92,13 @@ var _ = Describe("Types", Label("types", "config"), func() { It("should use the default mounter", Label("systemctl"), func() { runner := v2mock.NewFakeRunner() sysc := &v2mock.FakeSyscall{} - logger := v2.NewNullLogger() + logger := types.NewNullLogger() c := config.NewConfig( config.WithRunner(runner), config.WithSyscall(sysc), config.WithLogger(logger), ) - Expect(c.Mounter).To(Equal(v2.NewMounter(constants.MountBinary))) + Expect(c.Mounter).To(Equal(types.NewMounter(constants.MountBinary))) }) }) Describe("RunConfig", func() { @@ -108,7 +108,7 @@ var _ = Describe("Types", Label("types", "config"), func() { It("sets the default snapshot", func() { Expect(cfg.Snapshotter.MaxSnaps).To(Equal(constants.LoopDeviceMaxSnaps)) Expect(cfg.Snapshotter.Type).To(Equal(constants.LoopDeviceSnapshotterType)) - snapshotterCfg, ok := cfg.Snapshotter.Config.(*v2.LoopDeviceConfig) + snapshotterCfg, ok := cfg.Snapshotter.Config.(*types.LoopDeviceConfig) Expect(ok).To(BeTrue()) Expect(snapshotterCfg.FS).To(Equal(constants.LinuxImgFs)) Expect(snapshotterCfg.Size).To(Equal(constants.ImgSize)) @@ -129,19 +129,19 @@ var _ = Describe("Types", Label("types", "config"), func() { Expect(err).ShouldNot(HaveOccurred()) spec := config.NewInstallSpec(*c) - Expect(spec.Firmware).To(Equal(v2.EFI)) + Expect(spec.Firmware).To(Equal(types.EFI)) Expect(spec.System.Value()).To(Equal(constants.ISOBaseTree)) Expect(spec.RecoverySystem.Source.Value()).To(Equal(spec.System.Value())) - Expect(spec.PartTable).To(Equal(v2.GPT)) + Expect(spec.PartTable).To(Equal(types.GPT)) Expect(spec.Partitions.EFI).NotTo(BeNil()) }) It("sets installation defaults without being on installation media", Label("install"), func() { spec := config.NewInstallSpec(*c) - Expect(spec.Firmware).To(Equal(v2.EFI)) + Expect(spec.Firmware).To(Equal(types.EFI)) Expect(spec.System.IsEmpty()).To(BeTrue()) Expect(spec.RecoverySystem.Source.IsEmpty()).To(BeTrue()) - Expect(spec.PartTable).To(Equal(v2.GPT)) + Expect(spec.PartTable).To(Equal(types.GPT)) }) }) Describe("ResetSpec", Label("reset"), func() { diff --git a/pkg/elemental/elemental.go b/pkg/elemental/elemental.go index 00a34272502..d5712937af9 100644 --- a/pkg/elemental/elemental.go +++ b/pkg/elemental/elemental.go @@ -29,12 +29,12 @@ import ( "github.com/hashicorp/go-multierror" cnst "github.com/rancher/elemental-toolkit/v2/pkg/constants" "github.com/rancher/elemental-toolkit/v2/pkg/partitioner" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) // FormatPartition will format an already existing partition -func FormatPartition(c v2.Config, part *v2.Partition, opts ...string) error { +func FormatPartition(c types.Config, part *types.Partition, opts ...string) error { c.Logger.Infof("Formatting '%s' partition", part.Name) return partitioner.FormatDevice(c.Runner, part.Path, part.FS, part.FilesystemLabel, opts...) } @@ -42,7 +42,7 @@ func FormatPartition(c v2.Config, part *v2.Partition, opts ...string) error { // PartitionAndFormatDevice creates a new empty partition table on target disk // and applies the configured disk layout by creating and formatting all // required partitions -func PartitionAndFormatDevice(c v2.Config, i *v2.InstallSpec) error { +func PartitionAndFormatDevice(c types.Config, i *types.InstallSpec) error { disk := partitioner.NewDisk( i.Target, partitioner.WithRunner(c.Runner), @@ -66,7 +66,7 @@ func PartitionAndFormatDevice(c v2.Config, i *v2.InstallSpec) error { return createPartitions(c, disk, parts) } -func createAndFormatPartition(c v2.Config, disk *partitioner.Disk, part *v2.Partition) error { +func createAndFormatPartition(c types.Config, disk *partitioner.Disk, part *types.Partition) error { c.Logger.Debugf("Adding partition %s", part.Name) num, err := disk.AddPartition(part.Size, part.FS, part.Name, part.Flags...) if err != nil { @@ -96,7 +96,7 @@ func createAndFormatPartition(c v2.Config, disk *partitioner.Disk, part *v2.Part return nil } -func createPartitions(c v2.Config, disk *partitioner.Disk, parts v2.PartitionList) error { +func createPartitions(c types.Config, disk *partitioner.Disk, parts types.PartitionList) error { for _, part := range parts { err := createAndFormatPartition(c, disk, part) if err != nil { @@ -108,7 +108,7 @@ func createPartitions(c v2.Config, disk *partitioner.Disk, parts v2.PartitionLis // MountPartitions mounts configured partitions. Partitions with an unset mountpoint are not mounted. // Paritions already mounted are not remounted. Note umounts must be handled by caller logic. -func MountPartitions(c v2.Config, parts v2.PartitionList, overwriteFlags ...string) error { +func MountPartitions(c types.Config, parts types.PartitionList, overwriteFlags ...string) error { c.Logger.Infof("Mounting disk partitions") var err error var flags []string @@ -138,7 +138,7 @@ func MountPartitions(c v2.Config, parts v2.PartitionList, overwriteFlags ...stri // UnmountPartitions unmounts configured partitions. Partitions with an unset mountpoint are ignored. // Already unmounted partitions are also ignored. -func UnmountPartitions(c v2.Config, parts v2.PartitionList) error { +func UnmountPartitions(c types.Config, parts types.PartitionList) error { var errs error c.Logger.Infof("Unmounting disk partitions") @@ -159,7 +159,7 @@ func UnmountPartitions(c v2.Config, parts v2.PartitionList) error { } // Is Mounted checks if the given partition is mounted or not -func IsMounted(c v2.Config, part *v2.Partition) (bool, error) { +func IsMounted(c types.Config, part *types.Partition) (bool, error) { if part == nil { return false, fmt.Errorf("nil partition") } @@ -176,7 +176,7 @@ func IsMounted(c v2.Config, part *v2.Partition) (bool, error) { return !notMnt, nil } -func IsRWMountPoint(c v2.Config, mountPoint string) (bool, error) { +func IsRWMountPoint(c types.Config, mountPoint string) (bool, error) { cmdOut, err := c.Runner.Run("findmnt", "-fno", "OPTIONS", mountPoint) if err != nil { return false, err @@ -190,7 +190,7 @@ func IsRWMountPoint(c v2.Config, mountPoint string) (bool, error) { } // MountRWPartition mounts, or remounts if needed, a partition with RW permissions -func MountRWPartition(c v2.Config, part *v2.Partition) (umount func() error, err error) { +func MountRWPartition(c types.Config, part *types.Partition) (umount func() error, err error) { if mnt, _ := IsMounted(c, part); mnt { if ok, _ := IsRWMountPoint(c, part.MountPoint); ok { c.Logger.Debugf("Already RW mounted: %s at %s", part.Name, part.MountPoint) @@ -214,7 +214,7 @@ func MountRWPartition(c v2.Config, part *v2.Partition) (umount func() error, err } // MountPartition mounts a partition with the given mount options -func MountPartition(c v2.Config, part *v2.Partition, opts ...string) error { +func MountPartition(c types.Config, part *types.Partition, opts ...string) error { c.Logger.Debugf("Mounting partition %s", part.FilesystemLabel) err := utils.MkdirAll(c.Fs, part.MountPoint, cnst.DirPerm) if err != nil { @@ -239,7 +239,7 @@ func MountPartition(c v2.Config, part *v2.Partition, opts ...string) error { } // UnmountPartition unmounts the given partition or does nothing if not mounted -func UnmountPartition(c v2.Config, part *v2.Partition) error { +func UnmountPartition(c types.Config, part *types.Partition) error { if mnt, _ := IsMounted(c, part); !mnt { c.Logger.Debugf("Not unmounting partition, %s doesn't look like mountpoint", part.MountPoint) return nil @@ -249,7 +249,7 @@ func UnmountPartition(c v2.Config, part *v2.Partition) error { } // MountFileSystemImage mounts an image with the given mount options -func MountFileSystemImage(c v2.Config, img *v2.Image, opts ...string) error { +func MountFileSystemImage(c types.Config, img *types.Image, opts ...string) error { c.Logger.Debugf("Mounting image %s to %s", img.Label, img.MountPoint) err := utils.MkdirAll(c.Fs, img.MountPoint, cnst.DirPerm) if err != nil { @@ -273,7 +273,7 @@ func MountFileSystemImage(c v2.Config, img *v2.Image, opts ...string) error { } // UnmountFilesystemImage unmounts the given image or does nothing if not mounted -func UnmountFileSystemImage(c v2.Config, img *v2.Image) error { +func UnmountFileSystemImage(c types.Config, img *types.Image) error { // Using IsLikelyNotMountPoint seams to be safe as we are not checking // for bind mounts here if notMnt, _ := c.Mounter.IsLikelyNotMountPoint(img.MountPoint); notMnt { @@ -294,7 +294,7 @@ func UnmountFileSystemImage(c v2.Config, img *v2.Image) error { // CreateFileSystemImage creates the image file for the given image. An root tree path // can be used to determine the image size and the preload flag can be used to create an image // including the root tree data. -func CreateFileSystemImage(c v2.Config, img *v2.Image, rootDir string, preload bool, excludes ...string) error { +func CreateFileSystemImage(c types.Config, img *types.Image, rootDir string, preload bool, excludes ...string) error { c.Logger.Infof("Creating image %s from rootDir %s", img.File, rootDir) err := utils.MkdirAll(c.Fs, filepath.Dir(img.File), cnst.DirPerm) if err != nil { @@ -340,7 +340,7 @@ func CreateFileSystemImage(c v2.Config, img *v2.Image, rootDir string, preload b // CreateImageFromTree creates the given image including the given root tree. If preload flag is true // it attempts to preload the root tree at filesystem format time. This allows creating images with the // given root tree without the need of mounting them. -func CreateImageFromTree(c v2.Config, img *v2.Image, rootDir string, preload bool, cleaners ...func() error) (err error) { +func CreateImageFromTree(c types.Config, img *types.Image, rootDir string, preload bool, cleaners ...func() error) (err error) { defer func() { for _, cleaner := range cleaners { if cleaner == nil { @@ -404,7 +404,7 @@ func CreateImageFromTree(c v2.Config, img *v2.Image, rootDir string, preload boo } // CopyFileImg copies the files target as the source of this image. It also applies the img label over the copied image. -func CopyFileImg(c v2.Config, img *v2.Image) error { +func CopyFileImg(c types.Config, img *types.Image) error { if !img.Source.IsFile() { return fmt.Errorf("Copying a file image requires an image source of file type") } @@ -429,7 +429,7 @@ func CopyFileImg(c v2.Config, img *v2.Image) error { // DeployImage will deploy the given image into the target. This method // creates the filesystem image file and fills it with the correspondant data -func DeployImage(c v2.Config, img *v2.Image) error { +func DeployImage(c types.Config, img *types.Image) error { var err error var cleaner func() error @@ -438,7 +438,7 @@ func DeployImage(c v2.Config, img *v2.Image) error { if img.Source.IsDir() { transientTree = img.Source.Value() } else if img.Source.IsFile() { - srcImg := &v2.Image{ + srcImg := &types.Image{ File: img.Source.Value(), MountPoint: transientTree, } @@ -471,7 +471,7 @@ func DeployImage(c v2.Config, img *v2.Image) error { } // DumpSource sets the image data according to the image source type -func DumpSource(c v2.Config, target string, imgSrc *v2.ImageSource) error { // nolint:gocyclo +func DumpSource(c types.Config, target string, imgSrc *types.ImageSource) error { // nolint:gocyclo var err error var digest string @@ -488,7 +488,7 @@ func DumpSource(c v2.Config, target string, imgSrc *v2.ImageSource) error { // n c.Logger.Infof("Running cosing verification for %s", imgSrc.Value()) out, err := utils.CosignVerify( c.Fs, c.Runner, imgSrc.Value(), - c.CosignPubKey, v2.IsDebugLevel(c.Logger), + c.CosignPubKey, types.IsDebugLevel(c.Logger), ) if err != nil { c.Logger.Errorf("Cosign verification failed: %s", out) @@ -512,7 +512,7 @@ func DumpSource(c v2.Config, target string, imgSrc *v2.ImageSource) error { // n if err != nil { return err } - img := &v2.Image{File: imgSrc.Value(), MountPoint: cnst.ImgSrcDir} + img := &types.Image{File: imgSrc.Value(), MountPoint: cnst.ImgSrcDir} err = MountFileSystemImage(c, img, "auto", "ro") if err != nil { return err @@ -535,7 +535,7 @@ func DumpSource(c v2.Config, target string, imgSrc *v2.ImageSource) error { // n } // CopyCloudConfig will check if there is a cloud init in the config and store it on the target -func CopyCloudConfig(c v2.Config, path string, cloudInit []string) (err error) { +func CopyCloudConfig(c types.Config, path string, cloudInit []string) (err error) { if path == "" { c.Logger.Warnf("empty path. Will not copy cloud config files.") return nil @@ -555,7 +555,7 @@ func CopyCloudConfig(c v2.Config, path string, cloudInit []string) (err error) { } // SelinuxRelabel will relabel the system if it finds the binary and the context -func SelinuxRelabel(c v2.Config, rootDir string, raiseError bool) error { +func SelinuxRelabel(c types.Config, rootDir string, raiseError bool) error { policyFile, err := utils.FindFile(c.Fs, rootDir, filepath.Join(cnst.SELinuxTargetedPolicyPath, "policy.*")) contextFile := filepath.Join(rootDir, cnst.SELinuxTargetedContextFile) contextExists, _ := utils.Exists(c.Fs, contextFile) @@ -580,7 +580,7 @@ func SelinuxRelabel(c v2.Config, rootDir string, raiseError bool) error { } // ApplySelinuxLabels sets SELinux extended attributes to the root-tree being installed -func ApplySelinuxLabels(cfg v2.Config, parts v2.ElementalPartitions) error { +func ApplySelinuxLabels(cfg types.Config, parts types.ElementalPartitions) error { binds := map[string]string{} if mnt, _ := IsMounted(cfg, parts.Persistent); mnt { binds[parts.Persistent.MountPoint] = cnst.PersistentPath @@ -594,10 +594,10 @@ func ApplySelinuxLabels(cfg v2.Config, parts v2.ElementalPartitions) error { } // CheckActiveDeployment returns true if at least one of the mode sentinel files is found -func CheckActiveDeployment(cfg v2.Config) bool { +func CheckActiveDeployment(cfg types.Config) bool { cfg.Logger.Infof("Checking for active deployment") - tests := []func(v2.Config) bool{IsActiveMode, IsPassiveMode, IsRecoveryMode} + tests := []func(types.Config) bool{IsActiveMode, IsPassiveMode, IsRecoveryMode} for _, t := range tests { if t(cfg) { return true @@ -608,26 +608,26 @@ func CheckActiveDeployment(cfg v2.Config) bool { } // IsActiveMode checks if the active mode sentinel file exists -func IsActiveMode(cfg v2.Config) bool { +func IsActiveMode(cfg types.Config) bool { ok, _ := utils.Exists(cfg.Fs, cnst.ActiveMode) return ok } // IsPassiveMode checks if the passive mode sentinel file exists -func IsPassiveMode(cfg v2.Config) bool { +func IsPassiveMode(cfg types.Config) bool { ok, _ := utils.Exists(cfg.Fs, cnst.PassiveMode) return ok } // IsRecoveryMode checks if the recovery mode sentinel file exists -func IsRecoveryMode(cfg v2.Config) bool { +func IsRecoveryMode(cfg types.Config) bool { ok, _ := utils.Exists(cfg.Fs, cnst.RecoveryMode) return ok } // SourceISO downloads an ISO in a temporary folder, mounts it and returns the image source to be used // Returns a source and cleaner method to unmount and remove the temporary folder afterwards. -func SourceFormISO(c v2.Config, iso string) (*v2.ImageSource, func() error, error) { +func SourceFormISO(c types.Config, iso string) (*types.ImageSource, func() error, error) { nilErr := func() error { return nil } tmpDir, err := utils.TempDir(c.Fs, "", "elemental") @@ -669,12 +669,12 @@ func SourceFormISO(c v2.Config, iso string) (*v2.ImageSource, func() error, erro return nil, cleanAll, fmt.Errorf("squashfs image not found in ISO: %s", squashfsImg) } - return v2.NewFileSrc(squashfsImg), cleanAll, nil + return types.NewFileSrc(squashfsImg), cleanAll, nil } // DeactivateDevice deactivates unmounted the block devices present within the system. // Useful to deactivate LVM volumes, if any, related to the target device. -func DeactivateDevices(c v2.Config) error { +func DeactivateDevices(c types.Config) error { var err error var out []byte @@ -693,7 +693,7 @@ func DeactivateDevices(c v2.Config) error { // It will respect TMPDIR and use that if exists, fallback to try the persistent partition if its mounted // and finally the default /tmp/ dir // suffix is what is appended to the dir name elemental-suffix. If empty it will randomly generate a number -func GetTempDir(c v2.Config, suffix string) string { +func GetTempDir(c types.Config, suffix string) string { // if we got a TMPDIR var, respect and use that if suffix == "" { random := rand.New(rand.NewSource(time.Now().UnixNano())) @@ -712,7 +712,7 @@ func GetTempDir(c v2.Config, suffix string) string { } // Check persistent and if its mounted state, _ := c.LoadInstallState() - ep := v2.NewElementalPartitionsFromList(parts, state) + ep := types.NewElementalPartitionsFromList(parts, state) persistent := ep.Persistent if persistent != nil { if mnt, _ := IsMounted(c, persistent); mnt { diff --git a/pkg/elemental/elemental_test.go b/pkg/elemental/elemental_test.go index b37a5eefe7f..dff0eb855e1 100644 --- a/pkg/elemental/elemental_test.go +++ b/pkg/elemental/elemental_test.go @@ -32,7 +32,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" "github.com/rancher/elemental-toolkit/v2/pkg/elemental" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -47,10 +47,10 @@ func TestElementalSuite(t *testing.T) { } var _ = Describe("Elemental", Label("elemental"), func() { - var config *v2.Config + var config *types.Config var runner *v2mock.FakeRunner - var logger v2.Logger - var syscall v2.SyscallInterface + var logger types.Logger + var syscall types.SyscallInterface var client *v2mock.FakeHTTPClient var mounter *v2mock.FakeMounter var extractor *v2mock.FakeImageExtractor @@ -61,7 +61,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { syscall = &v2mock.FakeSyscall{} mounter = v2mock.NewFakeMounter() client = &v2mock.FakeHTTPClient{} - logger = v2.NewNullLogger() + logger = types.NewNullLogger() extractor = v2mock.NewFakeImageExtractor(logger) fs, cleanup, _ = vfst.NewTestFS(nil) config = conf.NewConfig( @@ -76,7 +76,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { }) AfterEach(func() { cleanup() }) Describe("MountRWPartition", Label("mount"), func() { - var parts v2.ElementalPartitions + var parts types.ElementalPartitions BeforeEach(func() { parts = conf.NewInstallElementalPartitions() err := utils.MkdirAll(fs, "/some", constants.DirPerm) @@ -137,7 +137,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { }) Describe("IsMounted", Label("ismounted"), func() { It("checks a mounted partition", func() { - part := &v2.Partition{ + part := &types.Partition{ MountPoint: "/some/mountpoint", } err := mounter.Mount("/some/device", "/some/mountpoint", "auto", []string{}) @@ -147,7 +147,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { Expect(mnt).To(BeTrue()) }) It("checks a not mounted partition", func() { - part := &v2.Partition{ + part := &types.Partition{ MountPoint: "/some/mountpoint", } mnt, err := elemental.IsMounted(*config, part) @@ -155,7 +155,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { Expect(mnt).To(BeFalse()) }) It("checks a partition without mountpoint", func() { - part := &v2.Partition{} + part := &types.Partition{} mnt, err := elemental.IsMounted(*config, part) Expect(err).ShouldNot(HaveOccurred()) Expect(mnt).To(BeFalse()) @@ -167,7 +167,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { }) }) Describe("MountPartitions", Label("MountPartitions", "disk", "partition", "mount"), func() { - var parts v2.ElementalPartitions + var parts types.ElementalPartitions BeforeEach(func() { parts = conf.NewInstallElementalPartitions() @@ -240,7 +240,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { }) Describe("UnmountPartitions", Label("UnmountPartitions", "disk", "partition", "unmount"), func() { - var parts v2.ElementalPartitions + var parts types.ElementalPartitions BeforeEach(func() { parts = conf.NewInstallElementalPartitions() @@ -290,9 +290,9 @@ var _ = Describe("Elemental", Label("elemental"), func() { }) Describe("MountImage", Label("MountImage", "mount", "image"), func() { - var img *v2.Image + var img *types.Image BeforeEach(func() { - img = &v2.Image{MountPoint: "/some/mountpoint"} + img = &types.Image{MountPoint: "/some/mountpoint"} }) It("Mounts file system image", func() { @@ -316,10 +316,10 @@ var _ = Describe("Elemental", Label("elemental"), func() { }) Describe("UnmountImage", Label("UnmountImage", "mount", "image"), func() { - var img *v2.Image + var img *types.Image BeforeEach(func() { runner.ReturnValue = []byte("/dev/loop") - img = &v2.Image{MountPoint: "/some/mountpoint"} + img = &types.Image{MountPoint: "/some/mountpoint"} Expect(elemental.MountFileSystemImage(*config, img)).To(BeNil()) Expect(img.LoopDevice).To(Equal("/dev/loop")) }) @@ -341,15 +341,15 @@ var _ = Describe("Elemental", Label("elemental"), func() { }) Describe("CreateFileSystemImage", Label("CreateFileSystemImage", "image"), func() { - var img *v2.Image + var img *types.Image BeforeEach(func() { - img = &v2.Image{ + img = &types.Image{ Label: "SOME_LABEL", Size: 32, File: filepath.Join(constants.StateDir, "some.img"), FS: constants.LinuxImgFs, MountPoint: constants.TransitionDir, - Source: v2.NewDirSrc(constants.ISOBaseTree), + Source: types.NewDirSrc(constants.ISOBaseTree), } _ = utils.MkdirAll(fs, constants.ISOBaseTree, constants.DirPerm) }) @@ -377,7 +377,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { Describe("FormatPartition", Label("FormatPartition", "partition", "format"), func() { It("Reformats an already existing partition", func() { - part := &v2.Partition{ + part := &types.Partition{ Path: "/dev/device1", FS: "ext4", FilesystemLabel: "MY_LABEL", @@ -391,7 +391,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { var partNum int var printOut string var failPart bool - var install *v2.InstallSpec + var install *types.InstallSpec BeforeEach(func() { cInit = &v2mock.FakeCloudInitRunner{ExecStages: []string{}, Error: false} @@ -471,17 +471,17 @@ var _ = Describe("Elemental", Label("elemental"), func() { }) It("Successfully creates partitions and formats them, EFI boot", func() { - install.PartTable = v2.GPT - install.Firmware = v2.EFI - install.Partitions.SetFirmwarePartitions(v2.EFI, v2.GPT) + install.PartTable = types.GPT + install.Firmware = types.EFI + install.Partitions.SetFirmwarePartitions(types.EFI, types.GPT) Expect(elemental.PartitionAndFormatDevice(*config, install)).To(BeNil()) Expect(runner.MatchMilestones(append(efiPartCmds, partCmds...))).To(BeNil()) }) It("Successfully creates partitions and formats them, BIOS boot", func() { - install.PartTable = v2.GPT - install.Firmware = v2.BIOS - install.Partitions.SetFirmwarePartitions(v2.BIOS, v2.GPT) + install.PartTable = types.GPT + install.Firmware = types.BIOS + install.Partitions.SetFirmwarePartitions(types.BIOS, types.GPT) Expect(elemental.PartitionAndFormatDevice(*config, install)).To(BeNil()) Expect(runner.MatchMilestones(biosPartCmds)).To(BeNil()) }) @@ -558,48 +558,48 @@ var _ = Describe("Elemental", Label("elemental"), func() { return []byte{}, nil } - err := elemental.DumpSource(*config, "/dest", v2.NewDirSrc("/source")) + err := elemental.DumpSource(*config, "/dest", types.NewDirSrc("/source")) Expect(err).ShouldNot(HaveOccurred()) Expect(rsyncCount).To(Equal(1)) Expect(src).To(HaveSuffix("/source/")) Expect(dest).To(HaveSuffix("/dest/")) }) It("Unpacks a docker image to target", Label("docker"), func() { - dockerSrc := v2.NewDockerSrc("docker/image:latest") + dockerSrc := types.NewDockerSrc("docker/image:latest") err := elemental.DumpSource(*config, destDir, dockerSrc) Expect(dockerSrc.GetDigest()).To(Equal("fakeDigest")) Expect(err).To(BeNil()) }) It("Unpacks a docker image to target with cosign validation", Label("docker", "cosign"), func() { config.Cosign = true - err := elemental.DumpSource(*config, destDir, v2.NewDockerSrc("docker/image:latest")) + err := elemental.DumpSource(*config, destDir, types.NewDockerSrc("docker/image:latest")) Expect(err).To(BeNil()) Expect(runner.CmdsMatch([][]string{{"cosign", "verify", "docker/image:latest"}})) }) It("Fails cosign validation", Label("cosign"), func() { runner.ReturnError = errors.New("cosign error") config.Cosign = true - err := elemental.DumpSource(*config, destDir, v2.NewDockerSrc("docker/image:latest")) + err := elemental.DumpSource(*config, destDir, types.NewDockerSrc("docker/image:latest")) Expect(err).NotTo(BeNil()) Expect(runner.CmdsMatch([][]string{{"cosign", "verify", "docker/image:latest"}})) }) It("Fails to unpack a docker image to target", Label("docker"), func() { unpackErr := errors.New("failed to unpack") extractor.SideEffect = func(_, _, _ string, _ bool) (string, error) { return "", unpackErr } - err := elemental.DumpSource(*config, destDir, v2.NewDockerSrc("docker/image:latest")) + err := elemental.DumpSource(*config, destDir, types.NewDockerSrc("docker/image:latest")) Expect(err).To(Equal(unpackErr)) }) It("Copies image file to target", func() { sourceImg := "/source.img" destFile := filepath.Join(destDir, "active.img") - err := elemental.DumpSource(*config, destFile, v2.NewFileSrc(sourceImg)) + err := elemental.DumpSource(*config, destFile, types.NewFileSrc(sourceImg)) Expect(err).To(BeNil()) Expect(runner.IncludesCmds([][]string{{"rsync"}})) }) It("Fails to copy, source can't be mounted", func() { mounter.ErrorOnMount = true - err := elemental.DumpSource(*config, "whatever", v2.NewFileSrc("/source.img")) + err := elemental.DumpSource(*config, "whatever", types.NewFileSrc("/source.img")) Expect(err).To(HaveOccurred()) }) It("Fails to copy, no write permissions", func() { @@ -607,13 +607,13 @@ var _ = Describe("Elemental", Label("elemental"), func() { _, err := fs.Create(sourceImg) Expect(err).To(BeNil()) config.Fs = vfs.NewReadOnlyFS(fs) - err = elemental.DumpSource(*config, "whatever", v2.NewFileSrc("/source.img")) + err = elemental.DumpSource(*config, "whatever", types.NewFileSrc("/source.img")) Expect(err).To(HaveOccurred()) }) }) Describe("CreateImageFromTree", Label("createImg"), func() { var imgFile, root string - var img *v2.Image + var img *types.Image var cleaned bool BeforeEach(func() { @@ -630,7 +630,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { Expect(sf.Close()).To(Succeed()) Expect(err).ShouldNot(HaveOccurred()) - img = &v2.Image{ + img = &types.Image{ FS: constants.LinuxImgFs, File: imgFile, MountPoint: "/some/mountpoint", @@ -671,7 +671,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { }) Describe("DeployImage", Label("deployImg"), func() { var imgFile, srcDir string - var img *v2.Image + var img *types.Image BeforeEach(func() { destDir, err := utils.TempDir(fs, "", "test") @@ -687,11 +687,11 @@ var _ = Describe("Elemental", Label("elemental"), func() { Expect(sf.Close()).To(Succeed()) Expect(err).ShouldNot(HaveOccurred()) - img = &v2.Image{ + img = &types.Image{ FS: constants.LinuxImgFs, File: imgFile, MountPoint: "/some/mountpoint", - Source: v2.NewDirSrc(srcDir), + Source: types.NewDirSrc(srcDir), } }) It("Deploys a directory image source into a filesystem image", func() { @@ -706,13 +706,13 @@ var _ = Describe("Elemental", Label("elemental"), func() { } return []byte{}, nil } - img.Source = v2.NewFileSrc("/some/file/path") + img.Source = types.NewFileSrc("/some/file/path") err := elemental.DeployImage(*config, img) Expect(err).ShouldNot(HaveOccurred()) Expect(runner.IncludesCmds([][]string{{"losetup"}, {"mkfs.ext2"}, {"rsync"}, {"losetup"}})).To(Succeed()) }) It("Deploys a container image source into a filesystem image", func() { - img.Source = v2.NewDockerSrc("image:tag") + img.Source = types.NewDockerSrc("image:tag") err := elemental.DeployImage(*config, img) Expect(err).ShouldNot(HaveOccurred()) Expect(runner.IncludesCmds([][]string{{"mkfs.ext2"}, {"rsync"}})).To(Succeed()) @@ -721,7 +721,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { extractor.SideEffect = func(_, _, _ string, _ bool) (string, error) { return "", fmt.Errorf("failed extracting image") } - img.Source = v2.NewDockerSrc("image:tag") + img.Source = types.NewDockerSrc("image:tag") err := elemental.DeployImage(*config, img) Expect(err).Should(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("extracting image")) @@ -733,7 +733,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { } return []byte{}, nil } - img.Source = v2.NewFileSrc("/some/file/path") + img.Source = types.NewFileSrc("/some/file/path") err := elemental.DeployImage(*config, img) Expect(err).Should(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("calling losetup")) @@ -749,7 +749,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { } return []byte{}, nil } - img.Source = v2.NewFileSrc("/some/file/path") + img.Source = types.NewFileSrc("/some/file/path") err := elemental.DeployImage(*config, img) Expect(err).Should(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("deleting loop")) @@ -776,7 +776,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { }) Describe("CopyImgFile", Label("copyimg"), func() { var imgFile, srcFile string - var img *v2.Image + var img *types.Image var fileContent []byte BeforeEach(func() { destDir, err := utils.TempDir(fs, "", "test") @@ -786,11 +786,11 @@ var _ = Describe("Elemental", Label("elemental"), func() { fileContent = []byte("imagefile") err = fs.WriteFile(srcFile, fileContent, constants.FilePerm) Expect(err).ShouldNot(HaveOccurred()) - img = &v2.Image{ + img = &types.Image{ Label: "myLabel", FS: constants.LinuxImgFs, File: imgFile, - Source: v2.NewFileSrc(srcFile), + Source: types.NewFileSrc(srcFile), } }) It("Copies image file and sets new label", func() { @@ -811,12 +811,12 @@ var _ = Describe("Elemental", Label("elemental"), func() { Expect(data).To(Equal(fileContent)) }) It("Fails to copy image if source is not of file type", func() { - img.Source = v2.NewEmptySrc() + img.Source = types.NewEmptySrc() err := elemental.CopyFileImg(*config, img) Expect(err).Should(HaveOccurred()) }) It("Fails to copy image if source does not exist", func() { - img.Source = v2.NewFileSrc("whatever") + img.Source = types.NewFileSrc("whatever") err := elemental.CopyFileImg(*config, img) Expect(err).Should(HaveOccurred()) }) @@ -990,7 +990,7 @@ var _ = Describe("Elemental", Label("elemental"), func() { }) }) Describe("CloudConfig", Label("CloudConfig", "cloud-config"), func() { - var parts v2.ElementalPartitions + var parts types.ElementalPartitions BeforeEach(func() { parts = conf.NewInstallElementalPartitions() }) diff --git a/pkg/features/features.go b/pkg/features/features.go index de8cdbd37a7..2b0e61505a8 100644 --- a/pkg/features/features.go +++ b/pkg/features/features.go @@ -29,7 +29,7 @@ import ( "strings" "github.com/rancher/elemental-toolkit/v2/pkg/systemd" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -79,7 +79,7 @@ func New(name string, units []*systemd.Unit) *Feature { } } -func (f *Feature) Install(log v2.Logger, destFs v2.FS, runner v2.Runner) error { +func (f *Feature) Install(log types.Logger, destFs types.FS, runner types.Runner) error { path := filepath.Join(embeddedRoot, fmt.Sprintf("%s.tar.gz", f.Name)) tar, err := files.Open(path) if err != nil { @@ -165,7 +165,7 @@ func Get(names []string) ([]*Feature, error) { return features, nil } -func extractTarGzip(log v2.Logger, tarFile io.Reader, destFs v2.FS, featureName string) error { +func extractTarGzip(log types.Logger, tarFile io.Reader, destFs types.FS, featureName string) error { gzipReader, err := gzip.NewReader(tarFile) if err != nil { return err diff --git a/pkg/http/client.go b/pkg/http/client.go index dfc0e8d0a7d..4b28f1decf5 100644 --- a/pkg/http/client.go +++ b/pkg/http/client.go @@ -23,7 +23,7 @@ import ( "github.com/cavaliergopher/grab/v3" "github.com/rancher/elemental-toolkit/v2/pkg/constants" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) type Client struct { @@ -37,7 +37,7 @@ func NewClient() *Client { } // GetURL attempts to download the contents of the given URL to the given destination -func (c Client) GetURL(log v2.Logger, url string, destination string) error { // nolint:revive +func (c Client) GetURL(log types.Logger, url string, destination string) error { // nolint:revive req, err := grab.NewRequest(destination, url) if err != nil { log.Errorf("Failed creating a request to '%s'", url) diff --git a/pkg/http/client_test.go b/pkg/http/client_test.go index b925d690f35..07f20d6c6b3 100644 --- a/pkg/http/client_test.go +++ b/pkg/http/client_test.go @@ -21,7 +21,7 @@ import ( "path/filepath" "github.com/rancher/elemental-toolkit/v2/pkg/http" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -31,11 +31,11 @@ const source = "https://raw.githubusercontent.com/rancher/elemental-toolkit/main var _ = Describe("HTTPClient", Label("http"), func() { var client *http.Client - var log v2.Logger + var log types.Logger var destDir string BeforeEach(func() { client = http.NewClient() - log = v2.NewNullLogger() + log = types.NewNullLogger() destDir, _ = os.MkdirTemp("", "elemental-test") }) AfterEach(func() { diff --git a/pkg/mocks/bootloader_mock.go b/pkg/mocks/bootloader_mock.go index 0977deb13e3..decefa170ca 100644 --- a/pkg/mocks/bootloader_mock.go +++ b/pkg/mocks/bootloader_mock.go @@ -19,10 +19,10 @@ package mocks import ( "fmt" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) -var _ v2.Bootloader = (*FakeBootloader)(nil) +var _ types.Bootloader = (*FakeBootloader)(nil) type FakeBootloader struct { ErrorInstall bool diff --git a/pkg/mocks/extractor_mock.go b/pkg/mocks/extractor_mock.go index 9dfa8c1af7d..86deff26a87 100644 --- a/pkg/mocks/extractor_mock.go +++ b/pkg/mocks/extractor_mock.go @@ -16,18 +16,18 @@ limitations under the License. package mocks -import v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" +import "github.com/rancher/elemental-toolkit/v2/pkg/types" const FakeDigest = "fakeDigest" type FakeImageExtractor struct { - Logger v2.Logger + Logger types.Logger SideEffect func(imageRef, destination, platformRef string, local bool) (string, error) } -var _ v2.ImageExtractor = FakeImageExtractor{} +var _ types.ImageExtractor = FakeImageExtractor{} -func NewFakeImageExtractor(logger v2.Logger) *FakeImageExtractor { +func NewFakeImageExtractor(logger types.Logger) *FakeImageExtractor { return &FakeImageExtractor{ Logger: logger, } diff --git a/pkg/mocks/http_mock.go b/pkg/mocks/http_mock.go index 8ac5c399d1e..315ceee6bbd 100644 --- a/pkg/mocks/http_mock.go +++ b/pkg/mocks/http_mock.go @@ -19,7 +19,7 @@ package mocks import ( "errors" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) // FakeHTTPClient is an implementation of HTTPClient interface used for testing @@ -30,7 +30,7 @@ type FakeHTTPClient struct { } // GetURL will return a FakeHttpBody and store the url call into ClientCalls -func (m *FakeHTTPClient) GetURL(_ v2.Logger, url string, _ string) error { +func (m *FakeHTTPClient) GetURL(_ types.Logger, url string, _ string) error { // Store calls to the mock client, so we can verify that we didnt mangled them or anything m.ClientCalls = append(m.ClientCalls, url) if m.Error { diff --git a/pkg/mocks/mounter_mock.go b/pkg/mocks/mounter_mock.go index 505ddcbf07d..c2b024c17af 100644 --- a/pkg/mocks/mounter_mock.go +++ b/pkg/mocks/mounter_mock.go @@ -19,11 +19,11 @@ package mocks import ( "errors" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "k8s.io/mount-utils" ) -var _ v2.Mounter = (*FakeMounter)(nil) +var _ types.Mounter = (*FakeMounter)(nil) // FakeMounter is a fake mounter for tests that can error out. type FakeMounter struct { diff --git a/pkg/mocks/runner_mock.go b/pkg/mocks/runner_mock.go index f95535c7d15..c38c8151202 100644 --- a/pkg/mocks/runner_mock.go +++ b/pkg/mocks/runner_mock.go @@ -21,7 +21,7 @@ import ( "os/exec" "strings" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) type FakeRunner struct { @@ -29,7 +29,7 @@ type FakeRunner struct { ReturnValue []byte SideEffect func(command string, args ...string) ([]byte, error) ReturnError error - Logger v2.Logger + Logger types.Logger CmdNotFound string } @@ -137,11 +137,11 @@ func (r FakeRunner) GetCmds() [][]string { return r.cmds } -func (r FakeRunner) GetLogger() v2.Logger { +func (r FakeRunner) GetLogger() types.Logger { return r.Logger } -func (r *FakeRunner) SetLogger(logger v2.Logger) { +func (r *FakeRunner) SetLogger(logger types.Logger) { r.Logger = logger } diff --git a/pkg/mocks/utils.go b/pkg/mocks/utils.go index 1f8ee9b4e72..a17d385d8ae 100644 --- a/pkg/mocks/utils.go +++ b/pkg/mocks/utils.go @@ -22,13 +22,13 @@ import ( "strconv" "github.com/rancher/elemental-toolkit/v2/pkg/constants" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) // FakeLoopDeviceSnapshotsStatus creates fake snapshots files according to the LoopDevice behavior. // Used for unit testing only. -func FakeLoopDeviceSnapshotsStatus(fs v2.FS, rootDir string, snapsCount int) error { +func FakeLoopDeviceSnapshotsStatus(fs types.FS, rootDir string, snapsCount int) error { var snapshotFile, snapshotsPrefix string var i int var err error diff --git a/pkg/partitioner/disk.go b/pkg/partitioner/disk.go index 19105244315..b23f31e8830 100644 --- a/pkg/partitioner/disk.go +++ b/pkg/partitioner/disk.go @@ -27,7 +27,7 @@ import ( "github.com/twpayne/go-vfs/v4" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -45,10 +45,10 @@ type Disk struct { lastS uint parts []Partition label string - runner v2.Runner - fs v2.FS - logger v2.Logger - mounter v2.Mounter + runner types.Runner + fs types.FS + logger types.Logger + mounter types.Mounter partBackend string } @@ -66,7 +66,7 @@ func NewDisk(device string, opts ...DiskOptions) *Disk { } if dev.runner == nil { - dev.runner = &v2.RealRunner{} + dev.runner = &types.RealRunner{} } if dev.fs == nil { @@ -74,19 +74,19 @@ func NewDisk(device string, opts ...DiskOptions) *Disk { } if dev.logger == nil { - dev.logger = v2.NewLogger() + dev.logger = types.NewLogger() } if dev.mounter == nil { path, _ := exec.LookPath("mount") - dev.mounter = v2.NewMounter(path) + dev.mounter = types.NewMounter(path) } return dev } // FormatDevice formats a block device with the given parameters -func FormatDevice(runner v2.Runner, device string, fileSystem string, label string, opts ...string) error { +func FormatDevice(runner types.Runner, device string, fileSystem string, label string, opts ...string) error { mkfs := MkfsCall{fileSystem: fileSystem, label: label, customOpts: opts, dev: device, runner: runner} _, err := mkfs.Apply() return err @@ -413,7 +413,7 @@ func (dev Disk) expandFilesystem(device string) (outStr string, err error) { case "xfs", "btrfs": // to grow an xfs or btrfs fs it needs to be mounted :/ tmpDir, err = utils.TempDir(dev.fs, "", "partitioner") - defer func(fs v2.FS, path string) { + defer func(fs types.FS, path string) { _ = fs.RemoveAll(path) }(dev.fs, tmpDir) diff --git a/pkg/partitioner/mkfs.go b/pkg/partitioner/mkfs.go index 9d8214efac9..eee0dd69d02 100644 --- a/pkg/partitioner/mkfs.go +++ b/pkg/partitioner/mkfs.go @@ -21,7 +21,7 @@ import ( "regexp" "github.com/rancher/elemental-toolkit/v2/pkg/constants" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) type MkfsCall struct { @@ -29,10 +29,10 @@ type MkfsCall struct { label string customOpts []string dev string - runner v2.Runner + runner types.Runner } -func NewMkfsCall(dev string, fileSystem string, label string, runner v2.Runner, customOpts ...string) *MkfsCall { +func NewMkfsCall(dev string, fileSystem string, label string, runner types.Runner, customOpts ...string) *MkfsCall { return &MkfsCall{dev: dev, fileSystem: fileSystem, label: label, runner: runner, customOpts: customOpts} } diff --git a/pkg/partitioner/options.go b/pkg/partitioner/options.go index ba1119af035..0209050e905 100644 --- a/pkg/partitioner/options.go +++ b/pkg/partitioner/options.go @@ -17,26 +17,26 @@ limitations under the License. package partitioner import ( - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) type DiskOptions func(d *Disk) error -func WithFS(fs v2.FS) func(d *Disk) error { +func WithFS(fs types.FS) func(d *Disk) error { return func(d *Disk) error { d.fs = fs return nil } } -func WithRunner(runner v2.Runner) func(d *Disk) error { +func WithRunner(runner types.Runner) func(d *Disk) error { return func(d *Disk) error { d.runner = runner return nil } } -func WithLogger(logger v2.Logger) func(d *Disk) error { +func WithLogger(logger types.Logger) func(d *Disk) error { return func(d *Disk) error { d.logger = logger return nil @@ -50,7 +50,7 @@ func WithGdisk() func(d *Disk) error { } } -func WithMounter(mounter v2.Mounter) func(d *Disk) error { +func WithMounter(mounter types.Mounter) func(d *Disk) error { return func(d *Disk) error { d.mounter = mounter return nil diff --git a/pkg/partitioner/parted.go b/pkg/partitioner/parted.go index 8725fb7d871..fff22d32e7c 100644 --- a/pkg/partitioner/parted.go +++ b/pkg/partitioner/parted.go @@ -25,7 +25,7 @@ import ( "strings" "github.com/rancher/elemental-toolkit/v2/pkg/constants" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) type partedCall struct { @@ -34,7 +34,7 @@ type partedCall struct { parts []*Partition deletions []int label string - runner v2.Runner + runner types.Runner flags []partFlag } @@ -46,7 +46,7 @@ type partFlag struct { var _ Partitioner = (*partedCall)(nil) -func newPartedCall(dev string, runner v2.Runner) *partedCall { +func newPartedCall(dev string, runner types.Runner) *partedCall { return &partedCall{dev: dev, wipe: false, parts: []*Partition{}, deletions: []int{}, label: "", runner: runner, flags: []partFlag{}} } diff --git a/pkg/partitioner/partitioner.go b/pkg/partitioner/partitioner.go index d0c0cee977e..eea552b72f2 100644 --- a/pkg/partitioner/partitioner.go +++ b/pkg/partitioner/partitioner.go @@ -17,7 +17,7 @@ limitations under the License. package partitioner import ( - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) const Parted = "parted" @@ -47,7 +47,7 @@ type Partition struct { FileSystem string } -func NewPartitioner(dev string, runner v2.Runner, backend string) Partitioner { +func NewPartitioner(dev string, runner types.Runner, backend string) Partitioner { switch backend { case Parted: return newPartedCall(dev, runner) diff --git a/pkg/partitioner/partitioner_test.go b/pkg/partitioner/partitioner_test.go index e3f990557dd..f1e07c61a67 100644 --- a/pkg/partitioner/partitioner_test.go +++ b/pkg/partitioner/partitioner_test.go @@ -30,7 +30,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" mocks "github.com/rancher/elemental-toolkit/v2/pkg/mocks" part "github.com/rancher/elemental-toolkit/v2/pkg/partitioner" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -105,14 +105,14 @@ var _ = Describe("Partitioner", Label("disk", "partition", "partitioner"), func( {"sgdisk", "--zap-all", "/dev/device"}, {"partx", "-u", "/dev/device"}, } - Expect(gc.SetPartitionTableLabel(v2.GPT)).To(Succeed()) + Expect(gc.SetPartitionTableLabel(types.GPT)).To(Succeed()) gc.WipeTable(true) _, err := gc.WriteChanges() Expect(err).To(BeNil()) Expect(runner.CmdsMatch(cmds)).To(BeNil()) }) It("Fails setting a new partition label", func() { - Expect(gc.SetPartitionTableLabel(v2.MSDOS)).NotTo(Succeed()) + Expect(gc.SetPartitionTableLabel(types.MSDOS)).NotTo(Succeed()) }) It("Creates a new partition", func() { cmds := [][]string{ @@ -179,7 +179,7 @@ var _ = Describe("Partitioner", Label("disk", "partition", "partitioner"), func( }) It("Gets partition table label", func() { label, _ := gc.GetPartitionTableLabel(sgdiskPrint) - Expect(label).To(Equal(v2.GPT)) + Expect(label).To(Equal(types.GPT)) }) It("Gets partitions info of the disk", func() { parts := gc.GetPartitions(sgdiskPrint) diff --git a/pkg/partitioner/sgdisk.go b/pkg/partitioner/sgdisk.go index 523d77203fa..c9099790fa5 100644 --- a/pkg/partitioner/sgdisk.go +++ b/pkg/partitioner/sgdisk.go @@ -24,7 +24,7 @@ import ( "strconv" "strings" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) const efiType = "EF00" @@ -36,14 +36,14 @@ type gdiskCall struct { wipe bool parts []*Partition deletions []int - runner v2.Runner + runner types.Runner expand bool pretend bool } var _ Partitioner = (*gdiskCall)(nil) -func newGdiskCall(dev string, runner v2.Runner) *gdiskCall { +func newGdiskCall(dev string, runner types.Runner) *gdiskCall { return &gdiskCall{ dev: dev, runner: runner, @@ -175,7 +175,7 @@ func (gd gdiskCall) GetSectorSize(printOut string) (uint, error) { // TODO parse printOut from a non gpt disk and return error here func (gd gdiskCall) GetPartitionTableLabel(_ string) (string, error) { - return v2.GPT, nil + return types.GPT, nil } // Parses the output of a gdiskCall.Print call diff --git a/pkg/snapshotter/btrfs.go b/pkg/snapshotter/btrfs.go index 700a80614d5..107f5a8d4ef 100644 --- a/pkg/snapshotter/btrfs.go +++ b/pkg/snapshotter/btrfs.go @@ -29,7 +29,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" "github.com/rancher/elemental-toolkit/v2/pkg/elemental" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -54,17 +54,17 @@ func configTemplatesPaths() []string { } } -var _ v2.Snapshotter = (*Btrfs)(nil) +var _ types.Snapshotter = (*Btrfs)(nil) type Btrfs struct { - cfg v2.Config - snapshotterCfg v2.SnapshotterConfig - btrfsCfg v2.BtrfsConfig + cfg types.Config + snapshotterCfg types.SnapshotterConfig + btrfsCfg types.BtrfsConfig rootDir string efiDir string currentSnapshotID int activeSnapshotID int - bootloader v2.Bootloader + bootloader types.Bootloader installing bool snapperArgs []string snapshotsUmount func() error @@ -109,18 +109,18 @@ func (d *Date) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { } // NewLoopDeviceSnapshotter creates a new loop device snapshotter vased on the given configuration and the given bootloader -func newBtrfsSnapshotter(cfg v2.Config, snapCfg v2.SnapshotterConfig, bootloader v2.Bootloader) (v2.Snapshotter, error) { +func newBtrfsSnapshotter(cfg types.Config, snapCfg types.SnapshotterConfig, bootloader types.Bootloader) (types.Snapshotter, error) { if snapCfg.Type != constants.BtrfsSnapshotterType { msg := "invalid snapshotter type ('%s'), must be of '%s' type" cfg.Logger.Errorf(msg, snapCfg.Type, constants.BtrfsSnapshotterType) return nil, fmt.Errorf(msg, snapCfg.Type, constants.BtrfsSnapshotterType) } - var btrfsCfg *v2.BtrfsConfig + var btrfsCfg *types.BtrfsConfig var ok bool if snapCfg.Config == nil { - btrfsCfg = v2.NewBtrfsConfig() + btrfsCfg = types.NewBtrfsConfig() } else { - btrfsCfg, ok = snapCfg.Config.(*v2.BtrfsConfig) + btrfsCfg, ok = snapCfg.Config.(*types.BtrfsConfig) if !ok { msg := "failed casting BtrfsConfig type" cfg.Logger.Errorf(msg) @@ -158,11 +158,11 @@ func (b *Btrfs) InitSnapshotter(state *v1.Partition, efiDir string) error { return b.setBtrfsForFirstTime(state) } -func (b *Btrfs) StartTransaction() (*v2.Snapshot, error) { +func (b *Btrfs) StartTransaction() (*types.Snapshot, error) { var newID int var err error var workingDir, path string - snapshot := &v2.Snapshot{} + snapshot := &types.Snapshot{} b.cfg.Logger.Info("Starting a btrfs snapshotter transaction") @@ -244,7 +244,7 @@ func (b *Btrfs) StartTransaction() (*v2.Snapshot, error) { return snapshot, err } -func (b *Btrfs) CloseTransactionOnError(snapshot *v2.Snapshot) (err error) { +func (b *Btrfs) CloseTransactionOnError(snapshot *types.Snapshot) (err error) { if snapshot.InProgress { err = b.cfg.Mounter.Unmount(snapshot.MountPoint) } @@ -258,7 +258,7 @@ func (b *Btrfs) CloseTransactionOnError(snapshot *v2.Snapshot) (err error) { return err } -func (b *Btrfs) CloseTransaction(snapshot *v2.Snapshot) (err error) { +func (b *Btrfs) CloseTransaction(snapshot *types.Snapshot) (err error) { var cmdOut []byte var subvolID int @@ -423,7 +423,7 @@ func (b *Btrfs) loadSnapshots() ([]int, error) { // SnapshotImageToSource converts the given snapshot into an ImageSource. This is useful to deploy a system // from a given snapshot, for instance setting the recovery image from a snapshot. -func (b *Btrfs) SnapshotToImageSource(snap *v2.Snapshot) (*v2.ImageSource, error) { +func (b *Btrfs) SnapshotToImageSource(snap *types.Snapshot) (*types.ImageSource, error) { ok, err := utils.Exists(b.cfg.Fs, snap.Path) if err != nil || !ok { msg := fmt.Sprintf("snapshot path does not exist: %s.", snap.Path) @@ -433,7 +433,7 @@ func (b *Btrfs) SnapshotToImageSource(snap *v2.Snapshot) (*v2.ImageSource, error } return nil, err } - return v2.NewDirSrc(snap.Path), nil + return types.NewDirSrc(snap.Path), nil } func (b *Btrfs) getSubvolumes(rootDir string) (btrfsSubvolList, error) { @@ -615,7 +615,7 @@ func (b *Btrfs) setBootloader() error { return err } -func (b *Btrfs) configureSnapper(snapshot *v2.Snapshot) error { +func (b *Btrfs) configureSnapper(snapshot *types.Snapshot) error { defaultTmpl, err := utils.FindFile(b.cfg.Fs, snapshot.WorkDir, configTemplatesPaths()...) if err != nil { b.cfg.Logger.Errorf("failed to find default snapper configuration template") @@ -661,7 +661,7 @@ func (b *Btrfs) configureSnapper(snapshot *v2.Snapshot) error { return nil } -func (b *Btrfs) remountStatePartition(state *v2.Partition) error { +func (b *Btrfs) remountStatePartition(state *types.Partition) error { b.cfg.Logger.Debugf("Umount %s", state.MountPoint) err := b.cfg.Mounter.Unmount(state.MountPoint) if err != nil { @@ -693,7 +693,7 @@ func (b *Btrfs) remountStatePartition(state *v2.Partition) error { return nil } -func (b *Btrfs) setBtrfsForFirstTime(state *v1.Partition) error { +func (b *Btrfs) setBtrfsForFirstTime(state *types.Partition) error { b.cfg.Logger.Debug("Enabling btrfs quota") cmdOut, err := b.cfg.Runner.Run("btrfs", "quota", "enable", state.MountPoint) if err != nil { @@ -720,7 +720,7 @@ func (b *Btrfs) setBtrfsForFirstTime(state *v1.Partition) error { return b.remountStatePartition(state) } -func (b *Btrfs) configureSnapperAndRootDir(state *v2.Partition) error { +func (b *Btrfs) configureSnapperAndRootDir(state *types.Partition) error { rootDir, stateMount, err := findStateMount(b.cfg.Runner, state.Path) if err != nil { b.cfg.Logger.Errorf("failed setting snapper root and state partition mountpoint: %v", err) @@ -736,7 +736,7 @@ func (b *Btrfs) configureSnapperAndRootDir(state *v2.Partition) error { return nil } -func findStateMount(runner v1.Runner, device string) (rootDir string, stateMount string, err error) { +func findStateMount(runner types.Runner, device string) (rootDir string, stateMount string, err error) { output, err := runner.Run("findmnt", "-lno", "SOURCE,TARGET", device) if err != nil { return "", "", err diff --git a/pkg/snapshotter/btrfs_test.go b/pkg/snapshotter/btrfs_test.go index aa5890796c2..c894a44f08c 100644 --- a/pkg/snapshotter/btrfs_test.go +++ b/pkg/snapshotter/btrfs_test.go @@ -28,28 +28,28 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" "github.com/rancher/elemental-toolkit/v2/pkg/snapshotter" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" "github.com/twpayne/go-vfs/v4" "github.com/twpayne/go-vfs/v4/vfst" ) var _ = Describe("Btrfs", Label("snapshotter", " btrfs"), func() { - var cfg v2.Config + var cfg types.Config var runner *v2mock.FakeRunner var fs vfs.FS - var logger v2.Logger + var logger types.Logger var mounter *v2mock.FakeMounter var cleanup func() var bootloader *v2mock.FakeBootloader var memLog *bytes.Buffer - var snapCfg v2.SnapshotterConfig + var snapCfg types.SnapshotterConfig var rootDir, efiDir string - var statePart *v2.Partition + var statePart *types.Partition BeforeEach(func() { rootDir = "/some/root" - statePart = &v2.Partition{ + statePart = &types.Partition{ Name: constants.StatePartName, Path: "/dev/state-device", MountPoint: rootDir, @@ -59,8 +59,8 @@ var _ = Describe("Btrfs", Label("snapshotter", " btrfs"), func() { mounter = v2mock.NewFakeMounter() bootloader = &v2mock.FakeBootloader{} memLog = bytes.NewBuffer(nil) - logger = v2.NewBufferLogger(memLog) - logger.SetLevel(v2.DebugLevel()) + logger = types.NewBufferLogger(memLog) + logger.SetLevel(types.DebugLevel()) var err error fs, cleanup, err = vfst.NewTestFS(map[string]interface{}{}) @@ -73,7 +73,7 @@ var _ = Describe("Btrfs", Label("snapshotter", " btrfs"), func() { conf.WithMounter(mounter), conf.WithPlatform("linux/amd64"), ) - snapCfg = v2.SnapshotterConfig{ + snapCfg = types.SnapshotterConfig{ Type: constants.BtrfsSnapshotterType, MaxSnaps: 4, } @@ -97,7 +97,7 @@ var _ = Describe("Btrfs", Label("snapshotter", " btrfs"), func() { }) Describe("Running transaction", func() { - var b v2.Snapshotter + var b types.Snapshotter var err error BeforeEach(func() { @@ -127,7 +127,7 @@ var _ = Describe("Btrfs", Label("snapshotter", " btrfs"), func() { }) Describe("Closing a transaction on a clean install", func() { - var snap *v2.Snapshot + var snap *types.Snapshot BeforeEach(func() { snap, err = b.StartTransaction() Expect(err).NotTo(HaveOccurred()) @@ -288,7 +288,7 @@ var _ = Describe("Btrfs", Label("snapshotter", " btrfs"), func() { }) Describe("Closing a transaction on a recovery system", func() { - var snap *v2.Snapshot + var snap *types.Snapshot BeforeEach(func() { runner.SideEffect = func(cmd string, args ...string) ([]byte, error) { fullCmd := strings.Join(append([]string{cmd}, args...), " ") @@ -482,7 +482,7 @@ var _ = Describe("Btrfs", Label("snapshotter", " btrfs"), func() { }) Describe("Closing a transaction on an active system", func() { - var snap *v2.Snapshot + var snap *types.Snapshot BeforeEach(func() { runner.SideEffect = func(cmd string, args ...string) ([]byte, error) { fullCmd := strings.Join(append([]string{cmd}, args...), " ") diff --git a/pkg/snapshotter/common.go b/pkg/snapshotter/common.go index 22fd6ff5674..6472f06a483 100644 --- a/pkg/snapshotter/common.go +++ b/pkg/snapshotter/common.go @@ -20,14 +20,14 @@ import ( "fmt" "github.com/rancher/elemental-toolkit/v2/pkg/constants" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) -type snapshotterFactory func(cfg v2.Config, snapCfg v2.SnapshotterConfig, bootloader v2.Bootloader) (v2.Snapshotter, error) +type snapshotterFactory func(cfg types.Config, snapCfg types.SnapshotterConfig, bootloader types.Bootloader) (types.Snapshotter, error) var snapshotterFactories = map[string]snapshotterFactory{} -func NewSnapshotter(cfg v2.Config, snapCfg v2.SnapshotterConfig, bootloader v2.Bootloader) (v2.Snapshotter, error) { +func NewSnapshotter(cfg types.Config, snapCfg types.SnapshotterConfig, bootloader types.Bootloader) (types.Snapshotter, error) { factory := snapshotterFactories[snapCfg.Type] if factory != nil { return factory(cfg, snapCfg, bootloader) diff --git a/pkg/snapshotter/loopdevice.go b/pkg/snapshotter/loopdevice.go index 1ec2e6e58a9..69f7d50b810 100644 --- a/pkg/snapshotter/loopdevice.go +++ b/pkg/snapshotter/loopdevice.go @@ -29,7 +29,7 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" "github.com/rancher/elemental-toolkit/v2/pkg/elemental" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -40,33 +40,33 @@ const ( loopDeviceLabelPattern = "EL_SNAP%d" ) -var _ v2.Snapshotter = (*LoopDevice)(nil) +var _ types.Snapshotter = (*LoopDevice)(nil) type LoopDevice struct { - cfg v2.Config - snapshotterCfg v2.SnapshotterConfig - loopDevCfg v2.LoopDeviceConfig + cfg types.Config + snapshotterCfg types.SnapshotterConfig + loopDevCfg types.LoopDeviceConfig rootDir string efiDir string currentSnapshotID int activeSnapshotID int - bootloader v2.Bootloader + bootloader types.Bootloader legacyClean bool } // newLoopDeviceSnapshotter creates a new loop device snapshotter vased on the given configuration and the given bootloader -func newLoopDeviceSnapshotter(cfg v2.Config, snapCfg v2.SnapshotterConfig, bootloader v2.Bootloader) (v2.Snapshotter, error) { +func newLoopDeviceSnapshotter(cfg types.Config, snapCfg types.SnapshotterConfig, bootloader types.Bootloader) (types.Snapshotter, error) { if snapCfg.Type != constants.LoopDeviceSnapshotterType { msg := "invalid snapshotter type ('%s'), must be of '%s' type" cfg.Logger.Errorf(msg, snapCfg.Type, constants.LoopDeviceSnapshotterType) return nil, fmt.Errorf(msg, snapCfg.Type, constants.LoopDeviceSnapshotterType) } - var loopDevCfg *v2.LoopDeviceConfig + var loopDevCfg *types.LoopDeviceConfig var ok bool if snapCfg.Config == nil { - loopDevCfg = v2.NewLoopDeviceConfig() + loopDevCfg = types.NewLoopDeviceConfig() } else { - loopDevCfg, ok = snapCfg.Config.(*v2.LoopDeviceConfig) + loopDevCfg, ok = snapCfg.Config.(*types.LoopDeviceConfig) if !ok { msg := "failed casting LoopDeviceConfig type" cfg.Logger.Errorf(msg) @@ -125,7 +125,7 @@ func (l *LoopDevice) InitSnapshotter(state *v1.Partition, efiDir string) error { } // StartTransaction starts a transaction for this snapshotter instance and returns the work in progress snapshot object. -func (l *LoopDevice) StartTransaction() (*v2.Snapshot, error) { +func (l *LoopDevice) StartTransaction() (*types.Snapshot, error) { l.cfg.Logger.Infof("Starting a snapshotter transaction") nextID, err := l.getNextSnapshotID() if err != nil { @@ -175,7 +175,7 @@ func (l *LoopDevice) StartTransaction() (*v2.Snapshot, error) { return nil, err } - snapshot := &v2.Snapshot{ + snapshot := &types.Snapshot{ ID: nextID, Path: filepath.Join(snapPath, loopDeviceImgName), WorkDir: workDir, @@ -190,7 +190,7 @@ func (l *LoopDevice) StartTransaction() (*v2.Snapshot, error) { // CloseTransactionOnError is a destructor method to clean the given initated snapshot. Useful in case of an error once // the transaction has already started. -func (l *LoopDevice) CloseTransactionOnError(snapshot *v2.Snapshot) error { +func (l *LoopDevice) CloseTransactionOnError(snapshot *types.Snapshot) error { var err error if snapshot == nil { @@ -218,7 +218,7 @@ func (l *LoopDevice) CloseTransactionOnError(snapshot *v2.Snapshot) error { // CloseTransaction closes the transaction for the given snapshot. This is the responsible of setting new active and // passive snapshots. -func (l *LoopDevice) CloseTransaction(snapshot *v2.Snapshot) (err error) { +func (l *LoopDevice) CloseTransaction(snapshot *types.Snapshot) (err error) { var linkDst, activeSnap string defer func() { @@ -356,7 +356,7 @@ func (l *LoopDevice) GetSnapshots() ([]int, error) { // SnapshotImageToSource converts the given snapshot into an ImageSource. This is useful to deploy a system // from a given snapshot, for instance setting the recovery image from a snapshot. -func (l *LoopDevice) SnapshotToImageSource(snap *v2.Snapshot) (*v2.ImageSource, error) { +func (l *LoopDevice) SnapshotToImageSource(snap *types.Snapshot) (*types.ImageSource, error) { ok, err := utils.Exists(l.cfg.Fs, snap.Path) if err != nil || !ok { msg := fmt.Sprintf("snapshot path does not exist: %s.", snap.Path) @@ -366,7 +366,7 @@ func (l *LoopDevice) SnapshotToImageSource(snap *v2.Snapshot) (*v2.ImageSource, } return nil, err } - return v2.NewFileSrc(snap.Path), nil + return types.NewFileSrc(snap.Path), nil } // getNextSnapshotID returns the next ID number for a new snapshot. @@ -441,8 +441,8 @@ func (l *LoopDevice) isSnapshotInUse(id int) (bool, error) { } // snapshotToImage is a helper method to convert an snapshot object into an image object. -func (l *LoopDevice) snapshotToImage(snapshot *v2.Snapshot) *v2.Image { - return &v2.Image{ +func (l *LoopDevice) snapshotToImage(snapshot *types.Snapshot) *types.Image { + return &types.Image{ File: snapshot.Path, Label: snapshot.Label, Size: l.loopDevCfg.Size, diff --git a/pkg/snapshotter/loopdevice_test.go b/pkg/snapshotter/loopdevice_test.go index 6c0ea02db9b..5f1db40f1d2 100644 --- a/pkg/snapshotter/loopdevice_test.go +++ b/pkg/snapshotter/loopdevice_test.go @@ -26,28 +26,28 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" "github.com/rancher/elemental-toolkit/v2/pkg/snapshotter" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" "github.com/twpayne/go-vfs/v4" "github.com/twpayne/go-vfs/v4/vfst" ) var _ = Describe("LoopDevice", Label("snapshotter", "loopdevice"), func() { - var cfg v2.Config + var cfg types.Config var runner *v2mock.FakeRunner var fs vfs.FS - var logger v2.Logger + var logger types.Logger var mounter *v2mock.FakeMounter var cleanup func() var bootloader *v2mock.FakeBootloader var memLog *bytes.Buffer - var snapCfg v2.SnapshotterConfig + var snapCfg types.SnapshotterConfig var rootDir, efiDir string - var statePart *v2.Partition + var statePart *types.Partition BeforeEach(func() { rootDir = "/some/root" - statePart = &v1.Partition{ + statePart = &types.Partition{ Name: constants.StatePartName, Path: "/dev/state-device", MountPoint: rootDir, @@ -57,8 +57,8 @@ var _ = Describe("LoopDevice", Label("snapshotter", "loopdevice"), func() { mounter = v2mock.NewFakeMounter() bootloader = &v2mock.FakeBootloader{} memLog = bytes.NewBuffer(nil) - logger = v2.NewBufferLogger(memLog) - logger.SetLevel(v2.DebugLevel()) + logger = types.NewBufferLogger(memLog) + logger.SetLevel(types.DebugLevel()) var err error fs, cleanup, err = vfst.NewTestFS(map[string]interface{}{}) @@ -71,7 +71,7 @@ var _ = Describe("LoopDevice", Label("snapshotter", "loopdevice"), func() { conf.WithMounter(mounter), conf.WithPlatform("linux/amd64"), ) - snapCfg = v2.NewLoopDevice() + snapCfg = types.NewLoopDevice() Expect(utils.MkdirAll(fs, rootDir, constants.DirPerm)).To(Succeed()) }) @@ -191,7 +191,7 @@ var _ = Describe("LoopDevice", Label("snapshotter", "loopdevice"), func() { Describe("using loopdevice on sixth snapshot", func() { var err error - var lp v2.Snapshotter + var lp types.Snapshotter BeforeEach(func() { diff --git a/pkg/systemd/unit.go b/pkg/systemd/unit.go index e4496fd3358..3e740baff26 100644 --- a/pkg/systemd/unit.go +++ b/pkg/systemd/unit.go @@ -17,7 +17,7 @@ limitations under the License. package systemd import ( - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) type Unit struct { @@ -30,12 +30,12 @@ func NewUnit(name string) *Unit { } } -func Enable(runner v2.Runner, unit *Unit) error { +func Enable(runner types.Runner, unit *Unit) error { _, err := runner.Run("systemctl", "enable", unit.Name) return err } -func Start(runner v2.Runner, unit *Unit) error { +func Start(runner types.Runner, unit *Unit) error { _, err := runner.Run("systemctl", "start", unit.Name) return err } diff --git a/pkg/types/v2/bootloader.go b/pkg/types/bootloader.go similarity index 98% rename from pkg/types/v2/bootloader.go rename to pkg/types/bootloader.go index 8098c7eaf3d..063116739bd 100644 --- a/pkg/types/v2/bootloader.go +++ b/pkg/types/bootloader.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types type Bootloader interface { Install(rootDir, bootDir string) (err error) diff --git a/pkg/types/v2/cloud-init-runner.go b/pkg/types/cloud-init-runner.go similarity index 98% rename from pkg/types/v2/cloud-init-runner.go rename to pkg/types/cloud-init-runner.go index 1d416a85a68..fb98b310fa5 100644 --- a/pkg/types/v2/cloud-init-runner.go +++ b/pkg/types/cloud-init-runner.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "github.com/rancher/yip/pkg/schema" diff --git a/pkg/types/v2/common.go b/pkg/types/common.go similarity index 99% rename from pkg/types/v2/common.go rename to pkg/types/common.go index e4b8d24bba0..1b3beabdf94 100644 --- a/pkg/types/v2/common.go +++ b/pkg/types/common.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "fmt" diff --git a/pkg/types/v2/common_test.go b/pkg/types/common_test.go similarity index 84% rename from pkg/types/v2/common_test.go rename to pkg/types/common_test.go index cf4a8d0d704..64478a1a2ef 100644 --- a/pkg/types/v2/common_test.go +++ b/pkg/types/common_test.go @@ -14,42 +14,42 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1_test +package types_test import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) var _ = Describe("Types", Label("types", "common"), func() { Describe("Source", func() { It("initiates each type as expected", func() { - o := &v2.ImageSource{} + o := &types.ImageSource{} Expect(o.Value()).To(Equal("")) Expect(o.IsDir()).To(BeFalse()) Expect(o.IsImage()).To(BeFalse()) Expect(o.IsFile()).To(BeFalse()) - o = v2.NewDirSrc("dir") + o = types.NewDirSrc("dir") Expect(o.IsDir()).To(BeTrue()) - o = v2.NewFileSrc("file") + o = types.NewFileSrc("file") Expect(o.IsFile()).To(BeTrue()) - o = v2.NewDockerSrc("image") + o = types.NewDockerSrc("image") Expect(o.IsImage()).To(BeTrue()) - o = v2.NewEmptySrc() + o = types.NewEmptySrc() Expect(o.IsEmpty()).To(BeTrue()) - o, err := v2.NewSrcFromURI("registry.company.org/image") + o, err := types.NewSrcFromURI("registry.company.org/image") Expect(o.IsImage()).To(BeTrue()) Expect(err).ShouldNot(HaveOccurred()) Expect(o.Value()).To(Equal("registry.company.org/image:latest")) - o, err = v2.NewSrcFromURI("oci://registry.company.org/image:tag") + o, err = types.NewSrcFromURI("oci://registry.company.org/image:tag") Expect(o.IsImage()).To(BeTrue()) Expect(err).ShouldNot(HaveOccurred()) Expect(o.Value()).To(Equal("registry.company.org/image:tag")) }) It("unmarshals each type as expected", func() { - o := v2.NewEmptySrc() + o := types.NewEmptySrc() _, err := o.CustomUnmarshal("docker://some/image") Expect(err).ShouldNot(HaveOccurred()) Expect(o.IsImage()).To(BeTrue()) @@ -80,35 +80,35 @@ var _ = Describe("Types", Label("types", "common"), func() { Expect(o.Value()).To(Equal("registry.company.org/my/image:tag")) }) It("convertion to string URI works are expected", func() { - o := v2.NewDirSrc("/some/dir") + o := types.NewDirSrc("/some/dir") Expect(o.IsDir()).To(BeTrue()) Expect(o.String()).To(Equal("dir:///some/dir")) - o = v2.NewFileSrc("filename") + o = types.NewFileSrc("filename") Expect(o.IsFile()).To(BeTrue()) Expect(o.String()).To(Equal("file://filename")) - o = v2.NewDockerSrc("container/image") + o = types.NewDockerSrc("container/image") Expect(o.IsImage()).To(BeTrue()) Expect(o.String()).To(Equal("oci://container/image")) - o = v2.NewEmptySrc() + o = types.NewEmptySrc() Expect(o.IsEmpty()).To(BeTrue()) Expect(o.String()).To(Equal("")) - o, err := v2.NewSrcFromURI("registry.company.org/image") + o, err := types.NewSrcFromURI("registry.company.org/image") Expect(o.IsImage()).To(BeTrue()) Expect(err).ShouldNot(HaveOccurred()) Expect(o.String()).To(Equal("oci://registry.company.org/image:latest")) }) It("fails to unmarshal non string types", func() { - o := v2.NewEmptySrc() + o := types.NewEmptySrc() _, err := o.CustomUnmarshal(map[string]string{}) Expect(err).Should(HaveOccurred()) }) It("fails to unmarshal unknown scheme and invalid image reference", func() { - o := v2.NewEmptySrc() + o := types.NewEmptySrc() _, err := o.CustomUnmarshal("scheme://some.uri.org") Expect(err).Should(HaveOccurred()) }) It("fails to unmarshal invalid uri", func() { - o := v2.NewEmptySrc() + o := types.NewEmptySrc() _, err := o.CustomUnmarshal("jp#afs://insanity") Expect(err).Should(HaveOccurred()) }) diff --git a/pkg/types/v2/config.go b/pkg/types/config.go similarity index 99% rename from pkg/types/v2/config.go rename to pkg/types/config.go index 95a3e989223..1fb53b8dec9 100644 --- a/pkg/types/v2/config.go +++ b/pkg/types/config.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "fmt" diff --git a/pkg/types/v2/config_test.go b/pkg/types/config_test.go similarity index 79% rename from pkg/types/v2/config_test.go rename to pkg/types/config_test.go index e1dfe478913..964ef365e5d 100644 --- a/pkg/types/v2/config_test.go +++ b/pkg/types/config_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1_test +package types_test import ( "path/filepath" @@ -28,20 +28,20 @@ import ( conf "github.com/rancher/elemental-toolkit/v2/pkg/config" "github.com/rancher/elemental-toolkit/v2/pkg/constants" v1mocks "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) var _ = Describe("Types", Label("types", "config"), func() { Describe("Write and load installation state", func() { - var config *v2.RunConfig + var config *types.RunConfig var runner *v1mocks.FakeRunner var fs vfs.FS var mounter *v1mocks.FakeMounter var cleanup func() var err error - var systemState *v2.SystemState - var installState *v2.InstallState + var systemState *types.SystemState + var installState *types.InstallState var statePath, recoveryPath string BeforeEach(func() { @@ -55,26 +55,26 @@ var _ = Describe("Types", Label("types", "config"), func() { conf.WithRunner(runner), conf.WithMounter(mounter), ) - systemState = &v2.SystemState{ - Source: v2.NewDockerSrc("registry.org/my/image:tag"), + systemState = &types.SystemState{ + Source: types.NewDockerSrc("registry.org/my/image:tag"), Label: "active_label", FS: "ext2", Digest: "adadgadg", } - installState = &v2.InstallState{ + installState = &types.InstallState{ Date: "somedate", - Snapshotter: v2.SnapshotterConfig{ + Snapshotter: types.SnapshotterConfig{ Type: "loopdevice", MaxSnaps: 7, - Config: &v2.LoopDeviceConfig{ + Config: &types.LoopDeviceConfig{ Size: 1024, FS: constants.SquashFs, }, }, - Partitions: map[string]*v2.PartitionState{ + Partitions: map[string]*types.PartitionState{ "state": { FSLabel: "state_label", - Snapshots: map[int]*v2.SystemState{ + Snapshots: map[int]*types.SystemState{ 1: systemState, }, }, @@ -151,12 +151,12 @@ var _ = Describe("Types", Label("types", "config"), func() { }) }) Describe("ElementalPartitions", func() { - var p v2.PartitionList - var ep v2.ElementalPartitions + var p types.PartitionList + var ep types.ElementalPartitions BeforeEach(func() { - ep = v2.ElementalPartitions{} - p = v2.PartitionList{ - &v2.Partition{ + ep = types.ElementalPartitions{} + p = types.PartitionList{ + &types.Partition{ FilesystemLabel: "COS_OEM", Size: 0, Name: "oem", @@ -166,7 +166,7 @@ var _ = Describe("Types", Label("types", "config"), func() { Path: "", Disk: "", }, - &v2.Partition{ + &types.Partition{ FilesystemLabel: "COS_CUSTOM", Size: 0, Name: "persistent", @@ -176,7 +176,7 @@ var _ = Describe("Types", Label("types", "config"), func() { Path: "", Disk: "", }, - &v2.Partition{ + &types.Partition{ FilesystemLabel: "SOMETHING", Size: 0, Name: "somename", @@ -190,33 +190,33 @@ var _ = Describe("Types", Label("types", "config"), func() { }) It("sets firmware partitions on efi", func() { Expect(ep.EFI == nil && ep.BIOS == nil).To(BeTrue()) - err := ep.SetFirmwarePartitions(v2.EFI, v2.GPT) + err := ep.SetFirmwarePartitions(types.EFI, types.GPT) Expect(err).ShouldNot(HaveOccurred()) Expect(ep.EFI != nil && ep.BIOS == nil).To(BeTrue()) }) It("sets firmware partitions on bios", func() { Expect(ep.EFI == nil && ep.BIOS == nil).To(BeTrue()) - err := ep.SetFirmwarePartitions(v2.BIOS, v2.GPT) + err := ep.SetFirmwarePartitions(types.BIOS, types.GPT) Expect(err).ShouldNot(HaveOccurred()) Expect(ep.EFI == nil && ep.BIOS != nil).To(BeTrue()) }) It("sets firmware partitions on msdos", func() { - ep.State = &v2.Partition{} + ep.State = &types.Partition{} Expect(ep.EFI == nil && ep.BIOS == nil).To(BeTrue()) - err := ep.SetFirmwarePartitions(v2.BIOS, v2.MSDOS) + err := ep.SetFirmwarePartitions(types.BIOS, types.MSDOS) Expect(err).ShouldNot(HaveOccurred()) Expect(ep.EFI == nil && ep.BIOS == nil).To(BeTrue()) Expect(ep.State.Flags != nil && ep.State.Flags[0] == "boot").To(BeTrue()) }) It("fails to set firmware partitions of state is not defined on msdos", func() { Expect(ep.EFI == nil && ep.BIOS == nil).To(BeTrue()) - err := ep.SetFirmwarePartitions(v2.BIOS, v2.MSDOS) + err := ep.SetFirmwarePartitions(types.BIOS, types.MSDOS) Expect(err).Should(HaveOccurred()) }) It("initializes an ElementalPartitions from a PartitionList", func() { // Use custom label for recovery partition - ep := v2.NewElementalPartitionsFromList(p, &v2.InstallState{ - Partitions: map[string]*v2.PartitionState{ + ep := types.NewElementalPartitionsFromList(p, &types.InstallState{ + Partitions: map[string]*types.PartitionState{ constants.RecoveryPartName: { FSLabel: "SOMETHING", }, @@ -231,23 +231,23 @@ var _ = Describe("Types", Label("types", "config"), func() { }) Describe("returns a partition list by install order", func() { It("with no extra parts", func() { - ep := v2.NewElementalPartitionsFromList(p, nil) - lst := ep.PartitionsByInstallOrder([]*v2.Partition{}) + ep := types.NewElementalPartitionsFromList(p, nil) + lst := ep.PartitionsByInstallOrder([]*types.Partition{}) Expect(len(lst)).To(Equal(2)) Expect(lst[0].Name == "oem").To(BeTrue()) Expect(lst[1].Name == "persistent").To(BeTrue()) }) It("with extra parts with size > 0", func() { // Use custom label for state partition - ep := v2.NewElementalPartitionsFromList(p, &v2.InstallState{ - Partitions: map[string]*v2.PartitionState{ + ep := types.NewElementalPartitionsFromList(p, &types.InstallState{ + Partitions: map[string]*types.PartitionState{ constants.StatePartName: { FSLabel: "SOMETHING", }, }, }) - var extraParts []*v2.Partition - extraParts = append(extraParts, &v2.Partition{Name: "extra", Size: 5}) + var extraParts []*types.Partition + extraParts = append(extraParts, &types.Partition{Name: "extra", Size: 5}) lst := ep.PartitionsByInstallOrder(extraParts) Expect(len(lst)).To(Equal(4)) @@ -257,9 +257,9 @@ var _ = Describe("Types", Label("types", "config"), func() { Expect(lst[3].Name == "persistent").To(BeTrue()) }) It("with extra part with size == 0 and persistent.Size == 0", func() { - ep := v2.NewElementalPartitionsFromList(p, &v2.InstallState{}) - var extraParts []*v2.Partition - extraParts = append(extraParts, &v2.Partition{Name: "extra", Size: 0}) + ep := types.NewElementalPartitionsFromList(p, &types.InstallState{}) + var extraParts []*types.Partition + extraParts = append(extraParts, &types.Partition{Name: "extra", Size: 0}) lst := ep.PartitionsByInstallOrder(extraParts) // Should ignore the wrong partition had have the persistent over it Expect(len(lst)).To(Equal(2)) @@ -267,10 +267,10 @@ var _ = Describe("Types", Label("types", "config"), func() { Expect(lst[1].Name == "persistent").To(BeTrue()) }) It("with extra part with size == 0 and persistent.Size > 0", func() { - ep := v2.NewElementalPartitionsFromList(p, nil) + ep := types.NewElementalPartitionsFromList(p, nil) ep.Persistent.Size = 10 - var extraParts []*v2.Partition - extraParts = append(extraParts, &v2.Partition{Name: "extra", FilesystemLabel: "LABEL", Size: 0}) + var extraParts []*types.Partition + extraParts = append(extraParts, &types.Partition{Name: "extra", FilesystemLabel: "LABEL", Size: 0}) lst := ep.PartitionsByInstallOrder(extraParts) // Will have our size == 0 partition the latest Expect(len(lst)).To(Equal(3)) @@ -279,11 +279,11 @@ var _ = Describe("Types", Label("types", "config"), func() { Expect(lst[2].Name == "extra").To(BeTrue()) }) It("with several extra parts with size == 0 and persistent.Size > 0", func() { - ep := v2.NewElementalPartitionsFromList(p, nil) + ep := types.NewElementalPartitionsFromList(p, nil) ep.Persistent.Size = 10 - var extraParts []*v2.Partition - extraParts = append(extraParts, &v2.Partition{Name: "extra1", Size: 0}) - extraParts = append(extraParts, &v2.Partition{Name: "extra2", Size: 0}) + var extraParts []*types.Partition + extraParts = append(extraParts, &types.Partition{Name: "extra1", Size: 0}) + extraParts = append(extraParts, &types.Partition{Name: "extra2", Size: 0}) lst := ep.PartitionsByInstallOrder(extraParts) // Should ignore the wrong partition had have the first partition with size 0 added last Expect(len(lst)).To(Equal(3)) @@ -294,14 +294,14 @@ var _ = Describe("Types", Label("types", "config"), func() { }) It("returns a partition list by mount order", func() { - ep := v2.NewElementalPartitionsFromList(p, nil) + ep := types.NewElementalPartitionsFromList(p, nil) lst := ep.PartitionsByMountPoint(false) Expect(len(lst)).To(Equal(2)) Expect(lst[0].Name == "persistent").To(BeTrue()) Expect(lst[1].Name == "oem").To(BeTrue()) }) It("returns a partition list by mount reverse order", func() { - ep := v2.NewElementalPartitionsFromList(p, nil) + ep := types.NewElementalPartitionsFromList(p, nil) lst := ep.PartitionsByMountPoint(true) Expect(len(lst)).To(Equal(2)) Expect(lst[0].Name == "oem").To(BeTrue()) @@ -309,10 +309,10 @@ var _ = Describe("Types", Label("types", "config"), func() { }) }) Describe("Partitionlist", func() { - var p v2.PartitionList + var p types.PartitionList BeforeEach(func() { - p = v2.PartitionList{ - &v2.Partition{ + p = types.PartitionList{ + &types.Partition{ FilesystemLabel: "ONE", Size: 0, Name: "one", @@ -322,7 +322,7 @@ var _ = Describe("Types", Label("types", "config"), func() { Path: "", Disk: "", }, - &v2.Partition{ + &types.Partition{ FilesystemLabel: "TWO", Size: 0, Name: "two", @@ -335,7 +335,7 @@ var _ = Describe("Types", Label("types", "config"), func() { } }) It("returns partitions by name", func() { - Expect(p.GetByName("two")).To(Equal(&v2.Partition{ + Expect(p.GetByName("two")).To(Equal(&types.Partition{ FilesystemLabel: "TWO", Size: 0, Name: "two", @@ -350,7 +350,7 @@ var _ = Describe("Types", Label("types", "config"), func() { Expect(p.GetByName("nonexistent")).To(BeNil()) }) It("returns partitions by filesystem label", func() { - Expect(p.GetByLabel("TWO")).To(Equal(&v2.Partition{ + Expect(p.GetByLabel("TWO")).To(Equal(&types.Partition{ FilesystemLabel: "TWO", Size: 0, Name: "two", @@ -366,7 +366,7 @@ var _ = Describe("Types", Label("types", "config"), func() { }) }) Describe("InstallSpec", func() { - var spec *v2.InstallSpec + var spec *types.InstallSpec BeforeEach(func() { cfg := config.NewConfig(config.WithMounter(v1mocks.NewFakeMounter())) @@ -378,8 +378,8 @@ var _ = Describe("Types", Label("types", "config"), func() { Expect(spec.System.IsEmpty()).To(BeTrue()) // Creates firmware partitions - spec.System = v2.NewDirSrc("/dir") - spec.Firmware = v2.EFI + spec.System = types.NewDirSrc("/dir") + spec.Firmware = types.EFI err := spec.Sanitize() Expect(err).ShouldNot(HaveOccurred()) Expect(spec.Partitions.EFI).NotTo(BeNil()) @@ -396,31 +396,31 @@ var _ = Describe("Types", Label("types", "config"), func() { Expect(err).Should(HaveOccurred()) // Fails without an install source - spec.System = v2.NewEmptySrc() + spec.System = types.NewEmptySrc() err = spec.Sanitize() Expect(err).Should(HaveOccurred()) }) Describe("with extra partitions", func() { BeforeEach(func() { // Set a source for the install - spec.System = v2.NewDirSrc("/dir") + spec.System = types.NewDirSrc("/dir") }) It("fails if persistent and an extra partition have size == 0", func() { - spec.ExtraPartitions = append(spec.ExtraPartitions, &v2.Partition{Size: 0}) + spec.ExtraPartitions = append(spec.ExtraPartitions, &types.Partition{Size: 0}) err := spec.Sanitize() Expect(err).Should(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("both persistent partition and extra partitions have size set to 0")) }) It("fails if more than one extra partition has size == 0", func() { spec.Partitions.Persistent.Size = 10 - spec.ExtraPartitions = append(spec.ExtraPartitions, &v2.Partition{Name: "1", Size: 0}) - spec.ExtraPartitions = append(spec.ExtraPartitions, &v2.Partition{Name: "2", Size: 0}) + spec.ExtraPartitions = append(spec.ExtraPartitions, &types.Partition{Name: "1", Size: 0}) + spec.ExtraPartitions = append(spec.ExtraPartitions, &types.Partition{Name: "2", Size: 0}) err := spec.Sanitize() Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("more than one extra partition has its size set to 0")) }) It("does not fail if persistent size is > 0 and an extra partition has size == 0", func() { - spec.ExtraPartitions = append(spec.ExtraPartitions, &v2.Partition{Size: 0}) + spec.ExtraPartitions = append(spec.ExtraPartitions, &types.Partition{Size: 0}) spec.Partitions.Persistent.Size = 10 err := spec.Sanitize() Expect(err).ToNot(HaveOccurred()) @@ -430,10 +430,10 @@ var _ = Describe("Types", Label("types", "config"), func() { }) Describe("ResetSpec", func() { It("runs sanitize method", func() { - spec := &v2.ResetSpec{ - System: v2.NewDirSrc("/dir"), - Partitions: v2.ElementalPartitions{ - State: &v2.Partition{ + spec := &types.ResetSpec{ + System: types.NewDirSrc("/dir"), + Partitions: types.ElementalPartitions{ + State: &types.Partition{ MountPoint: "mountpoint", }, }, @@ -447,24 +447,24 @@ var _ = Describe("Types", Label("types", "config"), func() { Expect(err).Should(HaveOccurred()) //Fails on empty source - spec.System = v2.NewEmptySrc() + spec.System = types.NewEmptySrc() err = spec.Sanitize() Expect(err).Should(HaveOccurred()) }) }) Describe("UpgradeSpec", func() { It("runs sanitize method", func() { - spec := &v2.UpgradeSpec{ - System: v2.NewDirSrc("/dir"), - RecoverySystem: v2.Image{ - Source: v2.NewDirSrc("/dir"), + spec := &types.UpgradeSpec{ + System: types.NewDirSrc("/dir"), + RecoverySystem: types.Image{ + Source: types.NewDirSrc("/dir"), Label: "SOMELABEL", }, - Partitions: v2.ElementalPartitions{ - State: &v2.Partition{ + Partitions: types.ElementalPartitions{ + State: &types.Partition{ MountPoint: "mountpoint", }, - Recovery: &v2.Partition{ + Recovery: &types.Partition{ MountPoint: "mountpoint", }, }, @@ -479,14 +479,14 @@ var _ = Describe("Types", Label("types", "config"), func() { Expect(spec.RecoverySystem.Label).To(BeEmpty()) //Fails on empty source for active upgrade - spec.System = v2.NewEmptySrc() + spec.System = types.NewEmptySrc() err = spec.Sanitize() Expect(err).Should(HaveOccurred()) //Sets recovery source to system source if empty - spec.System = v2.NewDockerSrc("some/image:tag") + spec.System = types.NewDockerSrc("some/image:tag") spec.RecoveryUpgrade = true - spec.RecoverySystem.Source = v2.NewEmptySrc() + spec.RecoverySystem.Source = types.NewEmptySrc() err = spec.Sanitize() Expect(err).ShouldNot(HaveOccurred()) Expect(spec.RecoverySystem.Source.Value()).To(Equal(spec.System.Value())) @@ -508,9 +508,9 @@ var _ = Describe("Types", Label("types", "config"), func() { Expect(iso.Sanitize()).ShouldNot(HaveOccurred()) //Success when properly provided source packages - spec := &v2.LiveISO{ - RootFS: []*v2.ImageSource{ - v2.NewDirSrc("/system/os"), + spec := &types.LiveISO{ + RootFS: []*types.ImageSource{ + types.NewDirSrc("/system/os"), }, } spec.BootloaderInRootFs = true @@ -518,14 +518,14 @@ var _ = Describe("Types", Label("types", "config"), func() { Expect(iso.Sanitize()).ShouldNot(HaveOccurred()) //Fails when packages were provided in incorrect format - spec = &v2.LiveISO{ - RootFS: []*v2.ImageSource{ + spec = &types.LiveISO{ + RootFS: []*types.ImageSource{ nil, }, - UEFI: []*v2.ImageSource{ + UEFI: []*types.ImageSource{ nil, }, - Image: []*v2.ImageSource{ + Image: []*types.ImageSource{ nil, }, } diff --git a/pkg/types/v2/errors.go b/pkg/types/errors.go similarity index 98% rename from pkg/types/v2/errors.go rename to pkg/types/errors.go index 73a82dfb1a8..126dd12f9c8 100644 --- a/pkg/types/v2/errors.go +++ b/pkg/types/errors.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types // SourceNotFound is the error to raise when we can't find a source for install/upgrade type SourceNotFound struct { diff --git a/pkg/types/v2/fs.go b/pkg/types/fs.go similarity index 98% rename from pkg/types/v2/fs.go rename to pkg/types/fs.go index 6d89170a5f6..a783bf8e08c 100644 --- a/pkg/types/v2/fs.go +++ b/pkg/types/fs.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "io/fs" diff --git a/pkg/types/v2/grub.go b/pkg/types/grub.go similarity index 99% rename from pkg/types/v2/grub.go rename to pkg/types/grub.go index b5c9d5e30e3..92a720e9858 100644 --- a/pkg/types/v2/grub.go +++ b/pkg/types/grub.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" diff --git a/pkg/types/v2/http.go b/pkg/types/http.go similarity index 97% rename from pkg/types/v2/http.go rename to pkg/types/http.go index 674f589be8a..c5bb8d2e7bc 100644 --- a/pkg/types/v2/http.go +++ b/pkg/types/http.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types type HTTPClient interface { GetURL(log Logger, url string, destination string) error diff --git a/pkg/types/v2/image.go b/pkg/types/image.go similarity index 87% rename from pkg/types/v2/image.go rename to pkg/types/image.go index 417b1507371..0aab94aadca 100644 --- a/pkg/types/v2/image.go +++ b/pkg/types/image.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "context" @@ -25,7 +25,7 @@ import ( "github.com/containerd/containerd/archive" "github.com/google/go-containerregistry/pkg/authn" "github.com/google/go-containerregistry/pkg/name" - v2 "github.com/google/go-containerregistry/pkg/v1" + containerregistry "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/daemon" "github.com/google/go-containerregistry/pkg/v1/mutate" "github.com/google/go-containerregistry/pkg/v1/remote" @@ -40,7 +40,7 @@ type OCIImageExtractor struct{} var _ ImageExtractor = OCIImageExtractor{} func (e OCIImageExtractor) ExtractImage(imageRef, destination, platformRef string, local bool) (string, error) { - platform, err := v2.ParsePlatform(platformRef) + platform, err := containerregistry.ParsePlatform(platformRef) if err != nil { return "", err } @@ -50,7 +50,7 @@ func (e OCIImageExtractor) ExtractImage(imageRef, destination, platformRef strin return "", err } - var img v2.Image + var img containerregistry.Image err = backoff.Retry(func() error { img, err = image(ref, *platform, local) @@ -71,7 +71,7 @@ func (e OCIImageExtractor) ExtractImage(imageRef, destination, platformRef strin return digest.String(), err } -func image(ref name.Reference, platform v2.Platform, local bool) (v2.Image, error) { +func image(ref name.Reference, platform containerregistry.Platform, local bool) (containerregistry.Image, error) { if local { return daemon.Image(ref) } diff --git a/pkg/types/v2/logger.go b/pkg/types/logger.go similarity index 99% rename from pkg/types/v2/logger.go rename to pkg/types/logger.go index 34d8ade4cf8..4fc7801ede9 100644 --- a/pkg/types/v2/logger.go +++ b/pkg/types/logger.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "bytes" diff --git a/pkg/types/v2/logger_test.go b/pkg/types/logger_test.go similarity index 79% rename from pkg/types/v2/logger_test.go rename to pkg/types/logger_test.go index e718d5db5ef..bc4d195874d 100644 --- a/pkg/types/v2/logger_test.go +++ b/pkg/types/logger_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1_test +package types_test import ( "bytes" @@ -24,34 +24,34 @@ import ( . "github.com/onsi/gomega" "github.com/sirupsen/logrus" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) var _ = Describe("logger", Label("log", "logger", "types"), func() { It("TestNewLogger returns a logger interface", func() { - l1 := v2.NewLogger() + l1 := types.NewLogger() l2 := logrus.New() Expect(reflect.TypeOf(l1).Kind()).To(Equal(reflect.TypeOf(l2).Kind())) }) It("TestNewNullLogger returns logger interface", func() { - l1 := v2.NewNullLogger() + l1 := types.NewNullLogger() l2 := logrus.New() Expect(reflect.TypeOf(l1).Kind()).To(Equal(reflect.TypeOf(l2).Kind())) }) It("DebugLevel returns the proper log level for debug output", func() { - Expect(v2.DebugLevel()).To(Equal(logrus.DebugLevel)) + Expect(types.DebugLevel()).To(Equal(logrus.DebugLevel)) }) It("Returns true on IsDebugLevel when log level is set to debug", func() { - l := v2.NewLogger() - l.SetLevel(v2.DebugLevel()) - Expect(v2.IsDebugLevel(l)).To(BeTrue()) + l := types.NewLogger() + l.SetLevel(types.DebugLevel()) + Expect(types.IsDebugLevel(l)).To(BeTrue()) }) It("Returns false on IsDebugLevel when log level is not set to debug", func() { - Expect(v2.IsDebugLevel(v2.NewLogger())).To(BeFalse()) + Expect(types.IsDebugLevel(types.NewLogger())).To(BeFalse()) }) It("NewBufferLogger stores content in a buffer", func() { b := &bytes.Buffer{} - l1 := v2.NewBufferLogger(b) + l1 := types.NewBufferLogger(b) l1.Info("TEST") Expect(b).To(ContainSubstring("TEST")) }) diff --git a/pkg/types/v2/mounter.go b/pkg/types/mounter.go similarity index 91% rename from pkg/types/v2/mounter.go rename to pkg/types/mounter.go index 0c1c70f9520..bff64163055 100644 --- a/pkg/types/v2/mounter.go +++ b/pkg/types/mounter.go @@ -14,13 +14,13 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "k8s.io/mount-utils" ) -// This is is just a redefinition of mount.Interface to v2.Mounter types +// This is is just a redefinition of mount.Interface to types.Mounter types type Mounter interface { Mount(source string, target string, fstype string, options []string) error Unmount(target string) error diff --git a/pkg/types/v2/platform.go b/pkg/types/platform.go similarity index 99% rename from pkg/types/v2/platform.go rename to pkg/types/platform.go index 072f2a77c7f..f083f4ae890 100644 --- a/pkg/types/v2/platform.go +++ b/pkg/types/platform.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "fmt" diff --git a/pkg/types/v2/platform_test.go b/pkg/types/platform_test.go similarity index 85% rename from pkg/types/v2/platform_test.go rename to pkg/types/platform_test.go index b86b3b7391e..01731e03753 100644 --- a/pkg/types/v2/platform_test.go +++ b/pkg/types/platform_test.go @@ -14,33 +14,33 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1_test +package types_test import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) var _ = Describe("Platform", Label("types", "platform"), func() { Describe("Source", func() { It("initiates platform as expected", func() { - platform, err := v2.NewPlatform("linux", "x86_64") + platform, err := types.NewPlatform("linux", "x86_64") Expect(err).To(BeNil()) Expect(platform.OS).To(Equal("linux")) Expect(platform.Arch).To(Equal("x86_64")) Expect(platform.GolangArch).To(Equal("amd64")) }) It("parses platform as expected", func() { - platform, err := v2.ParsePlatform("linux/amd64") + platform, err := types.ParsePlatform("linux/amd64") Expect(err).To(BeNil()) Expect(platform.OS).To(Equal("linux")) Expect(platform.Arch).To(Equal("x86_64")) Expect(platform.GolangArch).To(Equal("amd64")) }) It("initiates arm64 platform as expected", func() { - platform, err := v2.NewPlatformFromArch("arm64") + platform, err := types.NewPlatformFromArch("arm64") Expect(err).To(BeNil()) Expect(platform.OS).To(Equal("linux")) Expect(platform.Arch).To(Equal("arm64")) diff --git a/pkg/types/v2/runner.go b/pkg/types/runner.go similarity index 99% rename from pkg/types/v2/runner.go rename to pkg/types/runner.go index 8a1cd0e43a4..743841b9ab9 100644 --- a/pkg/types/v2/runner.go +++ b/pkg/types/runner.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "fmt" diff --git a/pkg/types/v2/runner_test.go b/pkg/types/runner_test.go similarity index 81% rename from pkg/types/v2/runner_test.go rename to pkg/types/runner_test.go index 7090518173a..b891100abd5 100644 --- a/pkg/types/v2/runner_test.go +++ b/pkg/types/runner_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1_test +package types_test import ( "bytes" @@ -23,12 +23,12 @@ import ( . "github.com/onsi/gomega" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) var _ = Describe("Runner", Label("types", "runner"), func() { It("Runs commands on the real Runner", func() { - r := v2.RealRunner{} + r := types.RealRunner{} _, err := r.Run("pwd") Expect(err).To(BeNil()) }) @@ -40,43 +40,43 @@ var _ = Describe("Runner", Label("types", "runner"), func() { It("Sets and gets the logger on the fake runner", func() { r := v2mock.NewFakeRunner() Expect(r.GetLogger()).To(BeNil()) - logger := v2.NewNullLogger() + logger := types.NewNullLogger() r.SetLogger(logger) Expect(r.GetLogger()).To(Equal(logger)) }) It("Sets and gets the logger on the real runner", func() { - r := v2.RealRunner{} + r := types.RealRunner{} Expect(r.GetLogger()).To(BeNil()) - logger := v2.NewNullLogger() + logger := types.NewNullLogger() r.SetLogger(logger) Expect(r.GetLogger()).To(Equal(logger)) }) It("logs the command when on debug", func() { memLog := &bytes.Buffer{} - logger := v2.NewBufferLogger(memLog) - logger.SetLevel(v2.DebugLevel()) - r := v2.RealRunner{Logger: logger} + logger := types.NewBufferLogger(memLog) + logger.SetLevel(types.DebugLevel()) + r := types.RealRunner{Logger: logger} _, err := r.Run("echo", "-n", "Some message") Expect(err).To(BeNil()) Expect(memLog.String()).To(ContainSubstring("echo -n Some message")) }) It("logs when command is not found in debug mode", func() { memLog := &bytes.Buffer{} - logger := v2.NewBufferLogger(memLog) - logger.SetLevel(v2.DebugLevel()) - r := v2.RealRunner{Logger: logger} + logger := types.NewBufferLogger(memLog) + logger.SetLevel(types.DebugLevel()) + r := types.RealRunner{Logger: logger} _, err := r.Run("IAmMissing") Expect(err).NotTo(BeNil()) Expect(memLog.String()).To(ContainSubstring("not found")) }) It("returns false if command does not exists", func() { - r := v2.RealRunner{} + r := types.RealRunner{} exists := r.CommandExists("THISCOMMANDSHOULDNOTBETHERECOMEON") Expect(exists).To(BeFalse()) }) It("returns true if command exists", func() { - r := v2.RealRunner{} + r := types.RealRunner{} exists := r.CommandExists("true") Expect(exists).To(BeTrue()) }) diff --git a/pkg/types/v2/snapshotter.go b/pkg/types/snapshotter.go similarity index 99% rename from pkg/types/v2/snapshotter.go rename to pkg/types/snapshotter.go index 855383760cb..2255e3dafc9 100644 --- a/pkg/types/v2/snapshotter.go +++ b/pkg/types/snapshotter.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "fmt" diff --git a/pkg/types/v2/syscall.go b/pkg/types/syscall.go similarity index 98% rename from pkg/types/v2/syscall.go rename to pkg/types/syscall.go index abe033e44a2..bdde3694d76 100644 --- a/pkg/types/v2/syscall.go +++ b/pkg/types/syscall.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1 +package types import ( "syscall" diff --git a/pkg/types/v2/syscall_test.go b/pkg/types/syscall_test.go similarity index 92% rename from pkg/types/v2/syscall_test.go rename to pkg/types/syscall_test.go index 5a09e552506..454823c0dcb 100644 --- a/pkg/types/v2/syscall_test.go +++ b/pkg/types/syscall_test.go @@ -14,20 +14,20 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1_test +package types_test import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) // unit test stolen from yip var _ = Describe("Syscall", Label("types", "syscall"), func() { It("Calling chroot on the real syscall should fail", func() { - r := v2.RealSyscall{} + r := types.RealSyscall{} err := r.Chroot("/tmp/") // We need elevated privs to chroot so this should fail Expect(err).ToNot(BeNil()) @@ -41,7 +41,7 @@ var _ = Describe("Syscall", Label("types", "syscall"), func() { }) It("Calling chdir on the real syscall should not fail", func() { - r := v2.RealSyscall{} + r := types.RealSyscall{} err := r.Chdir("/tmp/") Expect(err).To(BeNil()) }) diff --git a/pkg/types/v2/types_suite_test.go b/pkg/types/types_suite_test.go similarity index 97% rename from pkg/types/v2/types_suite_test.go rename to pkg/types/types_suite_test.go index 24a2d4cf1fe..290e6dcc56b 100644 --- a/pkg/types/v2/types_suite_test.go +++ b/pkg/types/types_suite_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1_test +package types_test import ( "testing" diff --git a/pkg/utils/chroot.go b/pkg/utils/chroot.go index 8232e07ad07..222c4d7f249 100644 --- a/pkg/utils/chroot.go +++ b/pkg/utils/chroot.go @@ -25,7 +25,7 @@ import ( "strings" "github.com/rancher/elemental-toolkit/v2/pkg/constants" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) // Chroot represents the struct that will allow us to run commands inside a given chroot @@ -34,10 +34,10 @@ type Chroot struct { defaultMounts []string extraMounts map[string]string activeMounts []string - config *v2.Config + config *types.Config } -func NewChroot(path string, config *v2.Config) *Chroot { +func NewChroot(path string, config *types.Config) *Chroot { return &Chroot{ path: path, defaultMounts: []string{"/dev", "/dev/pts", "/proc", "/sys"}, @@ -48,7 +48,7 @@ func NewChroot(path string, config *v2.Config) *Chroot { } // ChrootedCallback runs the given callback in a chroot environment -func ChrootedCallback(cfg *v2.Config, path string, bindMounts map[string]string, callback func() error) error { +func ChrootedCallback(cfg *types.Config, path string, bindMounts map[string]string, callback func() error) error { chroot := NewChroot(path, cfg) chroot.SetExtraMounts(bindMounts) return chroot.RunCallback(callback) diff --git a/pkg/utils/common.go b/pkg/utils/common.go index e72a0201188..77b5f9ff8c2 100644 --- a/pkg/utils/common.go +++ b/pkg/utils/common.go @@ -34,11 +34,11 @@ import ( "github.com/rancher/elemental-toolkit/v2/pkg/constants" elementalError "github.com/rancher/elemental-toolkit/v2/pkg/error" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) // BootedFrom will check if we are booting from the given label -func BootedFrom(runner v2.Runner, label string) bool { +func BootedFrom(runner types.Runner, label string) bool { out, _ := runner.Run("cat", "/proc/cmdline") return strings.Contains(string(out), label) } @@ -46,7 +46,7 @@ func BootedFrom(runner v2.Runner, label string) bool { // GetDeviceByLabel will try to return the device that matches the given label. // attempts value sets the number of attempts to find the device, it // waits a second between attempts. -func GetDeviceByLabel(runner v2.Runner, label string, attempts int) (string, error) { +func GetDeviceByLabel(runner types.Runner, label string, attempts int) (string, error) { part, err := GetFullDeviceByLabel(runner, label, attempts) if err != nil { return "", err @@ -55,8 +55,8 @@ func GetDeviceByLabel(runner v2.Runner, label string, attempts int) (string, err } // GetFullDeviceByLabel works like GetDeviceByLabel, but it will try to get as much info as possible from the existing -// partition and return a v2.Partition object -func GetFullDeviceByLabel(runner v2.Runner, label string, attempts int) (*v2.Partition, error) { +// partition and return a types.Partition object +func GetFullDeviceByLabel(runner types.Runner, label string, attempts int) (*types.Partition, error) { for tries := 0; tries < attempts; tries++ { _, _ = runner.Run("udevadm", "settle") parts, err := GetAllPartitions() @@ -75,7 +75,7 @@ func GetFullDeviceByLabel(runner v2.Runner, label string, attempts int) (*v2.Par // CopyFile Copies source file to target file using Fs interface. If target // is directory source is copied into that directory using source name file. // File mode is preserved -func CopyFile(fs v2.FS, source string, target string) error { +func CopyFile(fs types.FS, source string, target string) error { return ConcatFiles(fs, []string{source}, target) } @@ -83,7 +83,7 @@ func CopyFile(fs v2.FS, source string, target string) error { // Source files are concatenated into target file in the given order. // If target is a directory source is copied into that directory using // 1st source name file. The result keeps the file mode of the 1st source. -func ConcatFiles(fs v2.FS, sources []string, target string) (err error) { +func ConcatFiles(fs types.FS, sources []string, target string) (err error) { if len(sources) == 0 { return fmt.Errorf("Empty sources list") } @@ -128,7 +128,7 @@ func ConcatFiles(fs v2.FS, sources []string, target string) (err error) { // CreateDirStructure creates essentials directories under the root tree that might not be present // within a container image (/dev, /run, etc.) -func CreateDirStructure(fs v2.FS, target string) error { +func CreateDirStructure(fs types.FS, target string) error { for _, dir := range []string{"/run", "/dev", "/boot", "/oem", "/system", "/etc/elemental/config.d"} { err := MkdirAll(fs, filepath.Join(target, dir), constants.DirPerm) if err != nil { @@ -155,7 +155,7 @@ func CreateDirStructure(fs v2.FS, target string) error { // SyncData rsync's source folder contents to a target folder content, // both are expected to exist before hand. -func SyncData(log v2.Logger, runner v2.Runner, fs v2.FS, source string, target string, excludes ...string) error { +func SyncData(log types.Logger, runner types.Runner, fs types.FS, source string, target string, excludes ...string) error { flags := []string{"--progress", "--partial", "--human-readable", "--archive", "--xattrs", "--acls"} for _, e := range excludes { flags = append(flags, fmt.Sprintf("--exclude=%s", e)) @@ -166,7 +166,7 @@ func SyncData(log v2.Logger, runner v2.Runner, fs v2.FS, source string, target s // MirrorData rsync's source folder contents to a target folder content, in contrast, to SyncData this // method includes the --delete flag which forces the deletion of files in target that are missing in source. -func MirrorData(log v2.Logger, runner v2.Runner, fs v2.FS, source string, target string, excludes ...string) error { +func MirrorData(log types.Logger, runner types.Runner, fs types.FS, source string, target string, excludes ...string) error { flags := []string{"--progress", "--partial", "--human-readable", "--archive", "--xattrs", "--acls", "--delete"} for _, e := range excludes { flags = append(flags, fmt.Sprintf("--exclude=%s", e)) @@ -175,7 +175,7 @@ func MirrorData(log v2.Logger, runner v2.Runner, fs v2.FS, source string, target return rsyncWrapper(log, runner, fs, source, target, flags) } -func rsyncWrapper(log v2.Logger, runner v2.Runner, fs v2.FS, source string, target string, flags []string) error { +func rsyncWrapper(log types.Logger, runner types.Runner, fs types.FS, source string, target string, flags []string) error { if fs != nil { if s, err := fs.RawPath(source); err == nil { source = s @@ -212,7 +212,7 @@ func rsyncWrapper(log v2.Logger, runner v2.Runner, fs v2.FS, source string, targ return nil } -func displayProgress(log v2.Logger, tick time.Duration, message string) chan bool { +func displayProgress(log types.Logger, tick time.Duration, message string) chan bool { ticker := time.NewTicker(tick) done := make(chan bool) @@ -232,14 +232,14 @@ func displayProgress(log v2.Logger, tick time.Duration, message string) chan boo } // Reboot reboots the system after the given delay (in seconds) time passed. -func Reboot(runner v2.Runner, delay time.Duration) error { +func Reboot(runner types.Runner, delay time.Duration) error { time.Sleep(delay * time.Second) _, err := runner.Run("reboot", "-f") return err } // Shutdown halts the system after the given delay (in seconds) time passed. -func Shutdown(runner v2.Runner, delay time.Duration) error { +func Shutdown(runner types.Runner, delay time.Duration) error { time.Sleep(delay * time.Second) _, err := runner.Run("poweroff", "-f") return err @@ -247,7 +247,7 @@ func Shutdown(runner v2.Runner, delay time.Duration) error { // CosignVerify runs a cosign validation for the give image and given public key. If no // key is provided then it attempts a keyless validation (experimental feature). -func CosignVerify(fs v2.FS, runner v2.Runner, image string, publicKey string, debug bool) (string, error) { +func CosignVerify(fs types.FS, runner types.Runner, image string, publicKey string, debug bool) (string, error) { args := []string{} if debug { @@ -267,7 +267,7 @@ func CosignVerify(fs v2.FS, runner v2.Runner, image string, publicKey string, de return "", err } _ = os.Setenv("TUF_ROOT", tmpDir) - defer func(fs v2.FS, path string) { + defer func(fs types.FS, path string) { _ = fs.RemoveAll(path) }(fs, tmpDir) defer func() { @@ -280,7 +280,7 @@ func CosignVerify(fs v2.FS, runner v2.Runner, image string, publicKey string, de // CreateSquashFS creates a squash file at destination from a source, with options // TODO: Check validity of source maybe? -func CreateSquashFS(runner v2.Runner, logger v2.Logger, source string, destination string, options []string) error { +func CreateSquashFS(runner types.Runner, logger types.Logger, source string, destination string, options []string) error { // create args args := []string{source, destination} // append options passed to args in order to have the correct order @@ -300,7 +300,7 @@ func CreateSquashFS(runner v2.Runner, logger v2.Logger, source string, destinati } // LoadEnvFile will try to parse the file given and return a map with the key/values -func LoadEnvFile(fs v2.FS, file string) (map[string]string, error) { +func LoadEnvFile(fs types.FS, file string) (map[string]string, error) { var envMap map[string]string var err error @@ -319,7 +319,7 @@ func LoadEnvFile(fs v2.FS, file string) (map[string]string, error) { } // WriteEnvFile will write the given environment file with the given key/values -func WriteEnvFile(fs v2.FS, envs map[string]string, filename string) error { +func WriteEnvFile(fs types.FS, envs map[string]string, filename string) error { var bkFile string rawPath, err := fs.RawPath(filename) @@ -385,7 +385,7 @@ func IsHTTPURI(uri string) (bool, error) { // GetSource copies given source to destination, if source is a local path it simply // copies files, if source is a remote URL it tries to download URL to destination. -func GetSource(config v2.Config, source string, destination string) error { +func GetSource(config types.Config, source string, destination string) error { local, err := IsLocalURI(source) if err != nil { config.Logger.Errorf("Not a valid url: %s", source) @@ -435,7 +435,7 @@ func ValidTaggedContainerReference(ref string) bool { // FindFile attempts to find a file from a list of patterns on top of a given root path. // Returns first match if any and returns error otherwise. -func FindFile(vfs v2.FS, rootDir string, patterns ...string) (string, error) { +func FindFile(vfs types.FS, rootDir string, patterns ...string) (string, error) { var err error var found string @@ -455,7 +455,7 @@ func FindFile(vfs v2.FS, rootDir string, patterns ...string) (string, error) { // findFile attempts to find a file from a given pattern on top of a root path. // Returns empty path if no file is found. -func findFile(vfs v2.FS, rootDir, pattern string) (string, error) { +func findFile(vfs types.FS, rootDir, pattern string) (string, error) { var foundFile string base := filepath.Join(rootDir, getBaseDir(pattern)) if ok, _ := Exists(vfs, base); ok { @@ -485,7 +485,7 @@ func findFile(vfs v2.FS, rootDir, pattern string) (string, error) { // FindKernel finds for kernel files inside a given root tree path. // Returns kernel file and version. It assumes kernel files match certain patterns -func FindKernel(fs v2.FS, rootDir string) (string, string, error) { +func FindKernel(fs types.FS, rootDir string) (string, string, error) { var kernel, version string var err error @@ -511,7 +511,7 @@ func FindKernel(fs v2.FS, rootDir string) (string, string, error) { // FindInitrd finds for initrd files inside a given root tree path. // It assumes initrd files match certain patterns -func FindInitrd(fs v2.FS, rootDir string) (string, error) { +func FindInitrd(fs types.FS, rootDir string) (string, error) { initrd, err := FindFile(fs, rootDir, constants.GetInitrdPatterns()...) if err != nil { return "", fmt.Errorf("No initrd file found: %v", err) @@ -522,7 +522,7 @@ func FindInitrd(fs v2.FS, rootDir string) (string, error) { // FindKernelInitrd finds for kernel and intird files inside a given root tree path. // It assumes kernel and initrd files match certain patterns. // This is a comodity method of a combination of FindKernel and FindInitrd. -func FindKernelInitrd(fs v2.FS, rootDir string) (kernel string, initrd string, err error) { +func FindKernelInitrd(fs types.FS, rootDir string) (kernel string, initrd string, err error) { kernel, _, err = FindKernel(fs, rootDir) if err != nil { return "", "", err @@ -546,7 +546,7 @@ func getBaseDir(path string) string { // resolveLink attempts to resolve a symlink, if any. Returns the original given path // if not a symlink. In case of error returns error and the original given path. -func resolveLink(vfs v2.FS, path string, rootDir string, d fs.DirEntry, depth int) (string, error) { +func resolveLink(vfs types.FS, path string, rootDir string, d fs.DirEntry, depth int) (string, error) { var err error var resolved string var f fs.FileInfo @@ -579,7 +579,7 @@ func resolveLink(vfs v2.FS, path string, rootDir string, d fs.DirEntry, depth in // ResolveLink attempts to resolve a symlink, if any. Returns the original given path // if not a symlink or if it can't be resolved. -func ResolveLink(vfs v2.FS, path string, rootDir string, depth int) (string, error) { +func ResolveLink(vfs types.FS, path string, rootDir string, depth int) (string, error) { f, err := vfs.Lstat(path) if err != nil { return path, err @@ -589,7 +589,7 @@ func ResolveLink(vfs v2.FS, path string, rootDir string, depth int) (string, err } // CalcFileChecksum opens the given file and returns the sha256 checksum of it. -func CalcFileChecksum(fs v2.FS, fileName string) (string, error) { +func CalcFileChecksum(fs types.FS, fileName string) (string, error) { f, err := fs.Open(fileName) if err != nil { return "", err @@ -605,7 +605,7 @@ func CalcFileChecksum(fs v2.FS, fileName string) (string, error) { } // CreateRAWFile creates raw file of the given size in MB -func CreateRAWFile(fs v2.FS, filename string, size uint) error { +func CreateRAWFile(fs types.FS, filename string, size uint) error { f, err := fs.Create(filename) if err != nil { return elementalError.NewFromError(err, elementalError.CreateFile) diff --git a/pkg/utils/fs.go b/pkg/utils/fs.go index d313d677524..fb5c3567dfb 100644 --- a/pkg/utils/fs.go +++ b/pkg/utils/fs.go @@ -34,11 +34,11 @@ import ( "github.com/twpayne/go-vfs/v4" "github.com/twpayne/go-vfs/v4/vfst" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) // DirSize returns the accumulated size of all files in folder. Result in bytes -func DirSize(fs v2.FS, path string, excludes ...string) (int64, error) { +func DirSize(fs types.FS, path string, excludes ...string) (int64, error) { var size int64 err := vfs.Walk(fs, path, func(loopPath string, info os.FileInfo, err error) error { if err != nil { @@ -60,7 +60,7 @@ func DirSize(fs v2.FS, path string, excludes ...string) (int64, error) { } // DirSizeMB returns the accumulated size of all files in folder. Result in Megabytes -func DirSizeMB(fs v2.FS, path string, excludes ...string) (uint, error) { +func DirSizeMB(fs types.FS, path string, excludes ...string) (uint, error) { size, err := DirSize(fs, path, excludes...) if err != nil { return 0, err @@ -76,7 +76,7 @@ func DirSizeMB(fs v2.FS, path string, excludes ...string) (uint, error) { // Check if a file or directory exists. noFollow flag determines to // not follow symlinks to check files existance. -func Exists(fs v2.FS, path string, noFollow ...bool) (bool, error) { +func Exists(fs types.FS, path string, noFollow ...bool) (bool, error) { var err error if len(noFollow) > 0 && noFollow[0] { _, err = fs.Lstat(path) @@ -93,7 +93,7 @@ func Exists(fs v2.FS, path string, noFollow ...bool) (bool, error) { } // IsDir check if the path is a dir -func IsDir(fs v2.FS, path string) (bool, error) { +func IsDir(fs types.FS, path string) (bool, error) { fi, err := fs.Stat(path) if err != nil { return false, err @@ -102,7 +102,7 @@ func IsDir(fs v2.FS, path string) (bool, error) { } // MkdirAll directory and all parents if not existing -func MkdirAll(fs v2.FS, name string, mode os.FileMode) (err error) { +func MkdirAll(fs types.FS, name string, mode os.FileMode) (err error) { if _, isReadOnly := fs.(*vfs.ReadOnlyFS); isReadOnly { return permError("mkdir", name) } @@ -113,7 +113,7 @@ func MkdirAll(fs v2.FS, name string, mode os.FileMode) (err error) { } // readlink calls fs.Readlink but trims temporary prefix on Readlink result -func readlink(fs v2.FS, name string) (string, error) { +func readlink(fs types.FS, name string) (string, error) { res, err := fs.Readlink(name) if err != nil { return res, err @@ -158,7 +158,7 @@ func nextRandom() string { // TempDir creates a temp file in the virtual fs // Took from afero.FS code and adapted -func TempDir(fs v2.FS, dir, prefix string) (name string, err error) { +func TempDir(fs types.FS, dir, prefix string) (name string, err error) { if dir == "" { dir = os.TempDir() } @@ -193,7 +193,7 @@ func TempDir(fs v2.FS, dir, prefix string) (name string, err error) { // TempFile creates a temp file in the virtual fs // Took from afero.FS code and adapted -func TempFile(fs v2.FS, dir, pattern string) (f *os.File, err error) { +func TempFile(fs types.FS, dir, pattern string) (f *os.File, err error) { if dir == "" { dir = os.TempDir() } @@ -232,8 +232,8 @@ func (d *statDirEntry) IsDir() bool { return d.info.IsDir() } func (d *statDirEntry) Type() fs.FileMode { return d.info.Mode().Type() } func (d *statDirEntry) Info() (fs.FileInfo, error) { return d.info, nil } -// WalkDirFs is the same as filepath.WalkDir but accepts a v2.Fs so it can be run on any v2.Fs type -func WalkDirFs(fs v2.FS, root string, fn fs.WalkDirFunc) error { +// WalkDirFs is the same as filepath.WalkDir but accepts a types.Fs so it can be run on any types.Fs type +func WalkDirFs(fs types.FS, root string, fn fs.WalkDirFunc) error { info, err := fs.Stat(root) if err != nil { err = fn(root, nil, err) @@ -246,7 +246,7 @@ func WalkDirFs(fs v2.FS, root string, fn fs.WalkDirFunc) error { return err } -func walkDir(fs v2.FS, path string, d fs.DirEntry, walkDirFn fs.WalkDirFunc) error { +func walkDir(fs types.FS, path string, d fs.DirEntry, walkDirFn fs.WalkDirFunc) error { if err := walkDirFn(path, d, nil); err != nil || !d.IsDir() { if err == filepath.SkipDir && d.IsDir() { // Successfully skipped directory. @@ -276,7 +276,7 @@ func walkDir(fs v2.FS, path string, d fs.DirEntry, walkDirFn fs.WalkDirFunc) err return nil } -func readDir(vfs v2.FS, dirname string) ([]fs.DirEntry, error) { +func readDir(vfs types.FS, dirname string) ([]fs.DirEntry, error) { dirs, err := vfs.ReadDir(dirname) if err != nil { return nil, err diff --git a/pkg/utils/getpartitions.go b/pkg/utils/getpartitions.go index 941ea44078c..f40d55c2dd5 100644 --- a/pkg/utils/getpartitions.go +++ b/pkg/utils/getpartitions.go @@ -25,12 +25,12 @@ import ( "github.com/jaypipes/ghw/pkg/block" ghwUtil "github.com/jaypipes/ghw/pkg/util" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) -// ghwPartitionToInternalPartition transforms a block.Partition from ghw lib to our v2.Partition type -func ghwPartitionToInternalPartition(partition *block.Partition) *v2.Partition { - return &v2.Partition{ +// ghwPartitionToInternalPartition transforms a block.Partition from ghw lib to our types.Partition type +func ghwPartitionToInternalPartition(partition *block.Partition) *types.Partition { + return &types.Partition{ FilesystemLabel: partition.FilesystemLabel, Size: uint(partition.SizeBytes / (1024 * 1024)), // Converts B to MB Name: partition.Label, @@ -43,8 +43,8 @@ func ghwPartitionToInternalPartition(partition *block.Partition) *v2.Partition { } // GetAllPartitions returns all partitions in the system for all disks -func GetAllPartitions() (v2.PartitionList, error) { - var parts []*v2.Partition +func GetAllPartitions() (types.PartitionList, error) { + var parts []*types.Partition blockDevices, err := block.New(ghw.WithDisableTools(), ghw.WithDisableWarnings()) if err != nil { return nil, err diff --git a/pkg/utils/runstage.go b/pkg/utils/runstage.go index 643bf66f682..60fc4031d1d 100644 --- a/pkg/utils/runstage.go +++ b/pkg/utils/runstage.go @@ -24,7 +24,7 @@ import ( "github.com/rancher/yip/pkg/schema" "gopkg.in/yaml.v3" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" ) func onlyYAMLPartialErrors(er error) bool { @@ -43,7 +43,7 @@ func onlyYAMLPartialErrors(er error) bool { return true } -func checkYAMLError(cfg *v2.Config, allErrors, err error) error { +func checkYAMLError(cfg *types.Config, allErrors, err error) error { if !onlyYAMLPartialErrors(err) { // here we absorb errors only if are related to YAML unmarshalling // As cmdline is parsed out as a yaml file @@ -57,7 +57,7 @@ func checkYAMLError(cfg *v2.Config, allErrors, err error) error { } // RunStage will run yip -func RunStage(cfg *v2.Config, stage string, strict bool, cloudInitPaths ...string) error { +func RunStage(cfg *types.Config, stage string, strict bool, cloudInitPaths ...string) error { var allErrors error cfg.Logger.Debugf("Cloud-init paths set to %v", cloudInitPaths) @@ -118,7 +118,7 @@ func RunStage(cfg *v2.Config, stage string, strict bool, cloudInitPaths ...strin // filterNonExistingLocalURIs attempts to remove non existing local paths from the given URI slice. // Returns the filtered slice. -func filterNonExistingLocalURIs(cfg *v2.Config, uris ...string) []string { +func filterNonExistingLocalURIs(cfg *types.Config, uris ...string) []string { filteredPaths := []string{} for _, cp := range uris { if local, _ := IsLocalURI(cp); local { diff --git a/pkg/utils/runstage_test.go b/pkg/utils/runstage_test.go index 247cb03d8c0..60203acbfe1 100644 --- a/pkg/utils/runstage_test.go +++ b/pkg/utils/runstage_test.go @@ -31,7 +31,7 @@ import ( conf "github.com/rancher/elemental-toolkit/v2/pkg/config" "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -42,7 +42,7 @@ stages: - echo "I have a very bad feeling about this" ` -func writeCmdline(s string, fs v2.FS) error { +func writeCmdline(s string, fs types.FS) error { if err := fs.Mkdir("/proc", os.ModePerm); err != nil { return err } @@ -50,9 +50,9 @@ func writeCmdline(s string, fs v2.FS) error { } var _ = Describe("run stage", Label("RunStage"), func() { - var config *v2.Config + var config *types.Config var runner *v2mock.FakeRunner - var logger v2.Logger + var logger types.Logger var syscall *v2mock.FakeSyscall var client *v2mock.FakeHTTPClient var mounter *v2mock.FakeMounter @@ -68,7 +68,7 @@ var _ = Describe("run stage", Label("RunStage"), func() { // Use a different config with a buffer for logger, so we can check the output // We also use the real fs memLog = &bytes.Buffer{} - logger = v2.NewBufferLogger(memLog) + logger = types.NewBufferLogger(memLog) fs, cleanup, _ = vfst.NewTestFS(nil) config = conf.NewConfig( diff --git a/pkg/utils/utils_test.go b/pkg/utils/utils_test.go index eb0b7f6782b..a69129f4094 100644 --- a/pkg/utils/utils_test.go +++ b/pkg/utils/utils_test.go @@ -37,7 +37,7 @@ import ( conf "github.com/rancher/elemental-toolkit/v2/pkg/config" "github.com/rancher/elemental-toolkit/v2/pkg/constants" v2mock "github.com/rancher/elemental-toolkit/v2/pkg/mocks" - v2 "github.com/rancher/elemental-toolkit/v2/pkg/types/v2" + "github.com/rancher/elemental-toolkit/v2/pkg/types" "github.com/rancher/elemental-toolkit/v2/pkg/utils" ) @@ -50,10 +50,10 @@ func getNamesFromListFiles(list []fs.DirEntry) []string { } var _ = Describe("Utils", Label("utils"), func() { - var config *v2.Config + var config *types.Config var runner *v2mock.FakeRunner - var realRunner *v2.RealRunner - var logger v2.Logger + var realRunner *types.RealRunner + var logger types.Logger var syscall *v2mock.FakeSyscall var client *v2mock.FakeHTTPClient var mounter *v2mock.FakeMounter @@ -66,8 +66,8 @@ var _ = Describe("Utils", Label("utils"), func() { syscall = &v2mock.FakeSyscall{} mounter = v2mock.NewFakeMounter() client = &v2mock.FakeHTTPClient{} - logger = v2.NewNullLogger() - realRunner = &v2.RealRunner{Logger: logger} + logger = types.NewNullLogger() + realRunner = &types.RealRunner{Logger: logger} extractor = v2mock.NewFakeImageExtractor(logger) // Ensure /tmp exists in the VFS fs, cleanup, _ = vfst.NewTestFS(nil) @@ -338,7 +338,7 @@ var _ = Describe("Utils", Label("utils"), func() { {"udevadm", "settle"}, } }) - It("returns found v2.Partition", func() { + It("returns found types.Partition", func() { var flags []string ghwTest := v2mock.GhwMock{} disk := block.Disk{Name: "device", Partitions: []*block.Partition{