From 1819ee173f2570b62b465aa8b154ef6edef7b991 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Wed, 26 Jun 2024 19:29:44 -0400 Subject: [PATCH 01/37] feat(wip): allow finch to build on Linux without Lima Signed-off-by: Justin Alvarez --- Makefile | 13 +- cmd/finch/lima_args_windows.go | 20 -- cmd/finch/main_darwin.go | 2 +- cmd/finch/main_native.go | 28 ++ cmd/finch/nerdctl.go | 25 +- cmd/finch/nerdctl_darwin.go | 6 +- cmd/finch/nerdctl_native.go | 29 ++ cmd/finch/nerdctl_remote.go | 36 ++ cmd/finch/nerdctl_shared_test.go | 2 + cmd/finch/nerdctl_windows.go | 14 + cmd/finch/support_bundle.go | 17 - ...rgs_darwin.go => support_bundle_native.go} | 6 +- cmd/finch/support_bundle_remote.go | 26 ++ cmd/finch/support_bundle_test.go | 332 ------------------ cmd/finch/version.go | 37 -- cmd/finch/version_native.go | 36 ++ cmd/finch/version_remote.go | 48 +++ cmd/finch/version_test.go | 2 + cmd/finch/virtual_machine_init.go | 2 + cmd/finch/virtual_machine_init_test.go | 2 + cmd/finch/virtual_machine_local.go | 29 ++ ...l_machine.go => virtual_machine_remote.go} | 2 + cmd/finch/virtual_machine_remove.go | 2 + cmd/finch/virtual_machine_remove_test.go | 2 + cmd/finch/virtual_machine_settings.go | 2 + cmd/finch/virtual_machine_settings_test.go | 2 + cmd/finch/virtual_machine_start.go | 2 + cmd/finch/virtual_machine_start_test.go | 2 + cmd/finch/virtual_machine_status.go | 2 + cmd/finch/virtual_machine_status_test.go | 2 + cmd/finch/virtual_machine_stop.go | 2 + cmd/finch/virtual_machine_stop_test.go | 2 + cmd/finch/virtual_machine_test.go | 2 + pkg/command/{lima.go => nerdctl.go} | 31 -- pkg/command/nerdctl_native.go | 41 +++ pkg/command/nerdctl_remote.go | 41 +++ pkg/command/{lima_test.go => nerdctl_test.go} | 0 ...lima_unix_test.go => nerdctl_unix_test.go} | 0 ...indows_test.go => nerdctl_windows_test.go} | 0 pkg/config/config.go | 67 +--- pkg/config/config_darwin.go | 53 +++ pkg/config/config_native.go | 10 + pkg/config/config_test.go | 2 + pkg/config/config_windows.go | 13 + pkg/config/defaults_linux.go | 21 ++ pkg/config/defaults_test.go | 2 + pkg/config/lima_config_applier.go | 249 ------------- pkg/config/lima_config_applier_darwin.go | 22 +- pkg/config/lima_config_applier_native.go | 52 +++ pkg/config/lima_config_applier_remote.go | 252 +++++++++++++ pkg/config/lima_config_applier_windows.go | 14 +- pkg/config/nerdctl_config_applier.go | 115 +----- pkg/config/nerdctl_config_applier_native.go | 23 ++ pkg/config/nerdctl_config_applier_remote.go | 123 +++++++ pkg/config/nerdctl_config_applier_test.go | 2 + pkg/config/validate_darwin.go | 2 +- pkg/config/validate_natvie.go | 15 + pkg/config/validate_windows.go | 2 +- pkg/disk/{disk_unix.go => disk_darwin.go} | 4 +- ...{disk_unix_test.go => disk_darwin_test.go} | 2 +- pkg/disk/disk_native.go | 25 ++ 61 files changed, 1027 insertions(+), 892 deletions(-) delete mode 100644 cmd/finch/lima_args_windows.go create mode 100644 cmd/finch/main_native.go create mode 100644 cmd/finch/nerdctl_native.go create mode 100644 cmd/finch/nerdctl_remote.go rename cmd/finch/{lima_args_darwin.go => support_bundle_native.go} (50%) create mode 100644 cmd/finch/support_bundle_remote.go delete mode 100644 cmd/finch/support_bundle_test.go create mode 100644 cmd/finch/version_native.go create mode 100644 cmd/finch/version_remote.go create mode 100644 cmd/finch/virtual_machine_local.go rename cmd/finch/{virtual_machine.go => virtual_machine_remote.go} (99%) rename pkg/command/{lima.go => nerdctl.go} (81%) create mode 100644 pkg/command/nerdctl_native.go create mode 100644 pkg/command/nerdctl_remote.go rename pkg/command/{lima_test.go => nerdctl_test.go} (100%) rename pkg/command/{lima_unix_test.go => nerdctl_unix_test.go} (100%) rename pkg/command/{lima_windows_test.go => nerdctl_windows_test.go} (100%) create mode 100644 pkg/config/config_native.go create mode 100644 pkg/config/defaults_linux.go create mode 100644 pkg/config/lima_config_applier_native.go create mode 100644 pkg/config/lima_config_applier_remote.go create mode 100644 pkg/config/nerdctl_config_applier_native.go create mode 100644 pkg/config/nerdctl_config_applier_remote.go create mode 100644 pkg/config/validate_natvie.go rename pkg/disk/{disk_unix.go => disk_darwin.go} (99%) rename pkg/disk/{disk_unix_test.go => disk_darwin_test.go} (99%) create mode 100644 pkg/disk/disk_native.go diff --git a/Makefile b/Makefile index 13a9fc713..0f384e941 100644 --- a/Makefile +++ b/Makefile @@ -73,8 +73,10 @@ arch-test: .PHONY: all ifeq ($(GOOS),windows) all: arch-test finch finch-core-local finch.windows.yaml networks.yaml config.yaml -else +else ifeq ($(GOOS),darwin) all: arch-test finch finch-core finch.yaml networks.yaml config.yaml lima-and-qemu +else ifeq ($(GOOS),linux) +all: finch endif .PHONY: all-local @@ -206,8 +208,10 @@ ifeq ($(GOOS),windows) finch: finch-windows finch-general else ifeq ($(GOOS),darwin) finch: finch-macos +else ifeq ($(GOOS),linux) +finch: finch-native else -finch: finch-unix +finch: finch-general endif finch-windows: @@ -220,8 +224,11 @@ finch-macos: finch-unix finch-unix: finch-general +finch-native: GO_BUILD_TAGS += "native" +finch-native: finch-general + finch-general: - $(GO) build -ldflags $(LDFLAGS) -o $(OUTDIR)/bin/$(BINARYNAME) $(PACKAGE)/cmd/finch + $(GO) build -ldflags $(LDFLAGS) -tags $(GO_BUILD_TAGS) -o $(OUTDIR)/bin/$(BINARYNAME) $(PACKAGE)/cmd/finch .PHONY: release release: check-licenses all download-licenses diff --git a/cmd/finch/lima_args_windows.go b/cmd/finch/lima_args_windows.go deleted file mode 100644 index 34e7a13ab..000000000 --- a/cmd/finch/lima_args_windows.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -//go:build windows - -package main - -func (nc *nerdctlCommand) GetLimaArgs() []string { - wd, err := nc.systemDeps.GetWd() - if err != nil { - nc.logger.Warnln("failed to get working directory, will default to user home with error %s", err.Error()) - return []string{"shell", limaInstanceName, "sudo", "-E"} - } - wslPath, err := convertToWSLPath(nc.systemDeps, wd) - if err != nil { - nc.logger.Warnln("failed to convert to WSL path, will default to user home with error %s", err.Error()) - return []string{"shell", limaInstanceName, "sudo", "-E"} - } - return []string{"shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E"} -} diff --git a/cmd/finch/main_darwin.go b/cmd/finch/main_darwin.go index e6614a404..c694160c9 100644 --- a/cmd/finch/main_darwin.go +++ b/cmd/finch/main_darwin.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin +//go:build darwin && !native package main diff --git a/cmd/finch/main_native.go b/cmd/finch/main_native.go new file mode 100644 index 000000000..82be5fcd0 --- /dev/null +++ b/cmd/finch/main_native.go @@ -0,0 +1,28 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux || native + +package main + +import ( + "github.com/spf13/afero" + + "github.com/runfinch/finch/pkg/command" + "github.com/runfinch/finch/pkg/config" + "github.com/runfinch/finch/pkg/dependency" + "github.com/runfinch/finch/pkg/flog" + "github.com/runfinch/finch/pkg/path" +) + +func dependencies( + _ command.Creator, + _ *config.Finch, + _ path.Finch, + _ afero.Fs, + _ command.LimaCmdCreator, + _ flog.Logger, + _ string, +) []*dependency.Group { + return []*dependency.Group{} +} diff --git a/cmd/finch/nerdctl.go b/cmd/finch/nerdctl.go index f3631713c..fc16a4193 100644 --- a/cmd/finch/nerdctl.go +++ b/cmd/finch/nerdctl.go @@ -19,7 +19,6 @@ import ( "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/config" "github.com/runfinch/finch/pkg/flog" - "github.com/runfinch/finch/pkg/lima" "github.com/runfinch/finch/pkg/system" "k8s.io/apimachinery/pkg/util/sets" @@ -261,7 +260,7 @@ func (nc *nerdctlCommand) run(cmdName string, args []string) error { // Add -E to sudo command in order to preserve existing environment variables, more info: // https://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo/8633575#8633575 - limaArgs := append(nc.GetLimaArgs(), append(additionalEnv, passedEnvArgs...)...) + limaArgs := append(nc.GetCmdArgs(), append(additionalEnv, passedEnvArgs...)...) limaArgs = append(limaArgs, append([]string{nerdctlCmdName}, strings.Fields(cmdName)...)...) @@ -283,28 +282,6 @@ func (nc *nerdctlCommand) run(cmdName string, args []string) error { return nc.lcc.Create(limaArgs...).Run() } -func (nc *nerdctlCommand) assertVMIsRunning(creator command.LimaCmdCreator, logger flog.Logger) error { - // Extra call to check VM before running nerdctl commands. These are the reasons of not doing message replacing - // 1. for the non-help commands, replacing stdout may cause "stdin is not a terminal" error for the commands that need input. - // E.g. finch login. - // 2. an extra call could give us more control about the error messages. Message replacing may fail if upstream - // changes the format of source string, which leads to extra CI validation work. - status, err := lima.GetVMStatus(creator, logger, limaInstanceName) - if err != nil { - return err - } - switch status { - case lima.Nonexistent: - return fmt.Errorf("instance %q does not exist, run `finch %s init` to create a new instance", - limaInstanceName, virtualMachineRootCmd) - case lima.Stopped: - return fmt.Errorf("instance %q is stopped, run `finch %s start` to start the instance", - limaInstanceName, virtualMachineRootCmd) - default: - return nil - } -} - // shouldReplaceForHelp returns true if we should replace "nerdctl" with "finch" for the output of the given command. func (nc *nerdctlCommand) shouldReplaceForHelp(cmdName string, args []string) bool { // The implicit help commands mean that if users input "finch" without any args, it will return the help of it. diff --git a/cmd/finch/nerdctl_darwin.go b/cmd/finch/nerdctl_darwin.go index e7f9979c9..0d6ef6632 100644 --- a/cmd/finch/nerdctl_darwin.go +++ b/cmd/finch/nerdctl_darwin.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin +//go:build darwin && !native package main @@ -22,6 +22,10 @@ var argHandlerMap = map[string]map[string]argHandler{} var commandHandlerMap = map[string]commandHandler{} +func (nc *nerdctlCommand) GetCmdArgs() []string { + return []string{"shell", limaInstanceName, "sudo", "-E"} +} + func resolveIP(host string, logger flog.Logger, _ command.Creator) (string, error) { parts := strings.SplitN(host, ":", 2) // If the IP Address is a string called "host-gateway", replace this value with the IP address that can be used to diff --git a/cmd/finch/nerdctl_native.go b/cmd/finch/nerdctl_native.go new file mode 100644 index 000000000..770a93dec --- /dev/null +++ b/cmd/finch/nerdctl_native.go @@ -0,0 +1,29 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux || native + +package main + +import ( + "github.com/runfinch/finch/pkg/command" + "github.com/runfinch/finch/pkg/flog" +) + +var aliasMap = map[string]string{} + +var argHandlerMap = map[string]map[string]argHandler{} + +var commandHandlerMap = map[string]commandHandler{} + +func (nc *nerdctlCommand) GetCmdArgs() []string { + return []string{""} +} + +func (nc *nerdctlCommand) assertVMIsRunning(creator command.LimaCmdCreator, logger flog.Logger) error { + return nil +} + +func resolveIP(host string, logger flog.Logger, _ command.Creator) (string, error) { + return "0.0.0.0", nil +} diff --git a/cmd/finch/nerdctl_remote.go b/cmd/finch/nerdctl_remote.go new file mode 100644 index 000000000..b5282ce89 --- /dev/null +++ b/cmd/finch/nerdctl_remote.go @@ -0,0 +1,36 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build (darwin || windows) && !native + +package main + +import ( + "fmt" + + "github.com/runfinch/finch/pkg/command" + "github.com/runfinch/finch/pkg/flog" + "github.com/runfinch/finch/pkg/lima" +) + +func (nc *nerdctlCommand) assertVMIsRunning(creator command.LimaCmdCreator, logger flog.Logger) error { + // Extra call to check VM before running nerdctl commands. These are the reasons of not doing message replacing + // 1. for the non-help commands, replacing stdout may cause "stdin is not a terminal" error for the commands that need input. + // E.g. finch login. + // 2. an extra call could give us more control about the error messages. Message replacing may fail if upstream + // changes the format of source string, which leads to extra CI validation work. + status, err := lima.GetVMStatus(creator, logger, limaInstanceName) + if err != nil { + return err + } + switch status { + case lima.Nonexistent: + return fmt.Errorf("instance %q does not exist, run `finch %s init` to create a new instance", + limaInstanceName, virtualMachineRootCmd) + case lima.Stopped: + return fmt.Errorf("instance %q is stopped, run `finch %s start` to start the instance", + limaInstanceName, virtualMachineRootCmd) + default: + return nil + } +} diff --git a/cmd/finch/nerdctl_shared_test.go b/cmd/finch/nerdctl_shared_test.go index c09500140..b12a8b6f9 100644 --- a/cmd/finch/nerdctl_shared_test.go +++ b/cmd/finch/nerdctl_shared_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package main import ( diff --git a/cmd/finch/nerdctl_windows.go b/cmd/finch/nerdctl_windows.go index e1f794605..26bcf26d0 100644 --- a/cmd/finch/nerdctl_windows.go +++ b/cmd/finch/nerdctl_windows.go @@ -15,6 +15,20 @@ import ( "github.com/runfinch/finch/pkg/flog" ) +func (nc *nerdctlCommand) GetCmdArgs() []string { + wd, err := nc.systemDeps.GetWd() + if err != nil { + nc.logger.Warnln("failed to get working directory, will default to user home with error %s", err.Error()) + return []string{"shell", limaInstanceName, "sudo", "-E"} + } + wslPath, err := convertToWSLPath(nc.systemDeps, wd) + if err != nil { + nc.logger.Warnln("failed to convert to WSL path, will default to user home with error %s", err.Error()) + return []string{"shell", limaInstanceName, "sudo", "-E"} + } + return []string{"shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E"} +} + func convertToWSLPath(systemDeps NerdctlCommandSystemDeps, winPath string) (string, error) { path, err := systemDeps.FilePathAbs(filepath.Clean(winPath)) if err != nil { diff --git a/cmd/finch/support_bundle.go b/cmd/finch/support_bundle.go index 39062ff0c..541d59c98 100644 --- a/cmd/finch/support_bundle.go +++ b/cmd/finch/support_bundle.go @@ -4,13 +4,10 @@ package main import ( - "fmt" - "github.com/spf13/cobra" "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/flog" - "github.com/runfinch/finch/pkg/lima" "github.com/runfinch/finch/pkg/support" ) @@ -89,17 +86,3 @@ func (gsa *generateSupportBundleAction) run(additionalFiles []string, excludeFil gsa.logger.Info("By default, this bundle contains basic logs and configs for Finch.") return nil } - -func (gsa *generateSupportBundleAction) assertVMExists() error { - status, err := lima.GetVMStatus(gsa.lcc, gsa.logger, limaInstanceName) - if err != nil { - return err - } - switch status { - case lima.Nonexistent: - return fmt.Errorf("cannot create support bundle for nonexistent VM, run `finch %s init` to create a new instance", - virtualMachineRootCmd) - default: - return nil - } -} diff --git a/cmd/finch/lima_args_darwin.go b/cmd/finch/support_bundle_native.go similarity index 50% rename from cmd/finch/lima_args_darwin.go rename to cmd/finch/support_bundle_native.go index f041fc20d..0dc35e875 100644 --- a/cmd/finch/lima_args_darwin.go +++ b/cmd/finch/support_bundle_native.go @@ -1,10 +1,10 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin +//go:build linux || native package main -func (nc *nerdctlCommand) GetLimaArgs() []string { - return []string{"shell", limaInstanceName, "sudo", "-E"} +func (gsa *generateSupportBundleAction) assertVMExists() error { + return nil } diff --git a/cmd/finch/support_bundle_remote.go b/cmd/finch/support_bundle_remote.go new file mode 100644 index 000000000..5b0bdbdda --- /dev/null +++ b/cmd/finch/support_bundle_remote.go @@ -0,0 +1,26 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build (darwin || windows) && !native + +package main + +import ( + "fmt" + + "github.com/runfinch/finch/pkg/lima" +) + +func (gsa *generateSupportBundleAction) assertVMExists() error { + status, err := lima.GetVMStatus(gsa.lcc, gsa.logger, limaInstanceName) + if err != nil { + return err + } + switch status { + case lima.Nonexistent: + return fmt.Errorf("cannot create support bundle for nonexistent VM, run `finch %s init` to create a new instance", + virtualMachineRootCmd) + default: + return nil + } +} diff --git a/cmd/finch/support_bundle_test.go b/cmd/finch/support_bundle_test.go deleted file mode 100644 index 5e0cc02d2..000000000 --- a/cmd/finch/support_bundle_test.go +++ /dev/null @@ -1,332 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -package main - -import ( - "fmt" - "testing" - - "github.com/golang/mock/gomock" - "github.com/stretchr/testify/assert" - - "github.com/runfinch/finch/pkg/mocks" -) - -func TestNewSupportBundleCommand(t *testing.T) { - t.Parallel() - - cmd := newSupportBundleCommand(nil, nil, nil) - assert.Equal(t, cmd.Name(), "support-bundle") -} - -func TestNewSupportBundleGenerateCommand(t *testing.T) { - t.Parallel() - - cmd := newSupportBundleGenerateCommand(nil, nil, nil) - assert.Equal(t, cmd.Name(), "generate") -} - -func TestGenerateSupportBundleAction_runAdapter(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - args []string - mockSvc func(*gomock.Controller, *mocks.Logger, *mocks.BundleBuilder, *mocks.LimaCmdCreator) - }{ - { - name: "no flags", - args: []string{}, - mockSvc: func( - ctrl *gomock.Controller, - logger *mocks.Logger, - builder *mocks.BundleBuilder, - lcc *mocks.LimaCmdCreator, - ) { - getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) - getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) - logger.EXPECT().Debugf(gomock.Any(), gomock.Any()) - - logger.EXPECT().Info(gomock.Any()) - builder.EXPECT().GenerateSupportBundle([]string{}, []string{}).Return("bundleName", nil) - logger.EXPECT().Infof(gomock.Any(), gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - }, - }, - { - name: "one include flag", - args: []string{ - "--include", - "testfile", - }, - mockSvc: func( - ctrl *gomock.Controller, - logger *mocks.Logger, - builder *mocks.BundleBuilder, - lcc *mocks.LimaCmdCreator, - ) { - getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) - getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) - logger.EXPECT().Debugf(gomock.Any(), gomock.Any()) - - logger.EXPECT().Info(gomock.Any()) - builder.EXPECT().GenerateSupportBundle([]string{"testfile"}, []string{}).Return("bundleName", nil) - logger.EXPECT().Infof(gomock.Any(), gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - }, - }, - { - name: "multiple include flags", - args: []string{ - "--include", - "testfile", - "--include", - "secondfile", - }, - mockSvc: func( - ctrl *gomock.Controller, - logger *mocks.Logger, - builder *mocks.BundleBuilder, - lcc *mocks.LimaCmdCreator, - ) { - getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) - getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) - logger.EXPECT().Debugf(gomock.Any(), gomock.Any()) - - logger.EXPECT().Info(gomock.Any()) - builder.EXPECT().GenerateSupportBundle([]string{"testfile", "secondfile"}, []string{}).Return("bundleName", nil) - logger.EXPECT().Infof(gomock.Any(), gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - }, - }, - { - name: "one exclude flag", - args: []string{ - "--exclude", - "testfile", - }, - mockSvc: func( - ctrl *gomock.Controller, - logger *mocks.Logger, - builder *mocks.BundleBuilder, - lcc *mocks.LimaCmdCreator, - ) { - getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) - getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) - logger.EXPECT().Debugf(gomock.Any(), gomock.Any()) - - logger.EXPECT().Info(gomock.Any()) - builder.EXPECT().GenerateSupportBundle([]string{}, []string{"testfile"}).Return("bundleName", nil) - logger.EXPECT().Infof(gomock.Any(), gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - }, - }, - { - name: "multiple exclude flags", - args: []string{ - "--exclude", - "testfile", - "--exclude", - "secondfile", - }, - mockSvc: func( - ctrl *gomock.Controller, - logger *mocks.Logger, - builder *mocks.BundleBuilder, - lcc *mocks.LimaCmdCreator, - ) { - getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) - getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) - logger.EXPECT().Debugf(gomock.Any(), gomock.Any()) - - logger.EXPECT().Info(gomock.Any()) - builder.EXPECT().GenerateSupportBundle([]string{}, []string{"testfile", "secondfile"}).Return("bundleName", nil) - logger.EXPECT().Infof(gomock.Any(), gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - }, - }, - { - name: "combo of include and exclude flags", - args: []string{ - "--include", - "testfile", - "--exclude", - "secondfile", - }, - mockSvc: func( - ctrl *gomock.Controller, - logger *mocks.Logger, - builder *mocks.BundleBuilder, - lcc *mocks.LimaCmdCreator, - ) { - getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) - getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) - logger.EXPECT().Debugf(gomock.Any(), gomock.Any()) - - logger.EXPECT().Info(gomock.Any()) - builder.EXPECT().GenerateSupportBundle([]string{"testfile"}, []string{"secondfile"}).Return("bundleName", nil) - logger.EXPECT().Infof(gomock.Any(), gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - logger.EXPECT().Info(gomock.Any()) - }, - }, - } - - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - - ctrl := gomock.NewController(t) - logger := mocks.NewLogger(ctrl) - builder := mocks.NewBundleBuilder(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) - tc.mockSvc(ctrl, logger, builder, lcc) - - cmd := newSupportBundleGenerateCommand(logger, builder, lcc) - cmd.SetArgs(tc.args) - assert.NoError(t, cmd.Execute()) - }) - } -} - -func TestGenerateSupportBundleAction_run(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - wantErr error - mockSvc func(*gomock.Controller, *mocks.Logger, *mocks.BundleBuilder, *mocks.LimaCmdCreator, []string, []string) - include []string - exclude []string - }{ - { - name: "VM is running, no error", - wantErr: nil, - mockSvc: func( - ctrl *gomock.Controller, - logger *mocks.Logger, - builder *mocks.BundleBuilder, - lcc *mocks.LimaCmdCreator, - include []string, - exclude []string, - ) { - getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) - getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) - logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") - - logger.EXPECT().Info("Generating support bundle...") - builder.EXPECT().GenerateSupportBundle(include, exclude).Return("bundleName", nil) - logger.EXPECT().Infof("Bundle created: %s", "bundleName") - logger.EXPECT().Info("Files posted on a Github issue can be read by anyone.") - logger.EXPECT().Info("Please ensure there is no sensitive information in the bundle before uploading.") - logger.EXPECT().Info("By default, this bundle contains basic logs and configs for Finch.") - }, - include: []string{}, - exclude: []string{}, - }, - { - name: "VM is stopped, no error", - wantErr: nil, - mockSvc: func( - ctrl *gomock.Controller, - logger *mocks.Logger, - builder *mocks.BundleBuilder, - lcc *mocks.LimaCmdCreator, - include []string, - exclude []string, - ) { - getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) - getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) - logger.EXPECT().Debugf("Status of virtual machine: %s", "Stopped") - - logger.EXPECT().Info("Generating support bundle...") - builder.EXPECT().GenerateSupportBundle(include, exclude).Return("bundleName", nil) - logger.EXPECT().Infof("Bundle created: %s", "bundleName") - logger.EXPECT().Info("Files posted on a Github issue can be read by anyone.") - logger.EXPECT().Info("Please ensure there is no sensitive information in the bundle before uploading.") - logger.EXPECT().Info("By default, this bundle contains basic logs and configs for Finch.") - }, - include: []string{}, - exclude: []string{}, - }, - { - name: "VM is nonexistent", - wantErr: fmt.Errorf("cannot create support bundle for nonexistent VM, run `finch %s init` to create a new instance", - virtualMachineRootCmd), - mockSvc: func( - ctrl *gomock.Controller, - logger *mocks.Logger, - _ *mocks.BundleBuilder, - lcc *mocks.LimaCmdCreator, - _ []string, - _ []string, - ) { - getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) - getVMStatusC.EXPECT().Output().Return([]byte(""), nil) - logger.EXPECT().Debugf("Status of virtual machine: %s", "") - }, - include: []string{}, - exclude: []string{}, - }, - { - name: "VM is running, error generating bundle", - wantErr: fmt.Errorf("foo"), - mockSvc: func( - ctrl *gomock.Controller, - logger *mocks.Logger, - builder *mocks.BundleBuilder, - lcc *mocks.LimaCmdCreator, - include []string, - exclude []string, - ) { - getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) - getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) - logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") - - logger.EXPECT().Info("Generating support bundle...") - builder.EXPECT().GenerateSupportBundle(include, exclude).Return("", fmt.Errorf("foo")) - }, - include: []string{}, - exclude: []string{}, - }, - } - - for _, tc := range testCases { - tc := tc - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - - ctrl := gomock.NewController(t) - logger := mocks.NewLogger(ctrl) - builder := mocks.NewBundleBuilder(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) - - tc.mockSvc(ctrl, logger, builder, lcc, tc.include, tc.exclude) - err := newGenerateSupportBundleAction(logger, builder, lcc).run(tc.include, tc.exclude) - assert.Equal(t, tc.wantErr, err) - }) - } -} diff --git a/cmd/finch/version.go b/cmd/finch/version.go index 1179f5499..3b2b140ba 100644 --- a/cmd/finch/version.go +++ b/cmd/finch/version.go @@ -5,8 +5,6 @@ package main import ( "bytes" - "encoding/json" - "errors" "fmt" "io" "text/template" @@ -15,7 +13,6 @@ import ( "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/flog" - "github.com/runfinch/finch/pkg/lima" "github.com/runfinch/finch/pkg/templates" "github.com/runfinch/finch/pkg/version" ) @@ -170,37 +167,3 @@ func (va *versionAction) showVersionMessage(tmpl *template.Template, nerdctlVers return nil } - -func (va *versionAction) printVersion(format string) error { - status, err := lima.GetVMStatus(va.creator, va.logger, limaInstanceName) - if err != nil { - return fmt.Errorf("failed to get VM status: %w", err) - } - if status != lima.Running { - return errors.New("detailed version info is unavailable because VM is not running") - } - // Add -E to sudo command in order to preserve existing environment variables, more info: - // https://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo/8633575#8633575 - limaArgs := []string{"shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", "--format", "json"} - out, err := va.creator.CreateWithoutStdio(limaArgs...).Output() - if err != nil { - return fmt.Errorf("failed to create the nerdctl version command: %w", err) - } - - var nerdctlVersion NerdctlVersionOutput - err = json.Unmarshal(out, &nerdctlVersion) - if err != nil { - return fmt.Errorf("failed to JSON-unmarshal the nerdctl version output: %w", err) - } - - tmpl, err := newVersionTemplate(format) - if err != nil { - return err - } - err = va.showVersionMessage(tmpl, nerdctlVersion) - if err != nil { - return err - } - - return nil -} diff --git a/cmd/finch/version_native.go b/cmd/finch/version_native.go new file mode 100644 index 000000000..94c2088d1 --- /dev/null +++ b/cmd/finch/version_native.go @@ -0,0 +1,36 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux || native + +package main + +import ( + "encoding/json" + "fmt" +) + +func (va *versionAction) printVersion(format string) error { + limaArgs := []string{"version", "--format", "json"} + out, err := va.creator.CreateWithoutStdio(limaArgs...).Output() + if err != nil { + return fmt.Errorf("failed to create the nerdctl version command: %w", err) + } + + var nerdctlVersion NerdctlVersionOutput + err = json.Unmarshal(out, &nerdctlVersion) + if err != nil { + return fmt.Errorf("failed to JSON-unmarshal the nerdctl version output: %w", err) + } + + tmpl, err := newVersionTemplate(format) + if err != nil { + return err + } + err = va.showVersionMessage(tmpl, nerdctlVersion) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/finch/version_remote.go b/cmd/finch/version_remote.go new file mode 100644 index 000000000..062228e98 --- /dev/null +++ b/cmd/finch/version_remote.go @@ -0,0 +1,48 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build (darwin || windows) && !native + +package main + +import ( + "encoding/json" + "errors" + "fmt" + + "github.com/runfinch/finch/pkg/lima" +) + +func (va *versionAction) printVersion(format string) error { + status, err := lima.GetVMStatus(va.creator, va.logger, limaInstanceName) + if err != nil { + return fmt.Errorf("failed to get VM status: %w", err) + } + if status != lima.Running { + return errors.New("detailed version info is unavailable because VM is not running") + } + // Add -E to sudo command in order to preserve existing environment variables, more info: + // https://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo/8633575#8633575 + limaArgs := []string{"shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", "--format", "json"} + out, err := va.creator.CreateWithoutStdio(limaArgs...).Output() + if err != nil { + return fmt.Errorf("failed to create the nerdctl version command: %w", err) + } + + var nerdctlVersion NerdctlVersionOutput + err = json.Unmarshal(out, &nerdctlVersion) + if err != nil { + return fmt.Errorf("failed to JSON-unmarshal the nerdctl version output: %w", err) + } + + tmpl, err := newVersionTemplate(format) + if err != nil { + return err + } + err = va.showVersionMessage(tmpl, nerdctlVersion) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/finch/version_test.go b/cmd/finch/version_test.go index 428c30c61..33a247c12 100644 --- a/cmd/finch/version_test.go +++ b/cmd/finch/version_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package main import ( diff --git a/cmd/finch/virtual_machine_init.go b/cmd/finch/virtual_machine_init.go index 1b64f2309..4f21f3c35 100644 --- a/cmd/finch/virtual_machine_init.go +++ b/cmd/finch/virtual_machine_init.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_init_test.go b/cmd/finch/virtual_machine_init_test.go index db45ab44d..87ce5ad10 100644 --- a/cmd/finch/virtual_machine_init_test.go +++ b/cmd/finch/virtual_machine_init_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_local.go b/cmd/finch/virtual_machine_local.go new file mode 100644 index 000000000..e6fb7e63b --- /dev/null +++ b/cmd/finch/virtual_machine_local.go @@ -0,0 +1,29 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux + +package main + +import ( + "github.com/runfinch/finch/pkg/command" + "github.com/runfinch/finch/pkg/config" + "github.com/runfinch/finch/pkg/flog" + "github.com/runfinch/finch/pkg/path" + + "github.com/spf13/afero" + "github.com/spf13/cobra" +) + +func virtualMachineCommands( + logger flog.Logger, + fp path.Finch, + lcc command.LimaCmdCreator, + ecc command.Creator, + fs afero.Fs, + fc *config.Finch, + home string, + finchRootPath string, +) *cobra.Command { + return &cobra.Command{} +} diff --git a/cmd/finch/virtual_machine.go b/cmd/finch/virtual_machine_remote.go similarity index 99% rename from cmd/finch/virtual_machine.go rename to cmd/finch/virtual_machine_remote.go index f35769391..9ff34e99a 100644 --- a/cmd/finch/virtual_machine.go +++ b/cmd/finch/virtual_machine_remote.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_remove.go b/cmd/finch/virtual_machine_remove.go index 38a43df41..0b766c7ad 100644 --- a/cmd/finch/virtual_machine_remove.go +++ b/cmd/finch/virtual_machine_remove.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_remove_test.go b/cmd/finch/virtual_machine_remove_test.go index 74fe34e24..24d065f05 100644 --- a/cmd/finch/virtual_machine_remove_test.go +++ b/cmd/finch/virtual_machine_remove_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_settings.go b/cmd/finch/virtual_machine_settings.go index d4ea22e8d..7265642e8 100644 --- a/cmd/finch/virtual_machine_settings.go +++ b/cmd/finch/virtual_machine_settings.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_settings_test.go b/cmd/finch/virtual_machine_settings_test.go index c582a5252..60a8bf776 100644 --- a/cmd/finch/virtual_machine_settings_test.go +++ b/cmd/finch/virtual_machine_settings_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_start.go b/cmd/finch/virtual_machine_start.go index a1a9d6b11..7d236533f 100644 --- a/cmd/finch/virtual_machine_start.go +++ b/cmd/finch/virtual_machine_start.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_start_test.go b/cmd/finch/virtual_machine_start_test.go index f7e0ce5c3..5a0d78370 100644 --- a/cmd/finch/virtual_machine_start_test.go +++ b/cmd/finch/virtual_machine_start_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_status.go b/cmd/finch/virtual_machine_status.go index a8a08ec34..60b7b369a 100644 --- a/cmd/finch/virtual_machine_status.go +++ b/cmd/finch/virtual_machine_status.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_status_test.go b/cmd/finch/virtual_machine_status_test.go index a1c3c6f5c..811e61851 100644 --- a/cmd/finch/virtual_machine_status_test.go +++ b/cmd/finch/virtual_machine_status_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_stop.go b/cmd/finch/virtual_machine_stop.go index ba61f1f24..972f31571 100644 --- a/cmd/finch/virtual_machine_stop.go +++ b/cmd/finch/virtual_machine_stop.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_stop_test.go b/cmd/finch/virtual_machine_stop_test.go index 63e8c94be..a1164d15a 100644 --- a/cmd/finch/virtual_machine_stop_test.go +++ b/cmd/finch/virtual_machine_stop_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/cmd/finch/virtual_machine_test.go b/cmd/finch/virtual_machine_test.go index f3dde7e8b..7b9cdb0f6 100644 --- a/cmd/finch/virtual_machine_test.go +++ b/cmd/finch/virtual_machine_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package main import ( diff --git a/pkg/command/lima.go b/pkg/command/nerdctl.go similarity index 81% rename from pkg/command/lima.go rename to pkg/command/nerdctl.go index 338fbd2de..f07414aa0 100644 --- a/pkg/command/lima.go +++ b/pkg/command/nerdctl.go @@ -6,8 +6,6 @@ package command import ( "bytes" "fmt" - "io" - "runtime" "strings" "golang.org/x/exp/slices" @@ -123,35 +121,6 @@ func (lcc *limaCmdCreator) replaceBytes(s []byte, rs []Replacement) []byte { return s } -func (lcc *limaCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, args ...string) Command { - lcc.logger.Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", args, envKeyLimaHome, lcc.limaHomePath) - cmd := lcc.cmdCreator.Create(lcc.limactlPath, args...) - limaHomeEnv := fmt.Sprintf("%s=%s", envKeyLimaHome, lcc.limaHomePath) - var pathEnv string - var envKeyPath string - var path string - if runtime.GOOS == "windows" { - envKeyPath = envKeyWinPath - path = lcc.systemDeps.Env(envKeyPath) - path = fmt.Sprintf(`%s\;%s`, lcc.binPath, path) - pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) - } else { - envKeyPath = envKeyUnixPath - path = lcc.systemDeps.Env(envKeyPath) - path = fmt.Sprintf("%s:%s", lcc.binPath, path) - pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) - } - - newPathEnv := replaceOrAppend(lcc.systemDeps.Environ(), envKeyLimaHome, limaHomeEnv) - newPathEnv = replaceOrAppend(newPathEnv, envKeyPath, pathEnv) - - cmd.SetEnv(newPathEnv) - cmd.SetStdin(stdin) - cmd.SetStdout(stdout) - cmd.SetStderr(stderr) - return cmd -} - func replaceOrAppend(orig []string, varName, newVar string) []string { envIdx := slices.IndexFunc(orig, func(envVar string) bool { return strings.HasPrefix(envVar, fmt.Sprintf("%s=", varName)) diff --git a/pkg/command/nerdctl_native.go b/pkg/command/nerdctl_native.go new file mode 100644 index 000000000..07fe94d33 --- /dev/null +++ b/pkg/command/nerdctl_native.go @@ -0,0 +1,41 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux || native + +package command + +import ( + "fmt" + "io" + "runtime" +) + +func (lcc *limaCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, args ...string) Command { + lcc.logger.Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", args, envKeyLimaHome, lcc.limaHomePath) + cmd := lcc.cmdCreator.Create("nerdctl", args...) + limaHomeEnv := fmt.Sprintf("%s=%s", envKeyLimaHome, lcc.limaHomePath) + var pathEnv string + var envKeyPath string + var path string + if runtime.GOOS == "windows" { + envKeyPath = envKeyWinPath + path = lcc.systemDeps.Env(envKeyPath) + path = fmt.Sprintf(`%s\;%s`, lcc.binPath, path) + pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) + } else { + envKeyPath = envKeyUnixPath + path = lcc.systemDeps.Env(envKeyPath) + path = fmt.Sprintf("%s:%s", lcc.binPath, path) + pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) + } + + newPathEnv := replaceOrAppend(lcc.systemDeps.Environ(), envKeyLimaHome, limaHomeEnv) + newPathEnv = replaceOrAppend(newPathEnv, envKeyPath, pathEnv) + + cmd.SetEnv(newPathEnv) + cmd.SetStdin(stdin) + cmd.SetStdout(stdout) + cmd.SetStderr(stderr) + return cmd +} diff --git a/pkg/command/nerdctl_remote.go b/pkg/command/nerdctl_remote.go new file mode 100644 index 000000000..c2fdce6c8 --- /dev/null +++ b/pkg/command/nerdctl_remote.go @@ -0,0 +1,41 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build (darwin || windows) && !native + +package command + +import ( + "fmt" + "io" + "runtime" +) + +func (lcc *limaCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, args ...string) Command { + lcc.logger.Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", args, envKeyLimaHome, lcc.limaHomePath) + cmd := lcc.cmdCreator.Create(lcc.limactlPath, args...) + limaHomeEnv := fmt.Sprintf("%s=%s", envKeyLimaHome, lcc.limaHomePath) + var pathEnv string + var envKeyPath string + var path string + if runtime.GOOS == "windows" { + envKeyPath = envKeyWinPath + path = lcc.systemDeps.Env(envKeyPath) + path = fmt.Sprintf(`%s\;%s`, lcc.binPath, path) + pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) + } else { + envKeyPath = envKeyUnixPath + path = lcc.systemDeps.Env(envKeyPath) + path = fmt.Sprintf("%s:%s", lcc.binPath, path) + pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) + } + + newPathEnv := replaceOrAppend(lcc.systemDeps.Environ(), envKeyLimaHome, limaHomeEnv) + newPathEnv = replaceOrAppend(newPathEnv, envKeyPath, pathEnv) + + cmd.SetEnv(newPathEnv) + cmd.SetStdin(stdin) + cmd.SetStdout(stdout) + cmd.SetStderr(stderr) + return cmd +} diff --git a/pkg/command/lima_test.go b/pkg/command/nerdctl_test.go similarity index 100% rename from pkg/command/lima_test.go rename to pkg/command/nerdctl_test.go diff --git a/pkg/command/lima_unix_test.go b/pkg/command/nerdctl_unix_test.go similarity index 100% rename from pkg/command/lima_unix_test.go rename to pkg/command/nerdctl_unix_test.go diff --git a/pkg/command/lima_windows_test.go b/pkg/command/nerdctl_windows_test.go similarity index 100% rename from pkg/command/lima_windows_test.go rename to pkg/command/nerdctl_windows_test.go diff --git a/pkg/config/config.go b/pkg/config/config.go index 714181f64..f2465da28 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -14,7 +14,6 @@ import ( "fmt" "path/filepath" - "github.com/lima-vm/lima/pkg/limayaml" "github.com/spf13/afero" "gopkg.in/yaml.v3" @@ -29,30 +28,9 @@ type AdditionalDirectory struct { Path *string `yaml:"path"` } -// Finch represents the configuration file for Finch CLI. -type Finch struct { - CPUs *int `yaml:"cpus,omitempty"` - Memory *string `yaml:"memory,omitempty"` - // Snapshotters: the snapshotters that will be installed and configured automatically on vm init or on vm start. - // Values: `soci` for SOCI snapshotter; `overlayfs` for default overlay snapshotter. +type GeneralSettings struct { Snapshotters []string `yaml:"snapshotters,omitempty"` - // CredsHelper: the list of credential helpers that will be installed and configured automatically on vm init or on vm start CredsHelpers []string `yaml:"creds_helpers,omitempty"` - // AdditionalDirectories are the work directories that are not supported by default. In macOS, only home directory is supported by default. - // For example, if you want to mount a directory into a container, and that directory is not under your home directory, - // then you'll need to specify this field to add that directory or any ascendant of it as a work directory. - AdditionalDirectories []AdditionalDirectory `yaml:"additional_directories,omitempty"` - // VMType sets which technology to use for Finch's VM. - // Currently supports `qemu` and `vz` (Virtualization.framework). - // Also sets mountType to "virtiofs", instead of the default "reverse-sshfs" - // Requires macOS 13.0 or later. - // This setting will only be applied on vm init. - VMType *limayaml.VMType `yaml:"vmType,omitempty"` - // Use Rosetta 2 when available. Forces vmType to "vz" (Virtualization.framework) if set to `true`. - // Requires macOS 13.0 or later and an Apple Silicon (ARM64) mac. - // Has no effect on systems where Rosetta 2 is not available (Intel/AMD64 macs, or macOS < 13.0). - // This setting will only be applied on vm init. - Rosetta *bool `yaml:"rosetta,omitempty"` } // Nerdctl is a copy from github.com/containerd/nerdctl/cmd/nerdctl/main.go @@ -100,6 +78,13 @@ type NerdctlConfigApplier interface { Apply(remoteAddr string) error } +// // NerdctlConfigApplierSystemDeps provides system dependencies. +// // +// //go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/pkg_config_nerdctl_config_applier_system_deps.go -package=mocks -mock_names NerdctlConfigApplierSystemDeps=NerdctlConfigApplierSystemDeps . NerdctlConfigApplierSystemDeps +// type NerdctlConfigApplierSystemDeps interface { +// system.UserHomeDir +// } + // LoadSystemDeps contains the system dependencies for Load. // //go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/pkg_config_load_system_deps.go -package=mocks -mock_names LoadSystemDeps=LoadSystemDeps . LoadSystemDeps @@ -194,39 +179,3 @@ func loadFinchConfig(fs afero.Fs, finchConfigPath string, logger flog.Logger, sy return &cfg, nil } - -// ModifyFinchConfig Modify Finch's configuration from user inputs. -func ModifyFinchConfig(fs afero.Fs, logger flog.Logger, finchConfigPath string, opts VMConfigOpts) (bool, error) { - var isConfigUpdated bool - - systemDeps := system.NewStdLib() - mem := fmemory.NewMemory() - - finchCfg, err := loadFinchConfig(fs, finchConfigPath, logger, systemDeps, mem) - if err != nil { - return isConfigUpdated, err - } - - cpus, memory := opts.CPUs, opts.Memory - if cpus != DefaultCPUs && cpus != *finchCfg.CPUs { - *finchCfg.CPUs = cpus - isConfigUpdated = true - } - if memory != DefaultMemory && memory != *finchCfg.Memory { - *finchCfg.Memory = memory - isConfigUpdated = true - } - - if !isConfigUpdated { - return isConfigUpdated, fmt.Errorf("the number of CPUs or the amount of memory should be at least one valid value") - } - - if err := validate(finchCfg, logger, systemDeps, mem); err != nil { - return false, fmt.Errorf("failed to validate config file: %w", err) - } - if err := writeConfig(finchCfg, fs, finchConfigPath); err != nil { - return false, err - } - - return isConfigUpdated, nil -} diff --git a/pkg/config/config_darwin.go b/pkg/config/config_darwin.go index 0f71c3251..c7c9177af 100644 --- a/pkg/config/config_darwin.go +++ b/pkg/config/config_darwin.go @@ -10,9 +10,26 @@ import ( "strconv" "strings" + "github.com/lima-vm/lima/pkg/limayaml" + "github.com/spf13/afero" + "github.com/runfinch/finch/pkg/command" + "github.com/runfinch/finch/pkg/flog" + "github.com/runfinch/finch/pkg/fmemory" + "github.com/runfinch/finch/pkg/system" ) +// Finch represents the configuration file for Finch CLI. +type Finch struct { + CPUs *int `yaml:"cpus,omitempty"` + Memory *string `yaml:"memory,omitempty"` + AdditionalDirectories []AdditionalDirectory `yaml:"additional_directories,omitempty"` + VMType *limayaml.VMType `yaml:"vmType,omitempty"` + Rosetta *bool `yaml:"rosetta,omitempty"` + Snapshotters []string `yaml:"snapshotters,omitempty"` + CredsHelpers []string `yaml:"creds_helpers,omitempty"` +} + // SupportsVirtualizationFramework checks if the user's system supports Virtualization.framework. func SupportsVirtualizationFramework(cmdCreator command.Creator) (bool, error) { cmd := cmdCreator.Create("sw_vers", "-productVersion") @@ -37,3 +54,39 @@ func SupportsVirtualizationFramework(cmdCreator command.Creator) (bool, error) { return false, nil } + +// ModifyFinchConfig Modify Finch's configuration from user inputs. +func ModifyFinchConfig(fs afero.Fs, logger flog.Logger, finchConfigPath string, opts VMConfigOpts) (bool, error) { + var isConfigUpdated bool + + systemDeps := system.NewStdLib() + mem := fmemory.NewMemory() + + finchCfg, err := loadFinchConfig(fs, finchConfigPath, logger, systemDeps, mem) + if err != nil { + return isConfigUpdated, err + } + + cpus, memory := opts.CPUs, opts.Memory + if cpus != DefaultCPUs && cpus != *finchCfg.CPUs { + *finchCfg.CPUs = cpus + isConfigUpdated = true + } + if memory != DefaultMemory && memory != *finchCfg.Memory { + *finchCfg.Memory = memory + isConfigUpdated = true + } + + if !isConfigUpdated { + return isConfigUpdated, fmt.Errorf("the number of CPUs or the amount of memory should be at least one valid value") + } + + if err := validate(finchCfg, logger, systemDeps, mem); err != nil { + return false, fmt.Errorf("failed to validate config file: %w", err) + } + if err := writeConfig(finchCfg, fs, finchConfigPath); err != nil { + return false, err + } + + return isConfigUpdated, nil +} diff --git a/pkg/config/config_native.go b/pkg/config/config_native.go new file mode 100644 index 000000000..3cff48087 --- /dev/null +++ b/pkg/config/config_native.go @@ -0,0 +1,10 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux + +package config + +type Finch struct { + GeneralSettings +} diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index bf8cd0713..b9101a9a2 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin + package config import ( diff --git a/pkg/config/config_windows.go b/pkg/config/config_windows.go index 61ecec773..ee8e3e2c9 100644 --- a/pkg/config/config_windows.go +++ b/pkg/config/config_windows.go @@ -6,10 +6,23 @@ package config import ( + "github.com/lima-vm/lima/pkg/limayaml" "github.com/runfinch/finch/pkg/command" + "github.com/runfinch/finch/pkg/flog" + "github.com/spf13/afero" ) +type Finch struct { + VMType *limayaml.VMType `yaml:"vmType,omitempty"` + GeneralSettings +} + // SupportsWSL2 checks if system supports WSL2 and sets default version to 2. func SupportsWSL2(cmdCreator command.Creator) error { return cmdCreator.Create("wsl", "--set-default-version", "2").Run() } + +// ModifyFinchConfig Modify Finch's configuration from user inputs. +func ModifyFinchConfig(_ afero.Fs, _ flog.Logger, _ string, _ VMConfigOpts) (bool, error) { + return true, nil +} diff --git a/pkg/config/defaults_linux.go b/pkg/config/defaults_linux.go new file mode 100644 index 000000000..5f01d25c5 --- /dev/null +++ b/pkg/config/defaults_linux.go @@ -0,0 +1,21 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux + +package config + +import ( + "github.com/runfinch/finch/pkg/command" + "github.com/runfinch/finch/pkg/fmemory" +) + +// applyDefaults sets default configuration options if they are not already set. +func applyDefaults( + cfg *Finch, + _ LoadSystemDeps, + _ fmemory.Memory, + _ command.Creator, +) *Finch { + return cfg +} diff --git a/pkg/config/defaults_test.go b/pkg/config/defaults_test.go index 570f489a7..36fd18e9e 100644 --- a/pkg/config/defaults_test.go +++ b/pkg/config/defaults_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin + package config import ( diff --git a/pkg/config/lima_config_applier.go b/pkg/config/lima_config_applier.go index 02e7715fa..8cd8a84e6 100644 --- a/pkg/config/lima_config_applier.go +++ b/pkg/config/lima_config_applier.go @@ -1,76 +1,12 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - package config import ( - "fmt" - "strings" - - "github.com/lima-vm/lima/pkg/limayaml" "github.com/spf13/afero" - "github.com/xorcare/pointer" - "golang.org/x/exp/slices" - "gopkg.in/yaml.v3" "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/system" ) -const ( - sociVersion = "0.5.0" - snapshotterProvisioningScriptHeader = "# snapshotter provisioning script" - sociInstallationProvisioningScriptHeader = snapshotterProvisioningScriptHeader + ": soci" - sociFileNameFormat = "soci-snapshotter-%s-linux-%s.tar.gz" - sociDownloadURLFormat = "https://github.com/awslabs/soci-snapshotter/releases/download/v%s/%s" - sociServiceDownloadURLFormat = "https://raw.githubusercontent.com/awslabs/soci-snapshotter/v%s/soci-snapshotter.service" - //nolint:lll // command string - sociInstallationScriptFormat = `%s -if [ ! -f /usr/local/bin/soci ]; then - # download soci - set -e - curl --retry 2 --retry-max-time 120 -OL "%s" - # move to usr/local/bin - tar -C /usr/local/bin -xvf %s ./soci ./soci-snapshotter-grpc - - # install as a systemd service - curl --retry 2 --retry-max-time 120 -OL "%s" - mv soci-snapshotter.service /usr/local/lib/systemd/system/ - ln -s /usr/local/lib/systemd/system/soci-snapshotter.service /etc/systemd/system/multi-user.target.wants/ - restorecon -v /usr/local/lib/systemd/system/soci-snapshotter.service - systemctl daemon-reload - sudo mkdir -p /usr/local/lib/systemd/system/soci-snapshotter.service.d/ - printf '[Unit]\nPartOf=containerd.service\n\n[Service]\nKillSignal=SIGTERM\n' | sudo tee /usr/local/lib/systemd/system/soci-snapshotter.service.d/finch.conf - systemctl enable --now soci-snapshotter -fi - -# changing containerd config, this seems to get reset on every VM stop/start -if ! grep -q soci /etc/containerd/config.toml; then - printf ' [proxy_plugins.soci]\n type = "snapshot"\n address = "/run/soci-snapshotter-grpc/soci-snapshotter-grpc.sock"\n' >> /etc/containerd/config.toml -fi - -sudo systemctl restart containerd.service -` - - userModeEmulationProvisioningScriptHeader = "# cross-arch tools" - wslDiskFormatScriptHeader = "# wsl disk format script" - qemuPkgInstallationScript = `%s -#!/bin/bash -qemu_pkgs="" -if [ ! -f /usr/bin/qemu-aarch64-static ]; then - qemu_pkgs="$qemu_pkgs qemu-user-static-aarch64" -elif [ ! -f /usr/bin/qemu-aarch64-static ]; then - qemu_pkgs="$qemu_pkgs qemu-user-static-arm" -elif [ ! -f /usr/bin/qemu-aarch64-static ]; then - qemu_pkgs="$qemu_pkgs qemu-user-static-x86" -fi - -if [[ $qemu_pkgs ]]; then - dnf install -y --setopt=install_weak_deps=False ${qemu_pkgs} -fi -` -) - // LimaConfigApplierSystemDeps contains the system dependencies for LimaConfigApplier. // //go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/pkg_config_lima_config_applier_system_deps.go -package=mocks -mock_names LimaConfigApplierSystemDeps=LimaConfigApplierSystemDeps . LimaConfigApplierSystemDeps @@ -90,188 +26,3 @@ type limaConfigApplier struct { } var _ LimaConfigApplier = (*limaConfigApplier)(nil) - -// NewLimaApplier creates a new LimaConfigApplier that -// applies lima configuration changes by writing to the lima config file on the disk. -func NewLimaApplier( - cfg *Finch, - cmdCreator command.Creator, - fs afero.Fs, - limaDefaultConfigPath string, - limaOverrideConfigPath string, - systemDeps LimaConfigApplierSystemDeps, - finchConfigPath string, -) LimaConfigApplier { - return &limaConfigApplier{ - cfg: cfg, - cmdCreator: cmdCreator, - fs: fs, - limaDefaultConfigPath: limaDefaultConfigPath, - limaOverrideConfigPath: limaOverrideConfigPath, - systemDeps: systemDeps, - finchConfigPath: finchConfigPath, - } -} - -// ConfigureDefaultLimaYaml writes Lima-specific config values from Finch's config to default.yaml at lima config file path. -// ConfigureDefaultLimaYaml will create a default.yaml at the path if it does not exist. -func (lca *limaConfigApplier) ConfigureDefaultLimaYaml() error { - if err := afero.WriteFile(lca.fs, lca.limaDefaultConfigPath, []byte(""), 0o600); err != nil { - return fmt.Errorf("failed to create the an empty lima config file: %w", err) - } - - var limaCfg limayaml.LimaYAML - - if limaCfg.Rosetta.Enabled == nil { - limaCfg.Rosetta.Enabled = pointer.Bool(false) - limaCfg.Rosetta.BinFmt = pointer.Bool(false) - } - - cfgAfterInit, err := lca.configureVirtualizationFramework(&limaCfg) - if err != nil { - return fmt.Errorf("failed to apply init-only config values: %w", err) - } - limaCfg = *cfgAfterInit - - limaCfgBytes, err := yaml.Marshal(limaCfg) - if err != nil { - return fmt.Errorf("failed to marshal the lima config file: %w", err) - } - - if err := afero.WriteFile(lca.fs, lca.limaDefaultConfigPath, limaCfgBytes, 0o600); err != nil { - return fmt.Errorf("failed to write to the lima config file: %w", err) - } - - return nil -} - -// ConfigureOverrideLimaYaml writes Lima-specific config values from Finch's config to override.yaml at lima config file path. -// ConfigureOverrideLimaYaml will create a override.yaml at the path if it does not exist. -func (lca *limaConfigApplier) ConfigureOverrideLimaYaml() error { - if err := afero.WriteFile(lca.fs, lca.limaOverrideConfigPath, []byte(""), 0o600); err != nil { - return fmt.Errorf("failed to create the an empty lima config file: %w", err) - } - var limaCfg limayaml.LimaYAML - - limaCfg.CPUs = lca.cfg.CPUs - limaCfg.Memory = lca.cfg.Memory - limaCfg.Mounts = []limayaml.Mount{} - for _, ad := range lca.cfg.AdditionalDirectories { - limaCfg.Mounts = append(limaCfg.Mounts, limayaml.Mount{ - Location: *ad.Path, Writable: pointer.Bool(true), - }) - } - - if *lca.cfg.VMType != "wsl2" && len(limaCfg.AdditionalDisks) == 0 { - limaCfg.AdditionalDisks = append(limaCfg.AdditionalDisks, limayaml.Disk{ - Name: "finch", - }) - } - - err := lca.provisionSnapshotters(&limaCfg) - if err != nil { - return fmt.Errorf("failed to provision snapshotters: %w", err) - } - - err = lca.configureDefaultSnapshotter(&limaCfg) - if err != nil { - return fmt.Errorf("failed to configure default snapshotter: %w", err) - } - - if *lca.cfg.VMType == "wsl2" { - ensureWslDiskFormatScript(&limaCfg) - } - - limaCfgBytes, err := yaml.Marshal(limaCfg) - if err != nil { - return fmt.Errorf("failed to marshal the lima config file: %w", err) - } - - if err := afero.WriteFile(lca.fs, lca.limaOverrideConfigPath, limaCfgBytes, 0o600); err != nil { - return fmt.Errorf("failed to write to the lima config file: %w", err) - } - - return nil -} - -func validateSnapshotter(snapshotter string) error { - supportedSnapshotters := []string{"overlayfs", "soci"} - if !slices.Contains(supportedSnapshotters, snapshotter) { - return fmt.Errorf("snapshotter %s is not supported", snapshotter) - } - return nil -} - -func (lca *limaConfigApplier) configureDefaultSnapshotter(limaCfg *limayaml.LimaYAML) error { - if len(lca.cfg.Snapshotters) == 0 { - limaCfg.Env = map[string]string{} - return nil - } - - snapshotter := lca.cfg.Snapshotters[0] - err := validateSnapshotter(snapshotter) - if err != nil { - return err - } - - limaCfg.Env = map[string]string{"CONTAINERD_SNAPSHOTTER": snapshotter} - - return nil -} - -func (lca *limaConfigApplier) provisionSnapshotters(limaCfg *limayaml.LimaYAML) error { - for _, snapshotter := range lca.cfg.Snapshotters { - switch snapshotter { - case "soci": - lca.provisionSociSnapshotter(limaCfg) - case "overlayfs": - continue - default: - return fmt.Errorf("snapshotter %s is not supported", snapshotter) - } - } - - return nil -} - -func (lca *limaConfigApplier) provisionSociSnapshotter(limaCfg *limayaml.LimaYAML) { - sociFileName := fmt.Sprintf(sociFileNameFormat, sociVersion, lca.systemDeps.Arch()) - sociDownloadURL := fmt.Sprintf(sociDownloadURLFormat, sociVersion, sociFileName) - sociServiceDownloadURL := fmt.Sprintf(sociServiceDownloadURLFormat, sociVersion) - sociInstallationScript := fmt.Sprintf(sociInstallationScriptFormat, sociInstallationProvisioningScriptHeader, - sociDownloadURL, sociFileName, sociServiceDownloadURL) - limaCfg.Provision = append(limaCfg.Provision, limayaml.Provision{ - Mode: "system", - Script: sociInstallationScript, - }) -} - -func ensureWslDiskFormatScript(limaCfg *limayaml.LimaYAML) { - if hasScript := findWslDiskFormatScript(limaCfg); !hasScript { - limaCfg.Provision = append(limaCfg.Provision, limayaml.Provision{ - Mode: "system", - Script: fmt.Sprintf(`%s -#!/bin/bash -mkdir -p /mnt/lima-finch -mount "$(blkid -s TYPE -t LABEL=FinchDataDisk -o device)" /mnt/lima-finch -`, wslDiskFormatScriptHeader), - }) - } -} - -func findWslDiskFormatScript(limaCfg *limayaml.LimaYAML) bool { - hasWslDiskFormatScript := false - for _, prov := range limaCfg.Provision { - trimmed := strings.Trim(prov.Script, " ") - if !hasWslDiskFormatScript && strings.HasPrefix(trimmed, wslDiskFormatScriptHeader) { - hasWslDiskFormatScript = true - break - } - } - - return hasWslDiskFormatScript -} - -func (lca *limaConfigApplier) GetFinchConfigPath() string { - return lca.finchConfigPath -} diff --git a/pkg/config/lima_config_applier_darwin.go b/pkg/config/lima_config_applier_darwin.go index 9537323d0..77f6d849c 100644 --- a/pkg/config/lima_config_applier_darwin.go +++ b/pkg/config/lima_config_applier_darwin.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin +//go:build darwin && !native package config @@ -64,3 +64,23 @@ func userModeEmulationInstallationScript(limaCfg *limayaml.LimaYAML) { Script: fmt.Sprintf(qemuPkgInstallationScript, userModeEmulationProvisioningScriptHeader), }) } + +func (lca *limaConfigApplier) configureCPUs(limaCfg *limayaml.LimaYAML) *limayaml.LimaYAML { + limaCfg.CPUs = lca.cfg.CPUs + return limaCfg +} + +func (lca *limaConfigApplier) configureMemory(limaCfg *limayaml.LimaYAML) *limayaml.LimaYAML { + limaCfg.Memory = lca.cfg.Memory + return limaCfg +} + +func (lca *limaConfigApplier) configureMounts(limaCfg *limayaml.LimaYAML) *limayaml.LimaYAML { + limaCfg.Mounts = []limayaml.Mount{} + for _, ad := range lca.cfg.AdditionalDirectories { + limaCfg.Mounts = append(limaCfg.Mounts, limayaml.Mount{ + Location: *ad.Path, Writable: pointer.Bool(true), + }) + } + return limaCfg +} diff --git a/pkg/config/lima_config_applier_native.go b/pkg/config/lima_config_applier_native.go new file mode 100644 index 000000000..8c7424c01 --- /dev/null +++ b/pkg/config/lima_config_applier_native.go @@ -0,0 +1,52 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux || native + +package config + +import ( + "github.com/lima-vm/lima/pkg/limayaml" + "github.com/spf13/afero" + + "github.com/runfinch/finch/pkg/command" +) + +// NewLimaApplier creates a new LimaConfigApplier that +// applies lima configuration changes by writing to the lima config file on the disk. +func NewLimaApplier( + _ *Finch, + _ command.Creator, + _ afero.Fs, + _ string, + _ string, + _ LimaConfigApplierSystemDeps, + _ string, +) LimaConfigApplier { + return &limaConfigApplier{} +} + +func (lca *limaConfigApplier) ConfigureDefaultLimaYaml() error { + return nil +} + +// ConfigureOverrideLimaYaml writes Lima-specific config values from Finch's config to override.yaml at lima config file path. +// ConfigureOverrideLimaYaml will create a override.yaml at the path if it does not exist. +func (lca *limaConfigApplier) ConfigureOverrideLimaYaml() error { + return nil +} + +func (lca *limaConfigApplier) configureDefaultSnapshotter(limaCfg *limayaml.LimaYAML) error { + return nil +} + +func (lca *limaConfigApplier) provisionSnapshotters(limaCfg *limayaml.LimaYAML) error { + return nil +} + +func (lca *limaConfigApplier) provisionSociSnapshotter(limaCfg *limayaml.LimaYAML) { +} + +func (lca *limaConfigApplier) GetFinchConfigPath() string { + return lca.finchConfigPath +} diff --git a/pkg/config/lima_config_applier_remote.go b/pkg/config/lima_config_applier_remote.go new file mode 100644 index 000000000..fa2220cbf --- /dev/null +++ b/pkg/config/lima_config_applier_remote.go @@ -0,0 +1,252 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build (darwin || windows) && !native + +package config + +import ( + "fmt" + "strings" + + "github.com/lima-vm/lima/pkg/limayaml" + "github.com/spf13/afero" + "github.com/xorcare/pointer" + "golang.org/x/exp/slices" + "gopkg.in/yaml.v3" + + "github.com/runfinch/finch/pkg/command" +) + +const ( + sociVersion = "0.5.0" + snapshotterProvisioningScriptHeader = "# snapshotter provisioning script" + sociInstallationProvisioningScriptHeader = snapshotterProvisioningScriptHeader + ": soci" + sociFileNameFormat = "soci-snapshotter-%s-linux-%s.tar.gz" + sociDownloadURLFormat = "https://github.com/awslabs/soci-snapshotter/releases/download/v%s/%s" + sociServiceDownloadURLFormat = "https://raw.githubusercontent.com/awslabs/soci-snapshotter/v%s/soci-snapshotter.service" + //nolint:lll // command string + sociInstallationScriptFormat = `%s +if [ ! -f /usr/local/bin/soci ]; then + # download soci + set -e + curl --retry 2 --retry-max-time 120 -OL "%s" + # move to usr/local/bin + tar -C /usr/local/bin -xvf %s ./soci ./soci-snapshotter-grpc + + # install as a systemd service + curl --retry 2 --retry-max-time 120 -OL "%s" + mv soci-snapshotter.service /usr/local/lib/systemd/system/ + ln -s /usr/local/lib/systemd/system/soci-snapshotter.service /etc/systemd/system/multi-user.target.wants/ + restorecon -v /usr/local/lib/systemd/system/soci-snapshotter.service + systemctl daemon-reload + sudo mkdir -p /usr/local/lib/systemd/system/soci-snapshotter.service.d/ + printf '[Unit]\nPartOf=containerd.service\n\n[Service]\nKillSignal=SIGTERM\n' | sudo tee /usr/local/lib/systemd/system/soci-snapshotter.service.d/finch.conf + systemctl enable --now soci-snapshotter +fi + +# changing containerd config, this seems to get reset on every VM stop/start +if ! grep -q soci /etc/containerd/config.toml; then + printf ' [proxy_plugins.soci]\n type = "snapshot"\n address = "/run/soci-snapshotter-grpc/soci-snapshotter-grpc.sock"\n' >> /etc/containerd/config.toml +fi + +sudo systemctl restart containerd.service +` + + userModeEmulationProvisioningScriptHeader = "# cross-arch tools" + wslDiskFormatScriptHeader = "# wsl disk format script" + qemuPkgInstallationScript = `%s +#!/bin/bash +qemu_pkgs="" +if [ ! -f /usr/bin/qemu-aarch64-static ]; then + qemu_pkgs="$qemu_pkgs qemu-user-static-aarch64" +elif [ ! -f /usr/bin/qemu-aarch64-static ]; then + qemu_pkgs="$qemu_pkgs qemu-user-static-arm" +elif [ ! -f /usr/bin/qemu-aarch64-static ]; then + qemu_pkgs="$qemu_pkgs qemu-user-static-x86" +fi + +if [[ $qemu_pkgs ]]; then + dnf install -y --setopt=install_weak_deps=False ${qemu_pkgs} +fi +` +) + +// NewLimaApplier creates a new LimaConfigApplier that +// applies lima configuration changes by writing to the lima config file on the disk. +func NewLimaApplier( + cfg *Finch, + cmdCreator command.Creator, + fs afero.Fs, + limaDefaultConfigPath string, + limaOverrideConfigPath string, + systemDeps LimaConfigApplierSystemDeps, + finchConfigPath string, +) LimaConfigApplier { + return &limaConfigApplier{ + cfg: cfg, + cmdCreator: cmdCreator, + fs: fs, + limaDefaultConfigPath: limaDefaultConfigPath, + limaOverrideConfigPath: limaOverrideConfigPath, + systemDeps: systemDeps, + finchConfigPath: finchConfigPath, + } +} + +// ConfigureDefaultLimaYaml writes Lima-specific config values from Finch's config to default.yaml at lima config file path. +// ConfigureDefaultLimaYaml will create a default.yaml at the path if it does not exist. +func (lca *limaConfigApplier) ConfigureDefaultLimaYaml() error { + if err := afero.WriteFile(lca.fs, lca.limaDefaultConfigPath, []byte(""), 0o600); err != nil { + return fmt.Errorf("failed to create the an empty lima config file: %w", err) + } + + var limaCfg limayaml.LimaYAML + + if limaCfg.Rosetta.Enabled == nil { + limaCfg.Rosetta.Enabled = pointer.Bool(false) + limaCfg.Rosetta.BinFmt = pointer.Bool(false) + } + + cfgAfterInit, err := lca.configureVirtualizationFramework(&limaCfg) + if err != nil { + return fmt.Errorf("failed to apply init-only config values: %w", err) + } + limaCfg = *cfgAfterInit + + limaCfgBytes, err := yaml.Marshal(limaCfg) + if err != nil { + return fmt.Errorf("failed to marshal the lima config file: %w", err) + } + + if err := afero.WriteFile(lca.fs, lca.limaDefaultConfigPath, limaCfgBytes, 0o600); err != nil { + return fmt.Errorf("failed to write to the lima config file: %w", err) + } + + return nil +} + +// ConfigureOverrideLimaYaml writes Lima-specific config values from Finch's config to override.yaml at lima config file path. +// ConfigureOverrideLimaYaml will create a override.yaml at the path if it does not exist. +func (lca *limaConfigApplier) ConfigureOverrideLimaYaml() error { + if err := afero.WriteFile(lca.fs, lca.limaOverrideConfigPath, []byte(""), 0o600); err != nil { + return fmt.Errorf("failed to create the an empty lima config file: %w", err) + } + var limaCfg limayaml.LimaYAML + + lca.configureCPUs(&limaCfg) + lca.configureMemory(&limaCfg) + lca.configureMounts(&limaCfg) + if *lca.cfg.VMType != "wsl2" && len(limaCfg.AdditionalDisks) == 0 { + limaCfg.AdditionalDisks = append(limaCfg.AdditionalDisks, limayaml.Disk{ + Name: "finch", + }) + } + + err := lca.provisionSnapshotters(&limaCfg) + if err != nil { + return fmt.Errorf("failed to provision snapshotters: %w", err) + } + + err = lca.configureDefaultSnapshotter(&limaCfg) + if err != nil { + return fmt.Errorf("failed to configure default snapshotter: %w", err) + } + + if *lca.cfg.VMType == "wsl2" { + ensureWslDiskFormatScript(&limaCfg) + } + + limaCfgBytes, err := yaml.Marshal(limaCfg) + if err != nil { + return fmt.Errorf("failed to marshal the lima config file: %w", err) + } + + if err := afero.WriteFile(lca.fs, lca.limaOverrideConfigPath, limaCfgBytes, 0o600); err != nil { + return fmt.Errorf("failed to write to the lima config file: %w", err) + } + + return nil +} + +func validateSnapshotter(snapshotter string) error { + supportedSnapshotters := []string{"overlayfs", "soci"} + if !slices.Contains(supportedSnapshotters, snapshotter) { + return fmt.Errorf("snapshotter %s is not supported", snapshotter) + } + return nil +} + +func (lca *limaConfigApplier) configureDefaultSnapshotter(limaCfg *limayaml.LimaYAML) error { + if len(lca.cfg.Snapshotters) == 0 { + limaCfg.Env = map[string]string{} + return nil + } + + snapshotter := lca.cfg.Snapshotters[0] + err := validateSnapshotter(snapshotter) + if err != nil { + return err + } + + limaCfg.Env = map[string]string{"CONTAINERD_SNAPSHOTTER": snapshotter} + + return nil +} + +func (lca *limaConfigApplier) provisionSnapshotters(limaCfg *limayaml.LimaYAML) error { + for _, snapshotter := range lca.cfg.Snapshotters { + switch snapshotter { + case "soci": + lca.provisionSociSnapshotter(limaCfg) + case "overlayfs": + continue + default: + return fmt.Errorf("snapshotter %s is not supported", snapshotter) + } + } + + return nil +} + +func (lca *limaConfigApplier) provisionSociSnapshotter(limaCfg *limayaml.LimaYAML) { + sociFileName := fmt.Sprintf(sociFileNameFormat, sociVersion, lca.systemDeps.Arch()) + sociDownloadURL := fmt.Sprintf(sociDownloadURLFormat, sociVersion, sociFileName) + sociServiceDownloadURL := fmt.Sprintf(sociServiceDownloadURLFormat, sociVersion) + sociInstallationScript := fmt.Sprintf(sociInstallationScriptFormat, sociInstallationProvisioningScriptHeader, + sociDownloadURL, sociFileName, sociServiceDownloadURL) + limaCfg.Provision = append(limaCfg.Provision, limayaml.Provision{ + Mode: "system", + Script: sociInstallationScript, + }) +} + +func ensureWslDiskFormatScript(limaCfg *limayaml.LimaYAML) { + if hasScript := findWslDiskFormatScript(limaCfg); !hasScript { + limaCfg.Provision = append(limaCfg.Provision, limayaml.Provision{ + Mode: "system", + Script: fmt.Sprintf(`%s +#!/bin/bash +mkdir -p /mnt/lima-finch +mount "$(blkid -s TYPE -t LABEL=FinchDataDisk -o device)" /mnt/lima-finch +`, wslDiskFormatScriptHeader), + }) + } +} + +func findWslDiskFormatScript(limaCfg *limayaml.LimaYAML) bool { + hasWslDiskFormatScript := false + for _, prov := range limaCfg.Provision { + trimmed := strings.Trim(prov.Script, " ") + if !hasWslDiskFormatScript && strings.HasPrefix(trimmed, wslDiskFormatScriptHeader) { + hasWslDiskFormatScript = true + break + } + } + + return hasWslDiskFormatScript +} + +func (lca *limaConfigApplier) GetFinchConfigPath() string { + return lca.finchConfigPath +} diff --git a/pkg/config/lima_config_applier_windows.go b/pkg/config/lima_config_applier_windows.go index a69c68fb3..63bf286a5 100644 --- a/pkg/config/lima_config_applier_windows.go +++ b/pkg/config/lima_config_applier_windows.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build windows +//go:build windows && !native package config @@ -26,3 +26,15 @@ func (lca *limaConfigApplier) configureVirtualizationFramework(limaCfg *limayaml } return limaCfg, nil } + +func (lca *limaConfigApplier) configureCPUs(limaCfg *limayaml.LimaYAML) *limayaml.LimaYAML { + return limaCfg +} + +func (lca *limaConfigApplier) configureMemory(limaCfg *limayaml.LimaYAML) *limayaml.LimaYAML { + return limaCfg +} + +func (lca *limaConfigApplier) configureMounts(limaCfg *limayaml.LimaYAML) *limayaml.LimaYAML { + return limaCfg +} diff --git a/pkg/config/nerdctl_config_applier.go b/pkg/config/nerdctl_config_applier.go index 63254d6f5..8864d98d7 100644 --- a/pkg/config/nerdctl_config_applier.go +++ b/pkg/config/nerdctl_config_applier.go @@ -7,20 +7,16 @@ import ( "errors" "fmt" "path" - "path/filepath" "strings" toml "github.com/pelletier/go-toml" - "github.com/pkg/sftp" "github.com/spf13/afero" - "github.com/spf13/afero/sftpfs" "github.com/runfinch/finch/pkg/fssh" ) const ( - nerdctlNamespace = "finch" - nerdctlRootfulCfgPath = "/etc/nerdctl/nerdctl.toml" + nerdctlNamespace = "finch" ) type nerdctlConfigApplier struct { @@ -68,59 +64,6 @@ func addLineToBashrc(fs afero.Fs, profileFilePath string, profStr string, cmd st return profStr, nil } -// updateEnvironment adds variables to the user's shell's environment. Currently it uses ~/.bashrc because -// Bash is the default shell and Bash will not load ~/.profile if ~/.bash_profile exists (which it does). -// ~/.bash_profile sources ~/.bashrc, so ~/.bashrc is currently the best place to define additional variables. -// The [GNU docs for Bash] explain how these files work together in more details. -// The default location of DOCKER_CONFIG is ~/.docker/config.json. This config change sets the location to -// ~/.finch/config.json, but from the perspective of macOS (/Users//.finch/config.json). -// The reason that we don't set environment variables inside /root/.bashrc is that the vars inside it are -// not able to be picked up even if we specify `sudo -E`. We have to switch to root user in order to access them, while -// normally we would access the VM as the regular user. -// For more information on the variable, see the registry nerdctl docs. -// -// [GNU docs for Bash]: https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html -// -// [registry nerdctl docs]: https://github.com/containerd/nerdctl/blob/master/docs/registry.md - -func updateEnvironment(fs afero.Fs, fc *Finch, finchDir, homeDir, limaVMHomeDir string) error { - cmdArr := []string{ - `export DOCKER_CONFIG="$FINCH_DIR"`, - "[ -L /usr/local/bin/docker-credential-ecr-login ] " + - `|| sudo ln -s "$FINCH_DIR"/cred-helpers/docker-credential-ecr-login /usr/local/bin/`, - `[ -L /root/.aws ] || sudo ln -fs "$AWS_DIR" /root/.aws`, - } - - awsDir := fmt.Sprintf("%s/.aws", homeDir) - - if *fc.VMType == "wsl2" { - cmdArr = append([]string{ - fmt.Sprintf(`FINCH_DIR="$(/usr/bin/wslpath '%s')"`, finchDir), - fmt.Sprintf(`AWS_DIR="$(/usr/bin/wslpath '%s')"`, awsDir), - }, cmdArr...) - } else { - cmdArr = append([]string{ - fmt.Sprintf(`FINCH_DIR=%s`, finchDir), - fmt.Sprintf(`AWS_DIR=%s`, awsDir), - }, cmdArr...) - } - - profileFilePath := fmt.Sprintf("%s/.bashrc", limaVMHomeDir) - profBuf, err := afero.ReadFile(fs, profileFilePath) - if err != nil { - return fmt.Errorf("failed to read config file %q: %w", profileFilePath, err) - } - profStr := string(profBuf) - for _, element := range cmdArr { - profStr, err = addLineToBashrc(fs, profileFilePath, profStr, element) - if err != nil { - return err - } - } - - return nil -} - // updateNerdctlConfig reads from the nerdctl config and updates values. func updateNerdctlConfig(fs afero.Fs, homeDir string, rootless bool) error { nerdctlRootlessCfgPath := fmt.Sprintf("%s/.config/nerdctl/nerdctl.toml", homeDir) @@ -166,68 +109,24 @@ func updateNerdctlConfig(fs afero.Fs, homeDir string, rootless bool) error { return nil } -func getLimaHomeDir(localFs afero.Fs, remoteFs afero.Fs, limaInstanceDir string, cfg *Finch) (string, error) { - var envB []byte - var envErr error - - if *cfg.VMType == "wsl2" { - envB, envErr = afero.ReadFile(localFs, filepath.Join(limaInstanceDir, "cidata", "lima.env")) - } else { - envB, envErr = afero.ReadFile(remoteFs, "/mnt/lima-cidata/lima.env") - } - - if envErr != nil { - return "", envErr - } - - var user, home string - lines := strings.Split(string(envB), "\n") - for _, l := range lines { - if strings.Contains(l, "LIMA_CIDATA_USER") { - user = strings.Split(l, "=")[1] - } else if strings.Contains(l, "LIMA_CIDATA_HOME") { - home = strings.Split(l, "=")[1] - } - } - - if home != "" { - return home, nil - } - - return "/home/" + user + ".linux", nil -} - -// Apply gets SSH and SFTP clients and uses them to update the nerdctl config. +// Apply updates the nerdctl config. func (nca *nerdctlConfigApplier) Apply(remoteAddr string) error { - user := "root" - sshCfg, err := fssh.NewClientConfig(nca.fs, user, nca.privateKeyPath) - if err != nil { - return fmt.Errorf("failed to create ssh client config: %w", err) - } - - sshClient, err := nca.dialer.Dial("tcp", remoteAddr, sshCfg) + nFs, err := nerdctlFs(nca.fs, nca.privateKeyPath, remoteAddr) if err != nil { - return fmt.Errorf("failed to setup ssh client: %w", err) + return fmt.Errorf("failed to get nerdctlFs: %w", err) } - sftpClient, err := sftp.NewClient(sshClient) - if err != nil { - return fmt.Errorf("failed to setup sftp client: %w", err) - } - - sftpFs := sftpfs.New(sftpClient) - - limaHomeDir, err := getLimaHomeDir(nca.fs, sftpFs, nca.limaInstancePath, nca.fc) + homeDir, err := getHomeDir(nca.fs, nFs, nca.limaInstancePath, nca.fc, nca.homeDir) if err != nil { return fmt.Errorf("failed to get lima home dir: %w", err) } // rootless hardcoded to false for now to match our finch.yaml file - if err := updateNerdctlConfig(sftpFs, limaHomeDir, false); err != nil { + if err := updateNerdctlConfig(nca.fs, homeDir, false); err != nil { return fmt.Errorf("failed to update the nerdctl config file: %w", err) } - if err := updateEnvironment(sftpFs, nca.fc, nca.finchDir, nca.homeDir, limaHomeDir); err != nil { + if err := updateEnvironment(nFs, nca.fc, nca.finchDir, homeDir, nca.homeDir); err != nil { return fmt.Errorf("failed to update the user's .profile file: %w", err) } return nil diff --git a/pkg/config/nerdctl_config_applier_native.go b/pkg/config/nerdctl_config_applier_native.go new file mode 100644 index 000000000..a5a149f3e --- /dev/null +++ b/pkg/config/nerdctl_config_applier_native.go @@ -0,0 +1,23 @@ +//go:build linux || native + +package config + +import ( + "github.com/spf13/afero" +) + +const nerdctlRootfulCfgPath = "/etc/finch/nerdctl/nerdctl.toml" + +func nerdctlFs(hostFs afero.Fs, _ string, _ string) (afero.Fs, error) { + return hostFs, nil +} + +// updateEnvironment is a noop on Linux since Finch does not fully control the user's environment +// on native Linux, unlike on macOS/Windows, via a VM. +func updateEnvironment(_ afero.Fs, _ *Finch, _, _, _ string) error { + return nil +} + +func getHomeDir(_ afero.Fs, _ afero.Fs, _ string, _ *Finch, systemHomeDir string) (string, error) { + return systemHomeDir, nil +} diff --git a/pkg/config/nerdctl_config_applier_remote.go b/pkg/config/nerdctl_config_applier_remote.go new file mode 100644 index 000000000..901da2c5d --- /dev/null +++ b/pkg/config/nerdctl_config_applier_remote.go @@ -0,0 +1,123 @@ +//go:build (darwin || windows) && !native + +package config + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/pkg/sftp" + "github.com/spf13/afero" + "github.com/spf13/afero/sftpfs" + + "github.com/runfinch/finch/pkg/fssh" +) + +const nerdctlRootfulCfgPath = "/etc/nerdctl/nerdctl.toml" + +func nerdctlFs(hostFs afero.Fs, privateKeyPath string, remoteAddr string) (afero.Fs, error) { + user := "root" + sshCfg, err := fssh.NewClientConfig(hostFs, user, privateKeyPath) + if err != nil { + return nil, fmt.Errorf("failed to create ssh client config: %w", err) + } + + dialer := fssh.NewDialer() + + sshClient, err := dialer.Dial("tcp", remoteAddr, sshCfg) + if err != nil { + return nil, fmt.Errorf("failed to setup ssh client: %w", err) + } + + sftpClient, err := sftp.NewClient(sshClient) + if err != nil { + return nil, fmt.Errorf("failed to setup sftp client: %w", err) + } + + return sftpfs.New(sftpClient), nil +} + +// updateEnvironment adds variables to the user's shell's environment. Currently it uses ~/.bashrc because +// Bash is the default shell and Bash will not load ~/.profile if ~/.bash_profile exists (which it does). +// ~/.bash_profile sources ~/.bashrc, so ~/.bashrc is currently the best place to define additional variables. +// The [GNU docs for Bash] explain how these files work together in more details. +// The default location of DOCKER_CONFIG is ~/.docker/config.json. This config change sets the location to +// ~/.finch/config.json, but from the perspective of macOS (/Users//.finch/config.json). +// The reason that we don't set environment variables inside /root/.bashrc is that the vars inside it are +// not able to be picked up even if we specify `sudo -E`. We have to switch to root user in order to access them, while +// normally we would access the VM as the regular user. +// For more information on the variable, see the registry nerdctl docs. +// +// [GNU docs for Bash]: https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html +// +// [registry nerdctl docs]: https://github.com/containerd/nerdctl/blob/master/docs/registry.md + +func updateEnvironment(fs afero.Fs, fc *Finch, finchDir, homeDir, limaVMHomeDir string) error { + cmdArr := []string{ + `export DOCKER_CONFIG="$FINCH_DIR"`, + "[ -L /usr/local/bin/docker-credential-ecr-login ] " + + `|| sudo ln -s "$FINCH_DIR"/cred-helpers/docker-credential-ecr-login /usr/local/bin/`, + `[ -L /root/.aws ] || sudo ln -fs "$AWS_DIR" /root/.aws`, + } + + awsDir := fmt.Sprintf("%s/.aws", homeDir) + + if *fc.VMType == "wsl2" { + cmdArr = append([]string{ + fmt.Sprintf(`FINCH_DIR="$(/usr/bin/wslpath '%s')"`, finchDir), + fmt.Sprintf(`AWS_DIR="$(/usr/bin/wslpath '%s')"`, awsDir), + }, cmdArr...) + } else { + cmdArr = append([]string{ + fmt.Sprintf(`FINCH_DIR=%s`, finchDir), + fmt.Sprintf(`AWS_DIR=%s`, awsDir), + }, cmdArr...) + } + + profileFilePath := fmt.Sprintf("%s/.bashrc", limaVMHomeDir) + profBuf, err := afero.ReadFile(fs, profileFilePath) + if err != nil { + return fmt.Errorf("failed to read config file %q: %w", profileFilePath, err) + } + profStr := string(profBuf) + for _, element := range cmdArr { + profStr, err = addLineToBashrc(fs, profileFilePath, profStr, element) + if err != nil { + return err + } + } + + return nil +} + +func getHomeDir(localFs afero.Fs, remoteFs afero.Fs, limaInstanceDir string, cfg *Finch, _ string) (string, error) { + var envB []byte + var envErr error + + if *cfg.VMType == "wsl2" { + envB, envErr = afero.ReadFile(localFs, filepath.Join(limaInstanceDir, "cidata", "lima.env")) + } else { + envB, envErr = afero.ReadFile(remoteFs, "/mnt/lima-cidata/lima.env") + } + + if envErr != nil { + return "", envErr + } + + var user, home string + lines := strings.Split(string(envB), "\n") + for _, l := range lines { + if strings.Contains(l, "LIMA_CIDATA_USER") { + user = strings.Split(l, "=")[1] + } else if strings.Contains(l, "LIMA_CIDATA_HOME") { + home = strings.Split(l, "=")[1] + } + } + + if home != "" { + return home, nil + } + + return "/home/" + user + ".linux", nil +} diff --git a/pkg/config/nerdctl_config_applier_test.go b/pkg/config/nerdctl_config_applier_test.go index fa6ca9738..fd013551a 100644 --- a/pkg/config/nerdctl_config_applier_test.go +++ b/pkg/config/nerdctl_config_applier_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package config import ( diff --git a/pkg/config/validate_darwin.go b/pkg/config/validate_darwin.go index 141fedffe..10fdc8a2c 100644 --- a/pkg/config/validate_darwin.go +++ b/pkg/config/validate_darwin.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin +//go:build darwin && !native package config diff --git a/pkg/config/validate_natvie.go b/pkg/config/validate_natvie.go new file mode 100644 index 000000000..1d64d271b --- /dev/null +++ b/pkg/config/validate_natvie.go @@ -0,0 +1,15 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux || native + +package config + +import ( + "github.com/runfinch/finch/pkg/flog" + "github.com/runfinch/finch/pkg/fmemory" +) + +func validate(_ *Finch, _ flog.Logger, _ LoadSystemDeps, _ fmemory.Memory) error { + return nil +} diff --git a/pkg/config/validate_windows.go b/pkg/config/validate_windows.go index 0eb78c841..4518a6cff 100644 --- a/pkg/config/validate_windows.go +++ b/pkg/config/validate_windows.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build windows +//go:build windows && !native package config diff --git a/pkg/disk/disk_unix.go b/pkg/disk/disk_darwin.go similarity index 99% rename from pkg/disk/disk_unix.go rename to pkg/disk/disk_darwin.go index dd36ae036..625fcef59 100644 --- a/pkg/disk/disk_unix.go +++ b/pkg/disk/disk_darwin.go @@ -1,8 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows -// +build !windows +//go:build darwin && !native +// +build darwin,!native package disk diff --git a/pkg/disk/disk_unix_test.go b/pkg/disk/disk_darwin_test.go similarity index 99% rename from pkg/disk/disk_unix_test.go rename to pkg/disk/disk_darwin_test.go index 6916fa058..522763af5 100644 --- a/pkg/disk/disk_unix_test.go +++ b/pkg/disk/disk_darwin_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows +//go:build darwin package disk diff --git a/pkg/disk/disk_native.go b/pkg/disk/disk_native.go new file mode 100644 index 000000000..7fc13d506 --- /dev/null +++ b/pkg/disk/disk_native.go @@ -0,0 +1,25 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux || native +// +build linux native + +package disk + +// EnsureUserDataDisk checks the current disk configuration and fixes it if needed. +func (m *userDataDiskManager) EnsureUserDataDisk() error { + return nil +} + +// DetachUserDataDisk unmounts the disk in wsl. +func (m *userDataDiskManager) DetachUserDataDisk() error { + return nil +} + +func (m *userDataDiskManager) createDisk(_ string) error { + return nil +} + +func (m *userDataDiskManager) attachDisk(_ string) error { + return nil +} From 4ad889dc26a9f465dbfd946d3f069f1f1046130b Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 9 Jul 2024 18:09:23 -0400 Subject: [PATCH 02/37] fix Makefile Signed-off-by: Justin Alvarez --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 0f384e941..9be2b064b 100644 --- a/Makefile +++ b/Makefile @@ -224,11 +224,11 @@ finch-macos: finch-unix finch-unix: finch-general -finch-native: GO_BUILD_TAGS += "native" +finch-native: GO_BUILD_TAGS += native finch-native: finch-general finch-general: - $(GO) build -ldflags $(LDFLAGS) -tags $(GO_BUILD_TAGS) -o $(OUTDIR)/bin/$(BINARYNAME) $(PACKAGE)/cmd/finch + $(GO) build -ldflags $(LDFLAGS) -tags "$(GO_BUILD_TAGS)" -o $(OUTDIR)/bin/$(BINARYNAME) $(PACKAGE)/cmd/finch .PHONY: release release: check-licenses all download-licenses From 3bdf5c83e87181988b2568555b59c7fd10fdcc83 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 9 Jul 2024 19:27:32 -0400 Subject: [PATCH 03/37] refactor lima_cmd_creator => nerdctl_cmd_creator Signed-off-by: Justin Alvarez --- cmd/finch/main.go | 16 +- cmd/finch/main_darwin.go | 4 +- cmd/finch/main_native.go | 2 +- cmd/finch/main_windows.go | 2 +- cmd/finch/nerdctl.go | 20 +- cmd/finch/nerdctl_darwin_test.go | 184 +++++++------ cmd/finch/nerdctl_native.go | 2 +- cmd/finch/nerdctl_remote.go | 2 +- cmd/finch/nerdctl_shared_test.go | 26 +- cmd/finch/nerdctl_windows_test.go | 220 +++++++-------- cmd/finch/support_bundle.go | 14 +- cmd/finch/support_bundle_remote.go | 2 +- cmd/finch/version.go | 6 +- cmd/finch/version_test.go | 72 ++--- cmd/finch/virtual_machine_init.go | 10 +- cmd/finch/virtual_machine_init_test.go | 56 ++-- cmd/finch/virtual_machine_local.go | 2 +- cmd/finch/virtual_machine_remote.go | 14 +- cmd/finch/virtual_machine_remove.go | 8 +- cmd/finch/virtual_machine_remove_test.go | 12 +- cmd/finch/virtual_machine_start.go | 12 +- cmd/finch/virtual_machine_start_test.go | 56 ++-- cmd/finch/virtual_machine_status.go | 6 +- cmd/finch/virtual_machine_status_test.go | 36 +-- cmd/finch/virtual_machine_stop.go | 8 +- cmd/finch/virtual_machine_stop_test.go | 12 +- cmd/finch/virtual_machine_test.go | 32 +-- pkg/command/nerdctl.go | 52 ++-- pkg/command/nerdctl_native.go | 27 +- pkg/command/nerdctl_remote.go | 24 +- pkg/command/nerdctl_test.go | 6 +- pkg/config/config.go | 9 +- pkg/config/config_darwin.go | 14 +- pkg/config/config_native.go | 2 +- pkg/config/config_test.go | 101 ++++--- pkg/config/config_windows.go | 9 +- pkg/config/defaults_darwin_test.go | 167 ++++++++++++ pkg/config/defaults_test.go | 257 +----------------- pkg/config/defaults_windows_test.go | 46 ++++ pkg/config/lima_config_applier_darwin_test.go | 151 +++++----- pkg/config/lima_config_applier_native.go | 4 +- pkg/config/nerdctl_config_applier.go | 6 +- pkg/config/nerdctl_config_applier_test.go | 18 +- pkg/config/validate_darwin_test.go | 30 +- pkg/dependency/vmnet/sudoers_file_unix.go | 4 +- pkg/dependency/vmnet/vmnet_unix.go | 4 +- pkg/disk/disk.go | 6 +- pkg/disk/disk_darwin.go | 6 +- pkg/disk/disk_darwin_test.go | 78 ++++-- pkg/lima/lima.go | 4 +- ...ator.go => command_nerdctl_cmd_creator.go} | 42 +-- pkg/mocks/lima_cmd_creator_system_deps.go | 108 -------- pkg/mocks/nerdctl_cmd_creator_system_deps.go | 108 ++++++++ pkg/mocks/pkg_support_config.go | 62 ----- pkg/mocks/pkg_support_support.go | 49 ---- pkg/support/support.go | 8 +- pkg/support/support_test.go | 14 +- 57 files changed, 1095 insertions(+), 1157 deletions(-) create mode 100644 pkg/config/defaults_darwin_test.go create mode 100644 pkg/config/defaults_windows_test.go rename pkg/mocks/{command_lima_cmd_creator.go => command_nerdctl_cmd_creator.go} (55%) delete mode 100644 pkg/mocks/lima_cmd_creator_system_deps.go create mode 100644 pkg/mocks/nerdctl_cmd_creator_system_deps.go delete mode 100644 pkg/mocks/pkg_support_config.go delete mode 100644 pkg/mocks/pkg_support_support.go diff --git a/cmd/finch/main.go b/cmd/finch/main.go index 9d3f0b952..f596f148d 100644 --- a/cmd/finch/main.go +++ b/cmd/finch/main.go @@ -111,7 +111,7 @@ var newApp = func( return nil } - lcc := command.NewLimaCmdCreator(ecc, + ncc := command.NewNerdctlCmdCreator(ecc, logger, fp.LimaHomePath(), fp.LimactlPath(), @@ -125,17 +125,17 @@ var newApp = func( support.NewBundleConfig(fp, finchRootPath), fp, ecc, - lcc, + ncc, lima, ) // append nerdctl commands - allCommands := initializeNerdctlCommands(lcc, ecc, logger, fs, fc) + allCommands := initializeNerdctlCommands(ncc, ecc, logger, fs, fc) // append finch specific commands allCommands = append(allCommands, - newVersionCommand(lcc, logger, stdOut), - virtualMachineCommands(logger, fp, lcc, ecc, fs, fc, home, finchRootPath), - newSupportBundleCommand(logger, supportBundleBuilder, lcc), + newVersionCommand(ncc, logger, stdOut), + virtualMachineCommands(logger, fp, ncc, ecc, fs, fc, home, finchRootPath), + newSupportBundleCommand(logger, supportBundleBuilder, ncc), newGenDocsCommand(rootCmd, logger, fs, system.NewStdLib()), ) @@ -145,13 +145,13 @@ var newApp = func( } func initializeNerdctlCommands( - lcc command.LimaCmdCreator, + ncc command.NerdctlCmdCreator, ecc command.Creator, logger flog.Logger, fs afero.Fs, fc *config.Finch, ) []*cobra.Command { - nerdctlCommandCreator := newNerdctlCommandCreator(lcc, ecc, system.NewStdLib(), logger, fs, fc) + nerdctlCommandCreator := newNerdctlCommandCreator(ncc, ecc, system.NewStdLib(), logger, fs, fc) var allNerdctlCommands []*cobra.Command for cmdName, cmdDescription := range nerdctlCmds { allNerdctlCommands = append(allNerdctlCommands, nerdctlCommandCreator.create(cmdName, cmdDescription)) diff --git a/cmd/finch/main_darwin.go b/cmd/finch/main_darwin.go index c694160c9..852390a0b 100644 --- a/cmd/finch/main_darwin.go +++ b/cmd/finch/main_darwin.go @@ -23,7 +23,7 @@ func dependencies( fc *config.Finch, fp path.Finch, fs afero.Fs, - lcc command.LimaCmdCreator, + ncc command.NerdctlCmdCreator, logger flog.Logger, finchRootPath string, ) []*dependency.Group { @@ -37,6 +37,6 @@ func dependencies( finchRootPath, system.NewStdLib().Arch(), ), - vmnet.NewDependencyGroup(ecc, lcc, fs, fp, logger), + vmnet.NewDependencyGroup(ecc, ncc, fs, fp, logger), } } diff --git a/cmd/finch/main_native.go b/cmd/finch/main_native.go index 82be5fcd0..24b7e3bce 100644 --- a/cmd/finch/main_native.go +++ b/cmd/finch/main_native.go @@ -20,7 +20,7 @@ func dependencies( _ *config.Finch, _ path.Finch, _ afero.Fs, - _ command.LimaCmdCreator, + _ command.NerdctlCmdCreator, _ flog.Logger, _ string, ) []*dependency.Group { diff --git a/cmd/finch/main_windows.go b/cmd/finch/main_windows.go index af78a5679..cbabb3fab 100644 --- a/cmd/finch/main_windows.go +++ b/cmd/finch/main_windows.go @@ -24,7 +24,7 @@ func dependencies( fc *config.Finch, fp path.Finch, fs afero.Fs, - _ command.LimaCmdCreator, + _ command.NerdctlCmdCreator, logger flog.Logger, finchDir string, ) []*dependency.Group { diff --git a/cmd/finch/nerdctl.go b/cmd/finch/nerdctl.go index fc16a4193..b658d68b0 100644 --- a/cmd/finch/nerdctl.go +++ b/cmd/finch/nerdctl.go @@ -38,7 +38,7 @@ type NerdctlCommandSystemDeps interface { } type nerdctlCommandCreator struct { - lcc command.LimaCmdCreator + ncc command.NerdctlCmdCreator ecc command.Creator systemDeps NerdctlCommandSystemDeps logger flog.Logger @@ -52,14 +52,14 @@ type ( ) func newNerdctlCommandCreator( - lcc command.LimaCmdCreator, + ncc command.NerdctlCmdCreator, ecc command.Creator, systemDeps NerdctlCommandSystemDeps, logger flog.Logger, fs afero.Fs, fc *config.Finch, ) *nerdctlCommandCreator { - return &nerdctlCommandCreator{lcc: lcc, ecc: ecc, systemDeps: systemDeps, logger: logger, fs: fs, fc: fc} + return &nerdctlCommandCreator{ncc: ncc, ecc: ecc, systemDeps: systemDeps, logger: logger, fs: fs, fc: fc} } func (ncc *nerdctlCommandCreator) create(cmdName string, cmdDesc string) *cobra.Command { @@ -70,14 +70,14 @@ func (ncc *nerdctlCommandCreator) create(cmdName string, cmdDesc string) *cobra. // the args passed to nerdctlCommand.run will be empty because // cobra will try to parse `-d alpine` as if alpine is the value of the `-d` flag. DisableFlagParsing: true, - RunE: newNerdctlCommand(ncc.lcc, ncc.ecc, ncc.systemDeps, ncc.logger, ncc.fs, ncc.fc).runAdapter, + RunE: newNerdctlCommand(ncc.ncc, ncc.ecc, ncc.systemDeps, ncc.logger, ncc.fs, ncc.fc).runAdapter, } return command } type nerdctlCommand struct { - lcc command.LimaCmdCreator + ncc command.NerdctlCmdCreator ecc command.Creator systemDeps NerdctlCommandSystemDeps logger flog.Logger @@ -86,14 +86,14 @@ type nerdctlCommand struct { } func newNerdctlCommand( - lcc command.LimaCmdCreator, + ncc command.NerdctlCmdCreator, ecc command.Creator, systemDeps NerdctlCommandSystemDeps, logger flog.Logger, fs afero.Fs, fc *config.Finch, ) *nerdctlCommand { - return &nerdctlCommand{lcc: lcc, ecc: ecc, systemDeps: systemDeps, logger: logger, fs: fs, fc: fc} + return &nerdctlCommand{ncc: ncc, ecc: ecc, systemDeps: systemDeps, logger: logger, fs: fs, fc: fc} } func (nc *nerdctlCommand) runAdapter(cmd *cobra.Command, args []string) error { @@ -101,7 +101,7 @@ func (nc *nerdctlCommand) runAdapter(cmd *cobra.Command, args []string) error { } func (nc *nerdctlCommand) run(cmdName string, args []string) error { - err := nc.assertVMIsRunning(nc.lcc, nc.logger) + err := nc.assertVMIsRunning(nc.ncc, nc.logger) if err != nil { return err } @@ -276,10 +276,10 @@ func (nc *nerdctlCommand) run(cmdName string, args []string) error { limaArgs = append(limaArgs, nerdctlArgs...) if nc.shouldReplaceForHelp(cmdName, args) { - return nc.lcc.RunWithReplacingStdout([]command.Replacement{{Source: "nerdctl", Target: "finch"}}, limaArgs...) + return nc.ncc.RunWithReplacingStdout([]command.Replacement{{Source: "nerdctl", Target: "finch"}}, limaArgs...) } - return nc.lcc.Create(limaArgs...).Run() + return nc.ncc.Create(limaArgs...).Run() } // shouldReplaceForHelp returns true if we should replace "nerdctl" with "finch" for the output of the given command. diff --git a/cmd/finch/nerdctl_darwin_test.go b/cmd/finch/nerdctl_darwin_test.go index 122ff91fd..12c8e911c 100644 --- a/cmd/finch/nerdctl_darwin_test.go +++ b/cmd/finch/nerdctl_darwin_test.go @@ -39,9 +39,9 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { Use: "info", }, args: []string{}, - mockSvc: func(lcc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps) { + mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -49,7 +49,7 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { ncsd.EXPECT().LookupEnv("AWS_SESSION_TOKEN").Return("", false) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "info").Return(c) + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "info").Return(c) c.EXPECT().Run() }, }, @@ -61,13 +61,13 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) ecc := mocks.NewCommandCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) - tc.mockSvc(lcc, logger, ctrl, ncsd) + tc.mockSvc(ncc, logger, ctrl, ncsd) - assert.NoError(t, newNerdctlCommand(lcc, ecc, ncsd, logger, nil, &config.Finch{}).runAdapter(tc.cmd, tc.args)) + assert.NoError(t, newNerdctlCommand(ncc, ecc, ncsd, logger, nil, &config.Finch{}).runAdapter(tc.cmd, tc.args)) }) } } @@ -83,7 +83,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr error mockSvc func( t *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, ecc *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -99,7 +99,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -107,7 +107,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -115,7 +115,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("AWS_SESSION_TOKEN").Return("", false) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "build", "-t", "demo", ".").Return(c) + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "build", "-t", "demo", ".").Return(c) c.EXPECT().Run() }, }, @@ -127,7 +127,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -135,7 +135,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -144,7 +144,7 @@ func TestNerdctlCommand_run(t *testing.T) { logger.EXPECT().SetLevel(flog.Debug) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "pull", "test:tag").Return(c) + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "pull", "test:tag").Return(c) c.EXPECT().Run() }, }, @@ -156,7 +156,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -164,7 +164,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -175,7 +175,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("ARG3") ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "-e", "ARG1=val1", "alpine:latest", "env").Return(c) c.EXPECT().Run() }, @@ -188,7 +188,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -196,7 +196,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -206,7 +206,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("ARG2") ncsd.EXPECT().LookupEnv("ARG3").Return("val3", true) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "-e", "ARG3=val3", "alpine:latest", "env").Return(c) c.EXPECT().Run() }, @@ -219,7 +219,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -227,7 +227,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().SetLevel(flog.Debug) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") @@ -238,7 +238,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("ARG2") ncsd.EXPECT().LookupEnv("ARG3").Return("val3", true) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "-e", "ARG3=val3", "alpine:latest", "env").Return(c) c.EXPECT().Run() }, @@ -251,7 +251,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( t *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -262,7 +262,7 @@ func TestNerdctlCommand_run(t *testing.T) { require.NoError(t, afero.WriteFile(fs, envFilePath, []byte(envFileStr), 0o600)) getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -272,7 +272,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("ARG2") ncsd.EXPECT().LookupEnv("NOTSETARG") ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) - lcc.EXPECT(). + ncc.EXPECT(). Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "-e", "ARG1=val1", "alpine:latest", "env"). Return(c) c.EXPECT().Run() @@ -286,7 +286,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( t *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -297,7 +297,7 @@ func TestNerdctlCommand_run(t *testing.T) { require.NoError(t, afero.WriteFile(fs, envFilePath, []byte(envFileStr), 0o600)) getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().SetLevel(flog.Debug) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") @@ -308,7 +308,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("ARG2") ncsd.EXPECT().LookupEnv("NOTSETARG") ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) - lcc.EXPECT(). + ncc.EXPECT(). Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "-e", "ARG1=val1", "alpine:latest", "env"). Return(c) c.EXPECT().Run() @@ -322,7 +322,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( t *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -333,7 +333,7 @@ func TestNerdctlCommand_run(t *testing.T) { require.NoError(t, afero.WriteFile(fs, envFilePath, []byte(envFileStr), 0o600)) getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -343,7 +343,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("ARG2").Return("val2", true) ncsd.EXPECT().LookupEnv("NOTSETARG") ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) - lcc.EXPECT(). + ncc.EXPECT(). Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "-e", "ARG2=val2", "alpine:latest", "env"). Return(c) c.EXPECT().Run() @@ -356,7 +356,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: &os.PathError{Op: "open", Path: envFilePath, Err: afero.ErrFileNotFound}, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, _ *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -364,7 +364,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") }, @@ -377,7 +377,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -385,7 +385,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -394,7 +394,7 @@ func TestNerdctlCommand_run(t *testing.T) { logger.EXPECT().Debugf(`Resolving special IP "host-gateway" to %q for host %q`, "192.168.5.2", "name") ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "--add-host", "name:192.168.5.2", "alpine:latest").Return(c) c.EXPECT().Run() }, @@ -407,7 +407,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -415,7 +415,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -423,7 +423,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("AWS_SESSION_TOKEN").Return("", false) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "--add-host", "name:0.0.0.0", "alpine:latest").Return(c) c.EXPECT().Run() }, @@ -436,7 +436,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: errors.New("run cmd error"), mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -444,7 +444,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -452,7 +452,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("AWS_SESSION_TOKEN").Return("", false) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "--add-host", "alpine:latest").Return(c) c.EXPECT().Run().Return(errors.New("run cmd error")) }, @@ -465,7 +465,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -473,7 +473,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -482,7 +482,7 @@ func TestNerdctlCommand_run(t *testing.T) { logger.EXPECT().Debugf(`Resolving special IP "host-gateway" to %q for host %q`, "192.168.5.2", "name") ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "--add-host=name:192.168.5.2", "alpine:latest").Return(c) c.EXPECT().Run() }, @@ -495,7 +495,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -503,7 +503,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -512,7 +512,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "--add-host=name:0.0.0.0", "alpine:latest").Return(c) c.EXPECT().Run() }, @@ -528,7 +528,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -536,7 +536,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -544,7 +544,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("AWS_SESSION_TOKEN").Return("", false) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "run", "--rm", "-v", "/tmp:/tmp1/tmp2:rro", "--volume", "/tmp:/tmp1:rprivate,rro", "-v=/tmp:/tmp1/tmp2/tmp3/tmp4:rro", "--volume=/tmp:/tmp1/tmp3/tmp4:rshared", "-v", "volume", "alpine:latest").Return(c) c.EXPECT().Run() @@ -561,7 +561,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -569,7 +569,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -577,7 +577,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("AWS_SESSION_TOKEN").Return("", false) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "-v", "/tmp:/tmp1/tmp2:rro", "--volume", "/tmp:/tmp1:rprivate,rro", "-v=/tmp:/tmp1/tmp2/tmp3/tmp4:rro", "--volume=/tmp:/tmp1/tmp3/tmp4:rshared", "-v", "volume", "alpine:latest").Return(c) c.EXPECT().Run() @@ -591,7 +591,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -599,14 +599,14 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) ncsd.EXPECT().LookupEnv("AWS_SECRET_ACCESS_KEY").Return("", false) ncsd.EXPECT().LookupEnv("AWS_SESSION_TOKEN").Return("", false) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) - lcc.EXPECT().RunWithReplacingStdout( + ncc.EXPECT().RunWithReplacingStdout( testStdoutRs, "shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "pull", "test:tag", "--help").Return(nil) }, }, @@ -618,7 +618,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: fmt.Errorf("failed to replace"), mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -626,14 +626,14 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) ncsd.EXPECT().LookupEnv("AWS_SECRET_ACCESS_KEY").Return("", false) ncsd.EXPECT().LookupEnv("AWS_SESSION_TOKEN").Return("", false) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("", false) - lcc.EXPECT().RunWithReplacingStdout( + ncc.EXPECT().RunWithReplacingStdout( testStdoutRs, "shell", limaInstanceName, "sudo", "-E", nerdctlCmdName, "pull", "test:tag", "--help"). Return(fmt.Errorf("failed to replace")) }, @@ -646,7 +646,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -654,7 +654,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -662,7 +662,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("AWS_SESSION_TOKEN").Return("", false) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("test", true) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", nerdctlCmdName, + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", nerdctlCmdName, "push", "--sign=cosign", "test:tag").Return(c) c.EXPECT().Run() }, @@ -675,7 +675,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -683,7 +683,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -691,7 +691,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("AWS_SESSION_TOKEN").Return("", false) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("test", true) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", nerdctlCmdName, + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", nerdctlCmdName, "pull", "--verify=cosign", "test:tag").Return(c) c.EXPECT().Run() }, @@ -704,7 +704,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -712,7 +712,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -720,7 +720,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().LookupEnv("AWS_SESSION_TOKEN").Return("", false) ncsd.EXPECT().LookupEnv("COSIGN_PASSWORD").Return("test", true) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", nerdctlCmdName, "pull", "test:tag").Return(c) c.EXPECT().Run() }, @@ -729,13 +729,15 @@ func TestNerdctlCommand_run(t *testing.T) { name: "with ECR credential helper and environment set", cmdName: "pull", fc: &config.Finch{ - CredsHelpers: []string{"ecr-login"}, + SharedSettings: config.SharedSettings{ + CredsHelpers: []string{"ecr-login"}, + }, }, args: []string{"test:tag"}, wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, ecc *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -743,7 +745,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("TEST_ACCESS_KEY", true) @@ -767,7 +769,7 @@ func TestNerdctlCommand_run(t *testing.T) { `), nil) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", @@ -788,13 +790,15 @@ func TestNerdctlCommand_run(t *testing.T) { name: "with ECR credential helper, no environment set", cmdName: "pull", fc: &config.Finch{ - CredsHelpers: []string{"ecr-login"}, + SharedSettings: config.SharedSettings{ + CredsHelpers: []string{"ecr-login"}, + }, }, args: []string{"test:tag"}, wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, ecc *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -802,7 +806,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("TEST_ACCESS_KEY", false) @@ -826,7 +830,7 @@ func TestNerdctlCommand_run(t *testing.T) { `), nil) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", @@ -844,13 +848,15 @@ func TestNerdctlCommand_run(t *testing.T) { name: "with ECR credential helper, aws command fails but environment is used", cmdName: "pull", fc: &config.Finch{ - CredsHelpers: []string{"ecr-login"}, + SharedSettings: config.SharedSettings{ + CredsHelpers: []string{"ecr-login"}, + }, }, args: []string{"test:tag"}, wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, ecc *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -858,7 +864,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("TEST_ACCESS_KEY", true) @@ -878,7 +884,7 @@ func TestNerdctlCommand_run(t *testing.T) { logger.EXPECT().Debugln("failed to run `aws configure` command") c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", @@ -896,13 +902,15 @@ func TestNerdctlCommand_run(t *testing.T) { name: "with ECR credential helper, aws command fails but returns unexpected response", cmdName: "pull", fc: &config.Finch{ - CredsHelpers: []string{"ecr-login"}, + SharedSettings: config.SharedSettings{ + CredsHelpers: []string{"ecr-login"}, + }, }, args: []string{"test:tag"}, wantErr: nil, mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, ecc *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -910,7 +918,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("TEST_ACCESS_KEY", true) @@ -931,7 +939,7 @@ func TestNerdctlCommand_run(t *testing.T) { "This may result in a broken ecr-credential helper experience.") c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", + ncc.EXPECT().Create("shell", limaInstanceName, "sudo", "-E", @@ -953,14 +961,14 @@ func TestNerdctlCommand_run(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) ecc := mocks.NewCommandCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) fs := afero.NewMemMapFs() - tc.mockSvc(t, lcc, ecc, ncsd, logger, ctrl, fs) + tc.mockSvc(t, ncc, ecc, ncsd, logger, ctrl, fs) - assert.Equal(t, tc.wantErr, newNerdctlCommand(lcc, ecc, ncsd, logger, fs, tc.fc).run(tc.cmdName, tc.args)) + assert.Equal(t, tc.wantErr, newNerdctlCommand(ncc, ecc, ncsd, logger, fs, tc.fc).run(tc.cmdName, tc.args)) }) } } diff --git a/cmd/finch/nerdctl_native.go b/cmd/finch/nerdctl_native.go index 770a93dec..8a432482a 100644 --- a/cmd/finch/nerdctl_native.go +++ b/cmd/finch/nerdctl_native.go @@ -20,7 +20,7 @@ func (nc *nerdctlCommand) GetCmdArgs() []string { return []string{""} } -func (nc *nerdctlCommand) assertVMIsRunning(creator command.LimaCmdCreator, logger flog.Logger) error { +func (nc *nerdctlCommand) assertVMIsRunning(creator command.NerdctlCmdCreator, logger flog.Logger) error { return nil } diff --git a/cmd/finch/nerdctl_remote.go b/cmd/finch/nerdctl_remote.go index b5282ce89..4fe82511d 100644 --- a/cmd/finch/nerdctl_remote.go +++ b/cmd/finch/nerdctl_remote.go @@ -13,7 +13,7 @@ import ( "github.com/runfinch/finch/pkg/lima" ) -func (nc *nerdctlCommand) assertVMIsRunning(creator command.LimaCmdCreator, logger flog.Logger) error { +func (nc *nerdctlCommand) assertVMIsRunning(creator command.NerdctlCmdCreator, logger flog.Logger) error { // Extra call to check VM before running nerdctl commands. These are the reasons of not doing message replacing // 1. for the non-help commands, replacing stdout may cause "stdin is not a terminal" error for the commands that need input. // E.g. finch login. diff --git a/cmd/finch/nerdctl_shared_test.go b/cmd/finch/nerdctl_shared_test.go index b12a8b6f9..5d11e8a81 100644 --- a/cmd/finch/nerdctl_shared_test.go +++ b/cmd/finch/nerdctl_shared_test.go @@ -86,11 +86,11 @@ func TestNerdctlCommand_shouldReplaceForHelp(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) ecc := mocks.NewCommandCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) - assert.True(t, newNerdctlCommand(lcc, ecc, ncsd, logger, nil, &config.Finch{}).shouldReplaceForHelp(tc.cmdName, tc.args)) + assert.True(t, newNerdctlCommand(ncc, ecc, ncsd, logger, nil, &config.Finch{}).shouldReplaceForHelp(tc.cmdName, tc.args)) }) } } @@ -116,7 +116,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { limaInstanceName, virtualMachineRootCmd), mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, _ *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -124,7 +124,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Stopped") }, @@ -139,7 +139,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { limaInstanceName, virtualMachineRootCmd), mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, _ *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -147,7 +147,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte(""), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "") }, @@ -160,7 +160,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { wantErr: errors.New("unrecognized system status"), mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, _ *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -168,7 +168,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Broken") }, @@ -181,7 +181,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { wantErr: errors.New("get status error"), mockSvc: func( _ *testing.T, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.CommandCreator, _ *mocks.NerdctlCommandSystemDeps, _ *mocks.Logger, @@ -189,7 +189,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), errors.New("get status error")) }, }, @@ -201,12 +201,12 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) fs := afero.NewMemMapFs() - tc.mockSvc(t, lcc, ecc, ncsd, logger, ctrl, fs) - assert.Equal(t, tc.wantErr, newNerdctlCommand(lcc, ecc, ncsd, logger, fs, tc.fc).run(tc.cmdName, tc.args)) + tc.mockSvc(t, ncc, ecc, ncsd, logger, ctrl, fs) + assert.Equal(t, tc.wantErr, newNerdctlCommand(ncc, ecc, ncsd, logger, fs, tc.fc).run(tc.cmdName, tc.args)) }) } } diff --git a/cmd/finch/nerdctl_windows_test.go b/cmd/finch/nerdctl_windows_test.go index 3949b02ed..39c309024 100644 --- a/cmd/finch/nerdctl_windows_test.go +++ b/cmd/finch/nerdctl_windows_test.go @@ -44,11 +44,11 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { Use: "info", }, args: []string{}, - mockSvc: func(_ *mocks.CommandCreator, lcc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -60,7 +60,7 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "info").Return(c) + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "info").Return(c) c.EXPECT().Run() }, }, @@ -73,12 +73,12 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) - tc.mockSvc(ecc, lcc, logger, ctrl, ncsd) + tc.mockSvc(ecc, ncc, logger, ctrl, ncsd) - assert.NoError(t, newNerdctlCommand(lcc, ecc, ncsd, logger, nil, &config.Finch{}).runAdapter(tc.cmd, tc.args)) + assert.NoError(t, newNerdctlCommand(ncc, ecc, ncsd, logger, nil, &config.Finch{}).runAdapter(tc.cmd, tc.args)) }) } } @@ -104,7 +104,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -112,7 +112,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -129,7 +129,7 @@ func TestNerdctlCommand_run(t *testing.T) { c := mocks.NewCommand(ctrl) // alias substitution, build => image build - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "image", "build", "-t", "demo", "/mnt/c/Users").Return(c) c.EXPECT().Run() }, @@ -143,7 +143,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -151,7 +151,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -165,7 +165,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "pull", "test:tag").Return(c) + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "pull", "test:tag").Return(c) c.EXPECT().Run() }, }, @@ -178,7 +178,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -186,7 +186,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -201,7 +201,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "-e", "ARG1=val1", "alpine:latest", "env").Return(c) c.EXPECT().Run() }, @@ -215,7 +215,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -223,7 +223,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -238,7 +238,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) // alias substitution run=>container run - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "-e", "ARG3=val3", "alpine:latest", "env").Return(c) c.EXPECT().Run() }, @@ -252,7 +252,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -260,7 +260,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().SetLevel(flog.Debug) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") @@ -276,7 +276,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) // alias substitution run=>container run - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "-e", "ARG3=val3", "alpine:latest", "env").Return(c) c.EXPECT().Run() }, @@ -290,7 +290,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( t *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -301,7 +301,7 @@ func TestNerdctlCommand_run(t *testing.T) { require.NoError(t, afero.WriteFile(fs, envFilePath, []byte(envFileStr), 0o600)) getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -315,7 +315,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathAbs("C:\\workdir").Return("C:\\workdir", nil) ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "-e", "ARG1=val1", "alpine:latest", "env").Return(c) c.EXPECT().Run() }, @@ -329,7 +329,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( t *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -340,7 +340,7 @@ func TestNerdctlCommand_run(t *testing.T) { require.NoError(t, afero.WriteFile(fs, envFilePath, []byte(envFileStr), 0o600)) getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().SetLevel(flog.Debug) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") @@ -355,7 +355,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathAbs("C:\\workdir").Return("C:\\workdir", nil) ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "-e", "ARG1=val1", "alpine:latest", "env").Return(c) c.EXPECT().Run() }, @@ -369,7 +369,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( t *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -380,7 +380,7 @@ func TestNerdctlCommand_run(t *testing.T) { require.NoError(t, afero.WriteFile(fs, envFilePath, []byte(envFileStr), 0o600)) getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -394,7 +394,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathAbs("C:\\workdir").Return("C:\\workdir", nil) ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "-e", "ARG2=val2", "alpine:latest", "env").Return(c) c.EXPECT().Run() }, @@ -408,7 +408,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, _ *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -416,7 +416,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") }, @@ -430,7 +430,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, ecc *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, cmd *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -440,7 +440,7 @@ func TestNerdctlCommand_run(t *testing.T) { getVMStatusC := mocks.NewCommand(ctrl) ecc.EXPECT().Create("cmd", "/C", "netsh", "interface", "ipv4", "show", "addresses", "vEthernet (WSL)").Return(cmd) cmd.EXPECT().Output().Return([]byte("IP Address: 192.168.5.2"), nil) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -454,7 +454,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "--add-host", "name:192.168.5.2", "alpine:latest").Return(c) c.EXPECT().Run() }, @@ -468,7 +468,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -476,7 +476,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -488,7 +488,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "--add-host", "name:0.0.0.0", "alpine:latest").Return(c) c.EXPECT().Run() }, @@ -502,7 +502,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -510,7 +510,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -522,7 +522,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "--add-host", "alpine:latest").Return(c) c.EXPECT().Run().Return(errors.New("run cmd error")) }, @@ -536,7 +536,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, ecc *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, cmd *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -546,7 +546,7 @@ func TestNerdctlCommand_run(t *testing.T) { getVMStatusC := mocks.NewCommand(ctrl) ecc.EXPECT().Create("cmd", "/C", "netsh", "interface", "ipv4", "show", "addresses", "vEthernet (WSL)").Return(cmd) cmd.EXPECT().Output().Return([]byte("IP Address: 192.168.5.2"), nil) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -559,7 +559,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "--add-host=name:192.168.5.2", "alpine:latest").Return(c) c.EXPECT().Run() }, @@ -573,7 +573,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -581,7 +581,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -593,7 +593,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "--add-host=name:0.0.0.0", "alpine:latest").Return(c) c.EXPECT().Run() }, @@ -610,7 +610,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -618,7 +618,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -630,7 +630,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath).Times(3) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath).Times(3) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--rm", "-v", "/mnt/c/workdir:/tmp1/tmp2:rro", "-v=/mnt/c/workdir:/tmp1/tmp2/tmp3/tmp4:rro", "-v", "volume", "alpine:latest").Return(c) c.EXPECT().Run() @@ -645,7 +645,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -653,7 +653,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -664,7 +664,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathAbs("C:\\workdir").Return("C:\\workdir", nil) ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) - lcc.EXPECT().RunWithReplacingStdout( + ncc.EXPECT().RunWithReplacingStdout( testStdoutRs, "shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "pull", "test:tag", "--help").Return(nil) }, @@ -678,7 +678,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -686,7 +686,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -697,7 +697,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathAbs("C:\\workdir").Return("C:\\workdir", nil) ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) - lcc.EXPECT().RunWithReplacingStdout( + ncc.EXPECT().RunWithReplacingStdout( testStdoutRs, "shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "pull", "test:tag", "--help"). Return(fmt.Errorf("failed to replace")) }, @@ -711,7 +711,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -719,7 +719,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -731,7 +731,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", nerdctlCmdName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", nerdctlCmdName, "push", "--sign=cosign", "test:tag").Return(c) c.EXPECT().Run() }, @@ -745,7 +745,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -753,7 +753,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -765,7 +765,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", nerdctlCmdName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", nerdctlCmdName, "pull", "--verify=cosign", "test:tag").Return(c) c.EXPECT().Run() }, @@ -779,7 +779,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -787,7 +787,7 @@ func TestNerdctlCommand_run(t *testing.T) { _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -799,7 +799,7 @@ func TestNerdctlCommand_run(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir").Return(augmentedPath) ncsd.EXPECT().FilePathToSlash(augmentedPath).Return(wslPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", "COSIGN_PASSWORD=test", nerdctlCmdName, "pull", "test:tag").Return(c) c.EXPECT().Run() }, @@ -813,13 +813,13 @@ func TestNerdctlCommand_run(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) cmd := mocks.NewCommand(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) fs := afero.NewMemMapFs() - tc.mockSvc(t, ecc, lcc, cmd, ncsd, logger, ctrl, fs) - assert.Equal(t, tc.wantErr, newNerdctlCommand(lcc, ecc, ncsd, logger, fs, tc.fc).run(tc.cmdName, tc.args)) + tc.mockSvc(t, ecc, ncc, cmd, ncsd, logger, ctrl, fs) + assert.Equal(t, tc.wantErr, newNerdctlCommand(ncc, ecc, ncsd, logger, fs, tc.fc).run(tc.cmdName, tc.args)) }) } } @@ -862,14 +862,14 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, ctrl *gomock.Controller, _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -883,7 +883,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { c := mocks.NewCommand(ctrl) // alias substitution, run => container run - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--mount", ContainsStr("src=/mnt/c/workdir"), "alpine:latest").Return(c) c.EXPECT().Run() @@ -897,14 +897,14 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, ctrl *gomock.Controller, _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -918,7 +918,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { c := mocks.NewCommand(ctrl) // alias substitution, run => container run - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--mount", ContainsStr("source=/mnt/c/workdir"), "alpine:latest").Return(c) c.EXPECT().Run() @@ -932,14 +932,14 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, ctrl *gomock.Controller, _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -953,7 +953,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { c := mocks.NewCommand(ctrl) // alias substitution, run => container run - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", ContainsStr("source=/mnt/c/workdir"), "alpine:latest").Return(c) c.EXPECT().Run() @@ -967,14 +967,14 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, ctrl *gomock.Controller, _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -988,7 +988,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { c := mocks.NewCommand(ctrl) // alias substitution, run => container run - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--mount", ContainsStr("source=something"), "alpine:latest").Return(c) c.EXPECT().Run() @@ -1002,14 +1002,14 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, ctrl *gomock.Controller, _ afero.Fs, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -1023,7 +1023,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { c := mocks.NewCommand(ctrl) // alias substitution, run => container run - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "run", "--mount", "type=notbind,source=C:/workdir,target=/app", "alpine:latest").Return(c) c.EXPECT().Run() @@ -1036,12 +1036,12 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) fs := afero.NewMemMapFs() - tc.mockSvc(t, ecc, lcc, ncsd, logger, ctrl, fs) - assert.Equal(t, tc.wantErr, newNerdctlCommand(lcc, ecc, ncsd, logger, fs, &config.Finch{}).run(tc.cmdName, tc.args)) + tc.mockSvc(t, ecc, ncc, ncsd, logger, ctrl, fs) + assert.Equal(t, tc.wantErr, newNerdctlCommand(ncc, ecc, ncsd, logger, fs, &config.Finch{}).run(tc.cmdName, tc.args)) }) } } @@ -1063,11 +1063,11 @@ func TestNerdctlCommand_run_CpCommand(t *testing.T) { name: "copy into container", cmdName: "cp", args: []string{"C:\\workdir\\test", "somecontainer:/tmp"}, - mockSvc: func(_ *mocks.CommandCreator, lcc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -1083,7 +1083,7 @@ func TestNerdctlCommand_run_CpCommand(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir\\test").Return(hostcopyPath) ncsd.EXPECT().FilePathToSlash(hostcopyPath).Return(wslcopyPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "cp", wslcopyPath, "somecontainer:/tmp").Return(c) c.EXPECT().Run() }, @@ -1092,11 +1092,11 @@ func TestNerdctlCommand_run_CpCommand(t *testing.T) { name: "copy out of container", cmdName: "cp", args: []string{"somecontainer:/tmp/test", "C:\\workdir\\test"}, - mockSvc: func(_ *mocks.CommandCreator, lcc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -1112,7 +1112,7 @@ func TestNerdctlCommand_run_CpCommand(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir\\test").Return(hostcopyPath) ncsd.EXPECT().FilePathToSlash(hostcopyPath).Return(wslcopyPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "cp", "somecontainer:/tmp/test", wslcopyPath).Return(c) c.EXPECT().Run() }, @@ -1121,11 +1121,11 @@ func TestNerdctlCommand_run_CpCommand(t *testing.T) { name: "copy with options", cmdName: "cp", args: []string{"-L", "somecontainer:/tmp/test", "C:\\workdir\\test"}, - mockSvc: func(_ *mocks.CommandCreator, lcc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -1141,7 +1141,7 @@ func TestNerdctlCommand_run_CpCommand(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir\\test").Return(hostcopyPath) ncsd.EXPECT().FilePathToSlash(hostcopyPath).Return(wslcopyPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "container", "cp", "-L", "somecontainer:/tmp/test", wslcopyPath).Return(c) c.EXPECT().Run() }, @@ -1155,12 +1155,12 @@ func TestNerdctlCommand_run_CpCommand(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) - tc.mockSvc(ecc, lcc, logger, ctrl, ncsd) + tc.mockSvc(ecc, ncc, logger, ctrl, ncsd) - assert.NoError(t, newNerdctlCommand(lcc, ecc, ncsd, logger, nil, &config.Finch{}).run(tc.cmdName, tc.args)) + assert.NoError(t, newNerdctlCommand(ncc, ecc, ncsd, logger, nil, &config.Finch{}).run(tc.cmdName, tc.args)) }) } } @@ -1184,11 +1184,11 @@ func TestNerdctlCommand_run_BuildCommand(t *testing.T) { name: "build without options", cmdName: "build", args: []string{"C:\\workdir\\buildcontext"}, - mockSvc: func(_ *mocks.CommandCreator, lcc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -1204,7 +1204,7 @@ func TestNerdctlCommand_run_BuildCommand(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir\\buildcontext").Return(buildContext) ncsd.EXPECT().FilePathToSlash(buildContext).Return(wslBuildContextPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "image", "build", wslBuildContextPath).Return(c) c.EXPECT().Run() }, @@ -1213,11 +1213,11 @@ func TestNerdctlCommand_run_BuildCommand(t *testing.T) { name: "build with file option", cmdName: "build", args: []string{"-f", "C:\\workdir\\buildcontext", "C:\\workdir\\buildcontext"}, - mockSvc: func(_ *mocks.CommandCreator, lcc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -1233,7 +1233,7 @@ func TestNerdctlCommand_run_BuildCommand(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir\\buildcontext").Return(buildContext).Times(2) ncsd.EXPECT().FilePathToSlash(buildContext).Return(wslBuildContextPath).Times(2) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "image", "build", "-f", wslBuildContextPath, wslBuildContextPath).Return(c) c.EXPECT().Run() }, @@ -1242,11 +1242,11 @@ func TestNerdctlCommand_run_BuildCommand(t *testing.T) { name: "build with secret option", cmdName: "build", args: []string{"--secret", "src=C:\\workdir\\secret", "C:\\workdir\\buildcontext"}, - mockSvc: func(_ *mocks.CommandCreator, lcc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") ncsd.EXPECT().LookupEnv("AWS_ACCESS_KEY_ID").Return("", false) @@ -1266,7 +1266,7 @@ func TestNerdctlCommand_run_BuildCommand(t *testing.T) { ncsd.EXPECT().FilePathJoin(string(filepath.Separator), "mnt", "c", "workdir\\secret").Return(secretPath) ncsd.EXPECT().FilePathToSlash(secretPath).Return(wslSecretPath) c := mocks.NewCommand(ctrl) - lcc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, + ncc.EXPECT().Create("shell", "--workdir", wslPath, limaInstanceName, "sudo", "-E", nerdctlCmdName, "image", "build", "--secret", fmt.Sprintf("src=%s", wslSecretPath), wslBuildContextPath).Return(c) c.EXPECT().Run() @@ -1281,12 +1281,12 @@ func TestNerdctlCommand_run_BuildCommand(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) - tc.mockSvc(ecc, lcc, logger, ctrl, ncsd) + tc.mockSvc(ecc, ncc, logger, ctrl, ncsd) - assert.NoError(t, newNerdctlCommand(lcc, ecc, ncsd, logger, nil, &config.Finch{}).run(tc.cmdName, tc.args)) + assert.NoError(t, newNerdctlCommand(ncc, ecc, ncsd, logger, nil, &config.Finch{}).run(tc.cmdName, tc.args)) }) } } diff --git a/cmd/finch/support_bundle.go b/cmd/finch/support_bundle.go index 541d59c98..9118eec74 100644 --- a/cmd/finch/support_bundle.go +++ b/cmd/finch/support_bundle.go @@ -11,24 +11,24 @@ import ( "github.com/runfinch/finch/pkg/support" ) -func newSupportBundleCommand(logger flog.Logger, builder support.BundleBuilder, lcc command.LimaCmdCreator) *cobra.Command { +func newSupportBundleCommand(logger flog.Logger, builder support.BundleBuilder, ncc command.NerdctlCmdCreator) *cobra.Command { supportBundleCommand := &cobra.Command{ Use: "support-bundle", Short: "Support bundle management", } supportBundleCommand.AddCommand( - newSupportBundleGenerateCommand(logger, builder, lcc), + newSupportBundleGenerateCommand(logger, builder, ncc), ) return supportBundleCommand } -func newSupportBundleGenerateCommand(logger flog.Logger, builder support.BundleBuilder, lcc command.LimaCmdCreator) *cobra.Command { +func newSupportBundleGenerateCommand(logger flog.Logger, builder support.BundleBuilder, ncc command.NerdctlCmdCreator) *cobra.Command { supportBundleGenerateCommand := &cobra.Command{ Use: "generate", Args: cobra.NoArgs, Short: "Generate support bundle", Long: "Generates a collection of logs and configs that can be uploaded to a Github issue to help debug issues.", - RunE: newGenerateSupportBundleAction(logger, builder, lcc).runAdapter, + RunE: newGenerateSupportBundleAction(logger, builder, ncc).runAdapter, } supportBundleGenerateCommand.Flags().StringArray("include", []string{}, @@ -43,18 +43,18 @@ func newSupportBundleGenerateCommand(logger flog.Logger, builder support.BundleB type generateSupportBundleAction struct { logger flog.Logger builder support.BundleBuilder - lcc command.LimaCmdCreator + ncc command.NerdctlCmdCreator } func newGenerateSupportBundleAction( logger flog.Logger, builder support.BundleBuilder, - lcc command.LimaCmdCreator, + ncc command.NerdctlCmdCreator, ) *generateSupportBundleAction { return &generateSupportBundleAction{ logger: logger, builder: builder, - lcc: lcc, + ncc: ncc, } } diff --git a/cmd/finch/support_bundle_remote.go b/cmd/finch/support_bundle_remote.go index 5b0bdbdda..a368d0d4f 100644 --- a/cmd/finch/support_bundle_remote.go +++ b/cmd/finch/support_bundle_remote.go @@ -12,7 +12,7 @@ import ( ) func (gsa *generateSupportBundleAction) assertVMExists() error { - status, err := lima.GetVMStatus(gsa.lcc, gsa.logger, limaInstanceName) + status, err := lima.GetVMStatus(gsa.ncc, gsa.logger, limaInstanceName) if err != nil { return err } diff --git a/cmd/finch/version.go b/cmd/finch/version.go index 3b2b140ba..75bd6562a 100644 --- a/cmd/finch/version.go +++ b/cmd/finch/version.go @@ -43,7 +43,7 @@ Server: {{- end}} {{- end}}` -func newVersionCommand(limaCmdCreator command.LimaCmdCreator, logger flog.Logger, stdOut io.Writer) *cobra.Command { +func newVersionCommand(limaCmdCreator command.NerdctlCmdCreator, logger flog.Logger, stdOut io.Writer) *cobra.Command { versionCommand := &cobra.Command{ Use: "version", Args: cobra.NoArgs, @@ -57,7 +57,7 @@ func newVersionCommand(limaCmdCreator command.LimaCmdCreator, logger flog.Logger } type versionAction struct { - creator command.LimaCmdCreator + creator command.NerdctlCmdCreator logger flog.Logger stdOut io.Writer } @@ -105,7 +105,7 @@ type NerdctlServerOutput struct { Components []NerdctlComponentsOutput `json:"Components"` } -func newVersionAction(creator command.LimaCmdCreator, logger flog.Logger, stdOut io.Writer) *versionAction { +func newVersionAction(creator command.NerdctlCmdCreator, logger flog.Logger, stdOut io.Writer) *versionAction { return &versionAction{creator: creator, logger: logger, stdOut: stdOut} } diff --git a/cmd/finch/version_test.go b/cmd/finch/version_test.go index 33a247c12..e210f0170 100644 --- a/cmd/finch/version_test.go +++ b/cmd/finch/version_test.go @@ -63,9 +63,9 @@ func TestNewVersionCommand(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) var stdOut bytes.Buffer - cmd := newVersionCommand(lcc, logger, &stdOut) + cmd := newVersionCommand(ncc, logger, &stdOut) assert.Equal(t, cmd.Name(), "version") } @@ -89,14 +89,14 @@ func TestVersionAction_runAdaptor(t *testing.T) { return c }, args: []string{}, - mockSvc: func(lcc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") command := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", + ncc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", "--format", "json").Return(command) //nolint: lll // Version output format is larger than 500 command.EXPECT().Output().Return([]byte(`{"Client":{"Version":"v1.0.0","GitCommit":"c00780a1f5b905b09812722459c54936c9e070e6","GoVersion":"go1.19.2","Os":"linux","Arch":"arm64","Components":[{"Name":"buildctl","Version":"v0.10.5","Details":{"GitCommit":"bc26045116045516ff2427201abd299043eaf8f7"}}]},"Server":{"Components":[{"Name":"containerd","Version":"v1.6.8","Details":{"GitCommit":"9cd3357b7fd7218e4aec3eae239db1f68a5a6ec6"}},{"Name":"runc","Version":"1.1.4","Details":{"GitCommit":"v1.1.4-0-g5fd4c4d1"}}]}}`), nil) @@ -113,14 +113,14 @@ func TestVersionAction_runAdaptor(t *testing.T) { return c }, args: []string{"--format", "json"}, - mockSvc: func(lcc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") command := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", + ncc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", "--format", "json").Return(command) //nolint: lll // Version output format is larger than 500 command.EXPECT().Output().Return([]byte(`{"Client":{"Version":"v1.0.0","GitCommit":"c00780a1f5b905b09812722459c54936c9e070e6","GoVersion":"go1.19.2","Os":"linux","Arch":"arm64","Components":[{"Name":"buildctl","Version":"v0.10.5","Details":{"GitCommit":"bc26045116045516ff2427201abd299043eaf8f7"}}]},"Server":{"Components":[{"Name":"containerd","Version":"v1.6.8","Details":{"GitCommit":"9cd3357b7fd7218e4aec3eae239db1f68a5a6ec6"}},{"Name":"runc","Version":"1.1.4","Details":{"GitCommit":"v1.1.4-0-g5fd4c4d1"}}]}}`), nil) @@ -135,11 +135,11 @@ func TestVersionAction_runAdaptor(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) var stdOut bytes.Buffer - tc.mockSvc(lcc, logger, ctrl) + tc.mockSvc(ncc, logger, ctrl) - assert.NoError(t, newVersionAction(lcc, logger, &stdOut).runAdapter(tc.cmd(t), tc.args)) + assert.NoError(t, newVersionAction(ncc, logger, &stdOut).runAdapter(tc.cmd(t), tc.args)) }) } } @@ -166,14 +166,14 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(lcc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") command := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", + ncc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", "--format", "json").Return(command) command.EXPECT().Output().Return([]byte(nerdctlMockVersion), nil) }, @@ -214,9 +214,9 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(lcc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Stopped") }, @@ -239,9 +239,9 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(lcc *mocks.LimaCmdCreator, _ *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.LimaCmdCreator, _ *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), errors.New("get status error")) }, postRunCheck: func(t *testing.T, stdout []byte) { @@ -260,14 +260,14 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(lcc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") command := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", + ncc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", "--format", "json").Return(command) command.EXPECT().Output().Return([]byte(nerdctlMockVersion), nil) }, @@ -288,14 +288,14 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(lcc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") command := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", + ncc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", "--format", "json").Return(command) command.EXPECT().Output().Return([]byte(nerdctlMockVersion), nil) }, @@ -316,14 +316,14 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(lcc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") command := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", + ncc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", "--format", "json").Return(command) command.EXPECT().Output().Return([]byte(nerdctlMockVersion), nil) }, @@ -344,14 +344,14 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(lcc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") command := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", + ncc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", "--format", "json").Return(command) command.EXPECT().Output().Return([]byte(nerdctlMockVersion), nil) }, @@ -371,14 +371,14 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(lcc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") command := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", + ncc.EXPECT().CreateWithoutStdio("shell", limaInstanceName, "sudo", "-E", "nerdctl", "version", "--format", "json").Return(command) command.EXPECT().Output().Return([]byte(nerdctlMockVersion), nil) }, @@ -397,12 +397,12 @@ func TestVersionAction_run(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) - tc.mockSvc(lcc, logger, ctrl) + tc.mockSvc(ncc, logger, ctrl) var stdOut bytes.Buffer - err := newVersionAction(lcc, logger, &stdOut).run(tc.format) + err := newVersionAction(ncc, logger, &stdOut).run(tc.format) assert.Equal(t, tc.wantErr, err) tc.postRunCheck(t, stdOut.Bytes()) diff --git a/cmd/finch/virtual_machine_init.go b/cmd/finch/virtual_machine_init.go index 4f21f3c35..c43514dd8 100644 --- a/cmd/finch/virtual_machine_init.go +++ b/cmd/finch/virtual_machine_init.go @@ -21,7 +21,7 @@ import ( ) func newInitVMCommand( - lcc command.LimaCmdCreator, + ncc command.NerdctlCmdCreator, logger flog.Logger, optionalDepGroups []*dependency.Group, lca config.LimaConfigApplier, @@ -34,8 +34,8 @@ func newInitVMCommand( initVMCommand := &cobra.Command{ Use: "init", Short: "Initialize the virtual machine", - RunE: newInitVMAction(lcc, logger, optionalDepGroups, lca, baseYamlFilePath, diskManager).runAdapter, - PostRunE: newPostVMStartInitAction(logger, lcc, fs, privateKeyPath, nca).runAdapter, + RunE: newInitVMAction(ncc, logger, optionalDepGroups, lca, baseYamlFilePath, diskManager).runAdapter, + PostRunE: newPostVMStartInitAction(logger, ncc, fs, privateKeyPath, nca).runAdapter, } return initVMCommand @@ -43,7 +43,7 @@ func newInitVMCommand( type initVMAction struct { baseYamlFilePath string - creator command.LimaCmdCreator + creator command.NerdctlCmdCreator logger flog.Logger optionalDepGroups []*dependency.Group limaConfigApplier config.LimaConfigApplier @@ -51,7 +51,7 @@ type initVMAction struct { } func newInitVMAction( - creator command.LimaCmdCreator, + creator command.NerdctlCmdCreator, logger flog.Logger, optionalDepGroups []*dependency.Group, lca config.LimaConfigApplier, diff --git a/cmd/finch/virtual_machine_init_test.go b/cmd/finch/virtual_machine_init_test.go index 87ce5ad10..eb3331fb4 100644 --- a/cmd/finch/virtual_machine_init_test.go +++ b/cmd/finch/virtual_machine_init_test.go @@ -62,14 +62,14 @@ func TestInitVMAction_runAdapter(t *testing.T) { return groups }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte(""), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "") @@ -78,7 +78,7 @@ func TestInitVMAction_runAdapter(t *testing.T) { lca.EXPECT().ConfigureOverrideLimaYaml().Return(nil) dm.EXPECT().DetachUserDataDisk().Return(nil) dm.EXPECT().EnsureUserDataDisk().Return(nil) - lcc.EXPECT().CreateWithoutStdio("start", fmt.Sprintf("--name=%s", limaInstanceName), + ncc.EXPECT().CreateWithoutStdio("start", fmt.Sprintf("--name=%s", limaInstanceName), mockBaseYamlFilePath, "--tty=false").Return(command) command.EXPECT().CombinedOutput() @@ -95,14 +95,14 @@ func TestInitVMAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) dm := mocks.NewUserDataDiskManager(ctrl) groups := tc.groups(ctrl) - tc.mockSvc(lcc, logger, lca, dm, ctrl) + tc.mockSvc(ncc, logger, lca, dm, ctrl) - assert.NoError(t, newInitVMAction(lcc, logger, groups, lca, mockBaseYamlFilePath, dm).runAdapter(tc.command, tc.args)) + assert.NoError(t, newInitVMAction(ncc, logger, groups, lca, mockBaseYamlFilePath, dm).runAdapter(tc.command, tc.args)) }) } } @@ -129,14 +129,14 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte(""), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "") @@ -146,7 +146,7 @@ func TestInitVMAction_run(t *testing.T) { dm.EXPECT().EnsureUserDataDisk().Return(nil) command := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("start", fmt.Sprintf("--name=%s", limaInstanceName), + ncc.EXPECT().CreateWithoutStdio("start", fmt.Sprintf("--name=%s", limaInstanceName), mockBaseYamlFilePath, "--tty=false").Return(command) command.EXPECT().CombinedOutput() @@ -161,14 +161,14 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") }, @@ -182,14 +182,14 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Stopped") }, @@ -201,14 +201,14 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Broken") }, @@ -220,14 +220,14 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), errors.New("get status error")) }, }, @@ -248,14 +248,14 @@ func TestInitVMAction_run(t *testing.T) { return groups }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte(""), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "") @@ -271,7 +271,7 @@ func TestInitVMAction_run(t *testing.T) { dm.EXPECT().EnsureUserDataDisk().Return(nil) command := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("start", fmt.Sprintf("--name=%s", limaInstanceName), + ncc.EXPECT().CreateWithoutStdio("start", fmt.Sprintf("--name=%s", limaInstanceName), mockBaseYamlFilePath, "--tty=false").Return(command) command.EXPECT().CombinedOutput() @@ -288,14 +288,14 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte(""), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "") @@ -310,14 +310,14 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte(""), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "") @@ -329,7 +329,7 @@ func TestInitVMAction_run(t *testing.T) { logs := []byte("stdout + stderr") command := mocks.NewCommand(ctrl) command.EXPECT().CombinedOutput().Return(logs, errors.New("failed to init instance")) - lcc.EXPECT().CreateWithoutStdio("start", fmt.Sprintf("--name=%s", limaInstanceName), + ncc.EXPECT().CreateWithoutStdio("start", fmt.Sprintf("--name=%s", limaInstanceName), mockBaseYamlFilePath, "--tty=false").Return(command) logger.EXPECT().Info("Initializing and starting Finch virtual machine...") @@ -348,14 +348,14 @@ func TestInitVMAction_run(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) dm := mocks.NewUserDataDiskManager(ctrl) groups := tc.groups(ctrl) - tc.mockSvc(lcc, logger, lca, dm, ctrl) + tc.mockSvc(ncc, logger, lca, dm, ctrl) - err := newInitVMAction(lcc, logger, groups, lca, mockBaseYamlFilePath, dm).run() + err := newInitVMAction(ncc, logger, groups, lca, mockBaseYamlFilePath, dm).run() assert.Equal(t, err, tc.wantErr) }) } diff --git a/cmd/finch/virtual_machine_local.go b/cmd/finch/virtual_machine_local.go index e6fb7e63b..af4a92002 100644 --- a/cmd/finch/virtual_machine_local.go +++ b/cmd/finch/virtual_machine_local.go @@ -18,7 +18,7 @@ import ( func virtualMachineCommands( logger flog.Logger, fp path.Finch, - lcc command.LimaCmdCreator, + ncc command.NerdctlCmdCreator, ecc command.Creator, fs afero.Fs, fc *config.Finch, diff --git a/cmd/finch/virtual_machine_remote.go b/cmd/finch/virtual_machine_remote.go index 9ff34e99a..bcc810fb2 100644 --- a/cmd/finch/virtual_machine_remote.go +++ b/cmd/finch/virtual_machine_remote.go @@ -30,7 +30,7 @@ const ( ) func newVirtualMachineCommand( - limaCmdCreator command.LimaCmdCreator, + limaCmdCreator command.NerdctlCmdCreator, logger flog.Logger, optionalDepGroups []*dependency.Group, lca config.LimaConfigApplier, @@ -59,7 +59,7 @@ func newVirtualMachineCommand( // Used by the actions that call VM start to ensure that the in-VM config file options are applied after boot. type postVMStartInitAction struct { - creator command.LimaCmdCreator + creator command.NerdctlCmdCreator logger flog.Logger fs afero.Fs privateKeyPath string @@ -68,7 +68,7 @@ type postVMStartInitAction struct { func newPostVMStartInitAction( logger flog.Logger, - creator command.LimaCmdCreator, + creator command.NerdctlCmdCreator, fs afero.Fs, privateKeyPath string, nca config.NerdctlConfigApplier, @@ -101,7 +101,7 @@ func (p *postVMStartInitAction) run() error { func virtualMachineCommands( logger flog.Logger, fp path.Finch, - lcc command.LimaCmdCreator, + ncc command.NerdctlCmdCreator, ecc command.Creator, fs afero.Fs, fc *config.Finch, @@ -109,9 +109,9 @@ func virtualMachineCommands( finchRootPath string, ) *cobra.Command { return newVirtualMachineCommand( - lcc, + ncc, logger, - dependencies(ecc, fc, fp, fs, lcc, logger, fp.FinchDir(finchRootPath)), + dependencies(ecc, fc, fp, fs, ncc, logger, fp.FinchDir(finchRootPath)), config.NewLimaApplier( fc, ecc, @@ -132,6 +132,6 @@ func virtualMachineCommands( ), fp, fs, - disk.NewUserDataDiskManager(lcc, ecc, &afero.OsFs{}, fp, finchRootPath, fc, logger), + disk.NewUserDataDiskManager(ncc, ecc, &afero.OsFs{}, fp, finchRootPath, fc, logger), ) } diff --git a/cmd/finch/virtual_machine_remove.go b/cmd/finch/virtual_machine_remove.go index 0b766c7ad..ac1632afe 100644 --- a/cmd/finch/virtual_machine_remove.go +++ b/cmd/finch/virtual_machine_remove.go @@ -17,7 +17,7 @@ import ( "github.com/runfinch/finch/pkg/flog" ) -func newRemoveVMCommand(limaCmdCreator command.LimaCmdCreator, diskManager disk.UserDataDiskManager, logger flog.Logger) *cobra.Command { +func newRemoveVMCommand(limaCmdCreator command.NerdctlCmdCreator, diskManager disk.UserDataDiskManager, logger flog.Logger) *cobra.Command { removeVMCommand := &cobra.Command{ Use: "remove", Short: "Remove the virtual machine instance", @@ -30,12 +30,12 @@ func newRemoveVMCommand(limaCmdCreator command.LimaCmdCreator, diskManager disk. } type removeVMAction struct { - creator command.LimaCmdCreator + creator command.NerdctlCmdCreator logger flog.Logger diskManager disk.UserDataDiskManager } -func newRemoveVMAction(creator command.LimaCmdCreator, diskManager disk.UserDataDiskManager, logger flog.Logger) *removeVMAction { +func newRemoveVMAction(creator command.NerdctlCmdCreator, diskManager disk.UserDataDiskManager, logger flog.Logger) *removeVMAction { return &removeVMAction{creator: creator, logger: logger, diskManager: diskManager} } @@ -60,7 +60,7 @@ func (rva *removeVMAction) run(force bool) error { return rva.removeVM(false) } -func (rva *removeVMAction) assertVMIsStopped(creator command.LimaCmdCreator, logger flog.Logger) error { +func (rva *removeVMAction) assertVMIsStopped(creator command.NerdctlCmdCreator, logger flog.Logger) error { status, err := lima.GetVMStatus(creator, logger, limaInstanceName) if err != nil { return err diff --git a/cmd/finch/virtual_machine_remove_test.go b/cmd/finch/virtual_machine_remove_test.go index 24d065f05..a1d8138e5 100644 --- a/cmd/finch/virtual_machine_remove_test.go +++ b/cmd/finch/virtual_machine_remove_test.go @@ -69,10 +69,10 @@ func TestRemoveVMAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) dm := mocks.NewUserDataDiskManager(ctrl) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) - tc.mockSvc(logger, lcc, dm, ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) + tc.mockSvc(logger, ncc, dm, ctrl) - cmd := newRemoveVMCommand(lcc, dm, logger) + cmd := newRemoveVMCommand(ncc, dm, logger) cmd.SetArgs(tc.args) assert.NoError(t, cmd.Execute()) }) @@ -192,10 +192,10 @@ func TestRemoveVMAction_run(t *testing.T) { ctrl := gomock.NewController(t) dm := mocks.NewUserDataDiskManager(ctrl) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) - tc.mockSvc(logger, lcc, dm, ctrl) - err := newRemoveVMAction(lcc, dm, logger).run(tc.force) + tc.mockSvc(logger, ncc, dm, ctrl) + err := newRemoveVMAction(ncc, dm, logger).run(tc.force) assert.Equal(t, tc.wantErr, err) }) } diff --git a/cmd/finch/virtual_machine_start.go b/cmd/finch/virtual_machine_start.go index 7d236533f..9af2e3501 100644 --- a/cmd/finch/virtual_machine_start.go +++ b/cmd/finch/virtual_machine_start.go @@ -21,7 +21,7 @@ import ( ) func newStartVMCommand( - lcc command.LimaCmdCreator, + ncc command.NerdctlCmdCreator, logger flog.Logger, optionalDepGroups []*dependency.Group, lca config.LimaConfigApplier, @@ -33,13 +33,13 @@ func newStartVMCommand( return &cobra.Command{ Use: "start", Short: "Start the virtual machine", - RunE: newStartVMAction(lcc, logger, optionalDepGroups, lca, dm).runAdapter, - PostRunE: newPostVMStartInitAction(logger, lcc, fs, privateKeyPath, nca).runAdapter, + RunE: newStartVMAction(ncc, logger, optionalDepGroups, lca, dm).runAdapter, + PostRunE: newPostVMStartInitAction(logger, ncc, fs, privateKeyPath, nca).runAdapter, } } type startVMAction struct { - creator command.LimaCmdCreator + creator command.NerdctlCmdCreator logger flog.Logger optionalDepGroups []*dependency.Group limaConfigApplier config.LimaConfigApplier @@ -47,7 +47,7 @@ type startVMAction struct { } func newStartVMAction( - creator command.LimaCmdCreator, + creator command.NerdctlCmdCreator, logger flog.Logger, optionalDepGroups []*dependency.Group, lca config.LimaConfigApplier, @@ -100,7 +100,7 @@ func (sva *startVMAction) run() error { return nil } -func (sva *startVMAction) assertVMIsStopped(creator command.LimaCmdCreator, logger flog.Logger) error { +func (sva *startVMAction) assertVMIsStopped(creator command.NerdctlCmdCreator, logger flog.Logger) error { status, err := lima.GetVMStatus(creator, logger, limaInstanceName) if err != nil { return err diff --git a/cmd/finch/virtual_machine_start_test.go b/cmd/finch/virtual_machine_start_test.go index 5a0d78370..7d8ff72f8 100644 --- a/cmd/finch/virtual_machine_start_test.go +++ b/cmd/finch/virtual_machine_start_test.go @@ -62,14 +62,14 @@ func TestStartVMAction_runAdapter(t *testing.T) { }, args: []string{}, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Stopped") @@ -79,7 +79,7 @@ func TestStartVMAction_runAdapter(t *testing.T) { command := mocks.NewCommand(ctrl) command.EXPECT().CombinedOutput() - lcc.EXPECT().CreateWithoutStdio("start", limaInstanceName).Return(command) + ncc.EXPECT().CreateWithoutStdio("start", limaInstanceName).Return(command) logger.EXPECT().Info("Starting existing Finch virtual machine...") logger.EXPECT().Info("Finch virtual machine started successfully") @@ -94,14 +94,14 @@ func TestStartVMAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) dm := mocks.NewUserDataDiskManager(ctrl) groups := tc.groups(ctrl) - tc.mockSvc(lcc, logger, lca, dm, ctrl) + tc.mockSvc(ncc, logger, lca, dm, ctrl) - err := newStartVMAction(lcc, logger, groups, lca, dm).runAdapter(tc.command, tc.args) + err := newStartVMAction(ncc, logger, groups, lca, dm).runAdapter(tc.command, tc.args) assert.Equal(t, tc.wantErr, err) }) } @@ -137,14 +137,14 @@ func TestStartVMAction_run(t *testing.T) { return groups }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Stopped") @@ -154,7 +154,7 @@ func TestStartVMAction_run(t *testing.T) { command := mocks.NewCommand(ctrl) command.EXPECT().CombinedOutput() - lcc.EXPECT().CreateWithoutStdio("start", limaInstanceName).Return(command) + ncc.EXPECT().CreateWithoutStdio("start", limaInstanceName).Return(command) logger.EXPECT().Info("Starting existing Finch virtual machine...") logger.EXPECT().Info("Finch virtual machine started successfully") @@ -167,14 +167,14 @@ func TestStartVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") }, @@ -187,14 +187,14 @@ func TestStartVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte(""), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "") }, @@ -206,14 +206,14 @@ func TestStartVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Broken") }, @@ -225,14 +225,14 @@ func TestStartVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), errors.New("get status error")) }, }, @@ -246,14 +246,14 @@ func TestStartVMAction_run(t *testing.T) { return nil }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Stopped") @@ -277,14 +277,14 @@ func TestStartVMAction_run(t *testing.T) { return groups }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Stopped") @@ -294,7 +294,7 @@ func TestStartVMAction_run(t *testing.T) { command := mocks.NewCommand(ctrl) command.EXPECT().CombinedOutput() - lcc.EXPECT().CreateWithoutStdio("start", limaInstanceName).Return(command) + ncc.EXPECT().CreateWithoutStdio("start", limaInstanceName).Return(command) logger.EXPECT().Info("Starting existing Finch virtual machine...") logger.EXPECT().Info("Finch virtual machine started successfully") @@ -319,14 +319,14 @@ func TestStartVMAction_run(t *testing.T) { return groups }, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Stopped") @@ -337,7 +337,7 @@ func TestStartVMAction_run(t *testing.T) { logs := []byte("stdout + stderr") command := mocks.NewCommand(ctrl) command.EXPECT().CombinedOutput().Return(logs, errors.New("start command error")) - lcc.EXPECT().CreateWithoutStdio("start", limaInstanceName).Return(command) + ncc.EXPECT().CreateWithoutStdio("start", limaInstanceName).Return(command) logger.EXPECT().Info("Starting existing Finch virtual machine...") logger.EXPECT().SetFormatter(flog.TextWithoutTruncation) @@ -354,14 +354,14 @@ func TestStartVMAction_run(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) dm := mocks.NewUserDataDiskManager(ctrl) groups := tc.groups(ctrl) - tc.mockSvc(lcc, logger, lca, dm, ctrl) + tc.mockSvc(ncc, logger, lca, dm, ctrl) - err := newStartVMAction(lcc, logger, groups, lca, dm).run() + err := newStartVMAction(ncc, logger, groups, lca, dm).run() assert.Equal(t, err, tc.wantErr) }) } diff --git a/cmd/finch/virtual_machine_status.go b/cmd/finch/virtual_machine_status.go index 60b7b369a..1bde4a518 100644 --- a/cmd/finch/virtual_machine_status.go +++ b/cmd/finch/virtual_machine_status.go @@ -16,7 +16,7 @@ import ( "github.com/spf13/cobra" ) -func newStatusVMCommand(limaCmdCreator command.LimaCmdCreator, logger flog.Logger, stdout io.Writer) *cobra.Command { +func newStatusVMCommand(limaCmdCreator command.NerdctlCmdCreator, logger flog.Logger, stdout io.Writer) *cobra.Command { statusVMCommand := &cobra.Command{ Use: "status", Short: "Status of the virtual machine", @@ -27,12 +27,12 @@ func newStatusVMCommand(limaCmdCreator command.LimaCmdCreator, logger flog.Logge } type statusVMAction struct { - creator command.LimaCmdCreator + creator command.NerdctlCmdCreator logger flog.Logger stdout io.Writer } -func newStatusVMAction(creator command.LimaCmdCreator, logger flog.Logger, stdout io.Writer) *statusVMAction { +func newStatusVMAction(creator command.NerdctlCmdCreator, logger flog.Logger, stdout io.Writer) *statusVMAction { return &statusVMAction{creator: creator, logger: logger, stdout: stdout} } diff --git a/cmd/finch/virtual_machine_status_test.go b/cmd/finch/virtual_machine_status_test.go index 811e61851..46f9c1f31 100644 --- a/cmd/finch/virtual_machine_status_test.go +++ b/cmd/finch/virtual_machine_status_test.go @@ -45,13 +45,13 @@ func TestStatusVMAction_runAdapter(t *testing.T) { }, args: []string{}, mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte(""), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "") }, @@ -66,12 +66,12 @@ func TestStatusVMAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) stdout := bytes.Buffer{} - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) - tc.mockSvc(lcc, logger, lca, ctrl) + tc.mockSvc(ncc, logger, lca, ctrl) - assert.NoError(t, newStatusVMAction(lcc, logger, &stdout).runAdapter(tc.command, tc.args)) + assert.NoError(t, newStatusVMAction(ncc, logger, &stdout).runAdapter(tc.command, tc.args)) }) } } @@ -95,13 +95,13 @@ func TestStatusVMAction_run(t *testing.T) { wantErr: nil, wantStatusOutput: "Running\n", mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") }, @@ -111,13 +111,13 @@ func TestStatusVMAction_run(t *testing.T) { wantErr: nil, wantStatusOutput: "Stopped\n", mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Stopped") }, @@ -127,13 +127,13 @@ func TestStatusVMAction_run(t *testing.T) { wantErr: nil, wantStatusOutput: "Nonexistent\n", mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte(""), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "") }, @@ -143,13 +143,13 @@ func TestStatusVMAction_run(t *testing.T) { wantErr: errors.New("unrecognized system status"), wantStatusOutput: "", mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Broken") }, @@ -159,13 +159,13 @@ func TestStatusVMAction_run(t *testing.T) { wantErr: errors.New("get status error"), wantStatusOutput: "", mockSvc: func( - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, _ *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, ) { getVMStatusC := mocks.NewCommand(ctrl) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), errors.New("get status error")) }, }, @@ -179,12 +179,12 @@ func TestStatusVMAction_run(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) stdout := bytes.Buffer{} - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) - tc.mockSvc(lcc, logger, lca, ctrl) + tc.mockSvc(ncc, logger, lca, ctrl) - err := newStatusVMAction(lcc, logger, &stdout).run() + err := newStatusVMAction(ncc, logger, &stdout).run() assert.Equal(t, err, tc.wantErr) assert.Equal(t, tc.wantStatusOutput, stdout.String()) }) diff --git a/cmd/finch/virtual_machine_stop.go b/cmd/finch/virtual_machine_stop.go index 972f31571..c3966e124 100644 --- a/cmd/finch/virtual_machine_stop.go +++ b/cmd/finch/virtual_machine_stop.go @@ -16,7 +16,7 @@ import ( "github.com/spf13/cobra" ) -func newStopVMCommand(limaCmdCreator command.LimaCmdCreator, diskManager disk.UserDataDiskManager, logger flog.Logger) *cobra.Command { +func newStopVMCommand(limaCmdCreator command.NerdctlCmdCreator, diskManager disk.UserDataDiskManager, logger flog.Logger) *cobra.Command { stopVMCommand := &cobra.Command{ Use: "stop", Short: "Stop the virtual machine", @@ -29,12 +29,12 @@ func newStopVMCommand(limaCmdCreator command.LimaCmdCreator, diskManager disk.Us } type stopVMAction struct { - creator command.LimaCmdCreator + creator command.NerdctlCmdCreator diskManager disk.UserDataDiskManager logger flog.Logger } -func newStopVMAction(creator command.LimaCmdCreator, diskManager disk.UserDataDiskManager, logger flog.Logger) *stopVMAction { +func newStopVMAction(creator command.NerdctlCmdCreator, diskManager disk.UserDataDiskManager, logger flog.Logger) *stopVMAction { return &stopVMAction{creator: creator, diskManager: diskManager, logger: logger} } @@ -59,7 +59,7 @@ func (sva *stopVMAction) run(force bool) error { return sva.stopVM(false) } -func (sva *stopVMAction) assertVMIsRunning(creator command.LimaCmdCreator, logger flog.Logger) error { +func (sva *stopVMAction) assertVMIsRunning(creator command.NerdctlCmdCreator, logger flog.Logger) error { status, err := lima.GetVMStatus(creator, logger, limaInstanceName) if err != nil { return err diff --git a/cmd/finch/virtual_machine_stop_test.go b/cmd/finch/virtual_machine_stop_test.go index a1164d15a..62671ce08 100644 --- a/cmd/finch/virtual_machine_stop_test.go +++ b/cmd/finch/virtual_machine_stop_test.go @@ -74,10 +74,10 @@ func TestStopVMAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) dm := mocks.NewUserDataDiskManager(ctrl) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) - tc.mockSvc(logger, lcc, ctrl, dm) + ncc := mocks.NewLimaCmdCreator(ctrl) + tc.mockSvc(logger, ncc, ctrl, dm) - cmd := newStopVMCommand(lcc, dm, logger) + cmd := newStopVMCommand(ncc, dm, logger) cmd.SetArgs(tc.args) err := cmd.Execute() assert.Equal(t, tc.wantErr, err) @@ -197,10 +197,10 @@ func TestStopVMAction_run(t *testing.T) { ctrl := gomock.NewController(t) dm := mocks.NewUserDataDiskManager(ctrl) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) - tc.mockSvc(logger, lcc, ctrl, dm) - err := newStopVMAction(lcc, dm, logger).run(tc.force) + tc.mockSvc(logger, ncc, ctrl, dm) + err := newStopVMAction(ncc, dm, logger).run(tc.force) assert.Equal(t, tc.wantErr, err) }) } diff --git a/cmd/finch/virtual_machine_test.go b/cmd/finch/virtual_machine_test.go index 7b9cdb0f6..58c00e5bb 100644 --- a/cmd/finch/virtual_machine_test.go +++ b/cmd/finch/virtual_machine_test.go @@ -38,10 +38,10 @@ func TestPostVMStartInitAction_runAdapter(t *testing.T) { }{ { name: "config files are applied after boot", - mockSvc: func(logger *mocks.Logger, lcc *mocks.LimaCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { + mockSvc: func(logger *mocks.Logger, ncc *mocks.LimaCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { logger.EXPECT().Debugln("Applying guest configuration options") command.EXPECT().Output().Return([]byte("80"), nil) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) nca.EXPECT().Apply("127.0.0.1:80").Return(nil) }, cmd: &cobra.Command{ @@ -59,12 +59,12 @@ func TestPostVMStartInitAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) command := mocks.NewCommand(ctrl) nca := mocks.NewNerdctlConfigApplier(ctrl) - tc.mockSvc(logger, lcc, command, nca) + tc.mockSvc(logger, ncc, command, nca) - err := newPostVMStartInitAction(logger, lcc, nil, "", nca).runAdapter(tc.cmd, tc.args) + err := newPostVMStartInitAction(logger, ncc, nil, "", nca).runAdapter(tc.cmd, tc.args) assert.Equal(t, err, tc.wantErr) }) } @@ -80,39 +80,39 @@ func TestPostVMStartInitAction_run(t *testing.T) { }{ { name: "config files are applied after boot", - mockSvc: func(logger *mocks.Logger, lcc *mocks.LimaCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { + mockSvc: func(logger *mocks.Logger, ncc *mocks.LimaCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { logger.EXPECT().Debugln("Applying guest configuration options") command.EXPECT().Output().Return([]byte("80"), nil) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) nca.EXPECT().Apply("127.0.0.1:80").Return(nil) }, wantErr: nil, }, { name: "should return an error if sshPortCmd has an error output", - mockSvc: func(logger *mocks.Logger, lcc *mocks.LimaCmdCreator, command *mocks.Command, _ *mocks.NerdctlConfigApplier) { + mockSvc: func(logger *mocks.Logger, ncc *mocks.LimaCmdCreator, command *mocks.Command, _ *mocks.NerdctlConfigApplier) { logger.EXPECT().Debugln("Applying guest configuration options") command.EXPECT().Output().Return(nil, errors.New("ssh port error")) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) }, wantErr: errors.New("ssh port error"), }, { name: "should print info and return without error if port is 0", - mockSvc: func(logger *mocks.Logger, lcc *mocks.LimaCmdCreator, command *mocks.Command, _ *mocks.NerdctlConfigApplier) { + mockSvc: func(logger *mocks.Logger, ncc *mocks.LimaCmdCreator, command *mocks.Command, _ *mocks.NerdctlConfigApplier) { logger.EXPECT().Debugln("Applying guest configuration options") command.EXPECT().Output().Return([]byte("0"), nil) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) logger.EXPECT().Warnln("SSH port = 0, is the instance running? Not able to apply VM configuration options") }, wantErr: nil, }, { name: "should return error if applyNerdctlConfig has an error", - mockSvc: func(logger *mocks.Logger, lcc *mocks.LimaCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { + mockSvc: func(logger *mocks.Logger, ncc *mocks.LimaCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { logger.EXPECT().Debugln("Applying guest configuration options") command.EXPECT().Output().Return([]byte("80"), nil) - lcc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) + ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) nca.EXPECT().Apply("127.0.0.1:80").Return(errors.New("applyNerdctlConfig has an error")) }, wantErr: errors.New("applyNerdctlConfig has an error"), @@ -126,12 +126,12 @@ func TestPostVMStartInitAction_run(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) command := mocks.NewCommand(ctrl) nca := mocks.NewNerdctlConfigApplier(ctrl) - tc.mockSvc(logger, lcc, command, nca) + tc.mockSvc(logger, ncc, command, nca) - err := newPostVMStartInitAction(logger, lcc, nil, "", nca).run() + err := newPostVMStartInitAction(logger, ncc, nil, "", nca).run() assert.Equal(t, err, tc.wantErr) }) } diff --git a/pkg/command/nerdctl.go b/pkg/command/nerdctl.go index f07414aa0..3e43da3e7 100644 --- a/pkg/command/nerdctl.go +++ b/pkg/command/nerdctl.go @@ -14,16 +14,10 @@ import ( "github.com/runfinch/finch/pkg/system" ) -const ( - envKeyLimaHome = "LIMA_HOME" - envKeyUnixPath = "PATH" - envKeyWinPath = "Path" -) - -// LimaCmdCreator creates a limactl command. +// NerdctlCmdCreator creates a limactl command. // -//go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/command_lima_cmd_creator.go -package=mocks -mock_names LimaCmdCreator=LimaCmdCreator . LimaCmdCreator -type LimaCmdCreator interface { +//go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/command_nerdctl_cmd_creator.go -package=mocks -mock_names NerdctlCmdCreator=NerdctlCmdCreator . NerdctlCmdCreator +type NerdctlCmdCreator interface { // Create creates a new Lima command and connects the stdio of it to the stdio of the current process. Create(args ...string) Command // CreateWithoutStdio creates a new Lima command without connecting the stdio of it to the stdio of the current process. @@ -47,21 +41,21 @@ type Replacement struct { Source, Target string } -type limaCmdCreator struct { +type nerdctlCmdCreator struct { cmdCreator Creator logger flog.Logger - systemDeps LimaCmdCreatorSystemDeps + systemDeps NerdctlCmdCreatorSystemDeps limaHomePath string limactlPath string binPath string } -var _ LimaCmdCreator = (*limaCmdCreator)(nil) +var _ NerdctlCmdCreator = (*nerdctlCmdCreator)(nil) -// LimaCmdCreatorSystemDeps contains the system dependencies for NewLimaCmdCreator. +// NerdctlCmdCreatorSystemDeps contains the system dependencies for NewLimaCmdCreator. // -//go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/lima_cmd_creator_system_deps.go -package=mocks -mock_names LimaCmdCreatorSystemDeps=LimaCmdCreatorSystemDeps . LimaCmdCreatorSystemDeps -type LimaCmdCreatorSystemDeps interface { +//go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/nerdctl_cmd_creator_system_deps.go -package=mocks -mock_names NerdctlCmdCreatorSystemDeps=NerdctlCmdCreatorSystemDeps . NerdctlCmdCreatorSystemDeps +type NerdctlCmdCreatorSystemDeps interface { system.EnvironGetter system.StdinGetter system.StdoutGetter @@ -69,14 +63,14 @@ type LimaCmdCreatorSystemDeps interface { system.EnvGetter } -// NewLimaCmdCreator returns a LimaCmdCreator that creates limactl commands based on the provided lima-related paths. -func NewLimaCmdCreator( +// NewNerdctlCmdCreator returns a LimaCmdCreator that creates limactl commands based on the provided lima-related paths. +func NewNerdctlCmdCreator( cmdCreator Creator, logger flog.Logger, limaHomePath, limactlPath string, binPath string, - systemDeps LimaCmdCreatorSystemDeps, -) LimaCmdCreator { - return &limaCmdCreator{ + systemDeps NerdctlCmdCreatorSystemDeps, +) NerdctlCmdCreator { + return &nerdctlCmdCreator{ cmdCreator: cmdCreator, logger: logger, limaHomePath: limaHomePath, @@ -86,19 +80,19 @@ func NewLimaCmdCreator( } } -func (lcc *limaCmdCreator) Create(args ...string) Command { - return lcc.create(lcc.systemDeps.Stdin(), lcc.systemDeps.Stdout(), lcc.systemDeps.Stderr(), args...) +func (ncc *nerdctlCmdCreator) Create(args ...string) Command { + return ncc.create(ncc.systemDeps.Stdin(), ncc.systemDeps.Stdout(), ncc.systemDeps.Stderr(), args...) } -func (lcc *limaCmdCreator) CreateWithoutStdio(args ...string) Command { - return lcc.create(nil, nil, nil, args...) +func (ncc *nerdctlCmdCreator) CreateWithoutStdio(args ...string) Command { + return ncc.create(nil, nil, nil, args...) } -func (lcc *limaCmdCreator) RunWithReplacingStdout(rs []Replacement, args ...string) error { +func (ncc *nerdctlCmdCreator) RunWithReplacingStdout(rs []Replacement, args ...string) error { var buf bytes.Buffer - err := lcc.create(lcc.systemDeps.Stdin(), + err := ncc.create(ncc.systemDeps.Stdin(), &buf, - lcc.systemDeps.Stderr(), + ncc.systemDeps.Stderr(), args...).Run() if err != nil { // Note that at this point, buf may contain something that should be replaced and then written to stdout, @@ -107,14 +101,14 @@ func (lcc *limaCmdCreator) RunWithReplacingStdout(rs []Replacement, args ...stri // - The control flow is simpler. return err } - _, err = lcc.systemDeps.Stdout().Write(lcc.replaceBytes(buf.Bytes(), rs)) + _, err = ncc.systemDeps.Stdout().Write(ncc.replaceBytes(buf.Bytes(), rs)) if err != nil { return err } return nil } -func (lcc *limaCmdCreator) replaceBytes(s []byte, rs []Replacement) []byte { +func (ncc *nerdctlCmdCreator) replaceBytes(s []byte, rs []Replacement) []byte { for _, r := range rs { s = bytes.ReplaceAll(s, []byte(r.Source), []byte(r.Target)) } diff --git a/pkg/command/nerdctl_native.go b/pkg/command/nerdctl_native.go index 07fe94d33..bdde82d8c 100644 --- a/pkg/command/nerdctl_native.go +++ b/pkg/command/nerdctl_native.go @@ -6,34 +6,13 @@ package command import ( - "fmt" "io" - "runtime" ) -func (lcc *limaCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, args ...string) Command { - lcc.logger.Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", args, envKeyLimaHome, lcc.limaHomePath) - cmd := lcc.cmdCreator.Create("nerdctl", args...) - limaHomeEnv := fmt.Sprintf("%s=%s", envKeyLimaHome, lcc.limaHomePath) - var pathEnv string - var envKeyPath string - var path string - if runtime.GOOS == "windows" { - envKeyPath = envKeyWinPath - path = lcc.systemDeps.Env(envKeyPath) - path = fmt.Sprintf(`%s\;%s`, lcc.binPath, path) - pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) - } else { - envKeyPath = envKeyUnixPath - path = lcc.systemDeps.Env(envKeyPath) - path = fmt.Sprintf("%s:%s", lcc.binPath, path) - pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) - } +func (ncc *nerdctlCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, args ...string) Command { + ncc.logger.Debugf("Creating nerdctl command: ARGUMENTS: %v", args) + cmd := ncc.cmdCreator.Create("nerdctl", args...) - newPathEnv := replaceOrAppend(lcc.systemDeps.Environ(), envKeyLimaHome, limaHomeEnv) - newPathEnv = replaceOrAppend(newPathEnv, envKeyPath, pathEnv) - - cmd.SetEnv(newPathEnv) cmd.SetStdin(stdin) cmd.SetStdout(stdout) cmd.SetStderr(stderr) diff --git a/pkg/command/nerdctl_remote.go b/pkg/command/nerdctl_remote.go index c2fdce6c8..bd61dcb80 100644 --- a/pkg/command/nerdctl_remote.go +++ b/pkg/command/nerdctl_remote.go @@ -11,26 +11,32 @@ import ( "runtime" ) -func (lcc *limaCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, args ...string) Command { - lcc.logger.Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", args, envKeyLimaHome, lcc.limaHomePath) - cmd := lcc.cmdCreator.Create(lcc.limactlPath, args...) - limaHomeEnv := fmt.Sprintf("%s=%s", envKeyLimaHome, lcc.limaHomePath) +const ( + envKeyLimaHome = "LIMA_HOME" + envKeyUnixPath = "PATH" + envKeyWinPath = "Path" +) + +func (ncc *nerdctlCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, args ...string) Command { + ncc.logger.Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", args, envKeyLimaHome, ncc.limaHomePath) + cmd := ncc.cmdCreator.Create(ncc.limactlPath, args...) + limaHomeEnv := fmt.Sprintf("%s=%s", envKeyLimaHome, ncc.limaHomePath) var pathEnv string var envKeyPath string var path string if runtime.GOOS == "windows" { envKeyPath = envKeyWinPath - path = lcc.systemDeps.Env(envKeyPath) - path = fmt.Sprintf(`%s\;%s`, lcc.binPath, path) + path = ncc.systemDeps.Env(envKeyPath) + path = fmt.Sprintf(`%s\;%s`, ncc.binPath, path) pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) } else { envKeyPath = envKeyUnixPath - path = lcc.systemDeps.Env(envKeyPath) - path = fmt.Sprintf("%s:%s", lcc.binPath, path) + path = ncc.systemDeps.Env(envKeyPath) + path = fmt.Sprintf("%s:%s", ncc.binPath, path) pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) } - newPathEnv := replaceOrAppend(lcc.systemDeps.Environ(), envKeyLimaHome, limaHomeEnv) + newPathEnv := replaceOrAppend(ncc.systemDeps.Environ(), envKeyLimaHome, limaHomeEnv) newPathEnv = replaceOrAppend(newPathEnv, envKeyPath, pathEnv) cmd.SetEnv(newPathEnv) diff --git a/pkg/command/nerdctl_test.go b/pkg/command/nerdctl_test.go index cb1137de4..3937ac2ec 100644 --- a/pkg/command/nerdctl_test.go +++ b/pkg/command/nerdctl_test.go @@ -72,7 +72,7 @@ func TestLimaCmdCreator_Create(t *testing.T) { logger := mocks.NewLogger(ctrl) lcd := mocks.NewLimaCmdCreatorSystemDeps(ctrl) tc.mockSvc(logger, cmdCreator, cmd, lcd) - command.NewLimaCmdCreator(cmdCreator, logger, mockLimaHomePath, mockLimactlPath, mockQemuBinPath, lcd).Create(mockArgs...) + command.NewNerdctlCmdCreator(cmdCreator, logger, mockLimaHomePath, mockLimactlPath, mockQemuBinPath, lcd).Create(mockArgs...) }) } } @@ -115,7 +115,7 @@ func TestLimaCmdCreator_CreateWithoutStdio(t *testing.T) { logger := mocks.NewLogger(ctrl) lcd := mocks.NewLimaCmdCreatorSystemDeps(ctrl) tc.mockSvc(logger, cmdCreator, cmd, lcd) - command.NewLimaCmdCreator(cmdCreator, logger, mockLimaHomePath, mockLimactlPath, mockQemuBinPath, lcd). + command.NewNerdctlCmdCreator(cmdCreator, logger, mockLimaHomePath, mockLimactlPath, mockQemuBinPath, lcd). CreateWithoutStdio(mockArgs...) }) } @@ -304,7 +304,7 @@ func TestLimaCmdCreator_RunWithReplacingStdout(t *testing.T) { require.NoError(t, err) tc.mockSvc(logger, cmdCreator, lcd, ctrl, tc.inOut, stdoutFile) - assert.Equal(t, tc.wantErr, command.NewLimaCmdCreator(cmdCreator, logger, mockLimaHomePath, mockLimactlPath, mockQemuBinPath, lcd). + assert.Equal(t, tc.wantErr, command.NewNerdctlCmdCreator(cmdCreator, logger, mockLimaHomePath, mockLimactlPath, mockQemuBinPath, lcd). RunWithReplacingStdout(tc.stdoutRs, mockArgs...)) stdout, err := os.ReadFile(stdoutFilepath) diff --git a/pkg/config/config.go b/pkg/config/config.go index f2465da28..d41a82a36 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -14,6 +14,7 @@ import ( "fmt" "path/filepath" + "github.com/lima-vm/lima/pkg/limayaml" "github.com/spf13/afero" "gopkg.in/yaml.v3" @@ -28,7 +29,13 @@ type AdditionalDirectory struct { Path *string `yaml:"path"` } -type GeneralSettings struct { +// SystemSettings represents all settings shared by virtualized Finch configurations. +type SharedSystemSettings struct { + VMType *limayaml.VMType `yaml:"vmType,omitempty"` +} + +// GeneralSettings represents settings shared by all Finch configurations. +type SharedSettings struct { Snapshotters []string `yaml:"snapshotters,omitempty"` CredsHelpers []string `yaml:"creds_helpers,omitempty"` } diff --git a/pkg/config/config_darwin.go b/pkg/config/config_darwin.go index c7c9177af..fc9687ed1 100644 --- a/pkg/config/config_darwin.go +++ b/pkg/config/config_darwin.go @@ -10,7 +10,6 @@ import ( "strconv" "strings" - "github.com/lima-vm/lima/pkg/limayaml" "github.com/spf13/afero" "github.com/runfinch/finch/pkg/command" @@ -19,15 +18,18 @@ import ( "github.com/runfinch/finch/pkg/system" ) -// Finch represents the configuration file for Finch CLI. -type Finch struct { +type SystemSettings struct { CPUs *int `yaml:"cpus,omitempty"` Memory *string `yaml:"memory,omitempty"` AdditionalDirectories []AdditionalDirectory `yaml:"additional_directories,omitempty"` - VMType *limayaml.VMType `yaml:"vmType,omitempty"` Rosetta *bool `yaml:"rosetta,omitempty"` - Snapshotters []string `yaml:"snapshotters,omitempty"` - CredsHelpers []string `yaml:"creds_helpers,omitempty"` + SharedSystemSettings `yaml:",inline"` +} + +// Finch represents the configuration file for Finch CLI. +type Finch struct { + SystemSettings `yaml:",inline"` + SharedSettings `yaml:",inline"` } // SupportsVirtualizationFramework checks if the user's system supports Virtualization.framework. diff --git a/pkg/config/config_native.go b/pkg/config/config_native.go index 3cff48087..6509dbb0d 100644 --- a/pkg/config/config_native.go +++ b/pkg/config/config_native.go @@ -6,5 +6,5 @@ package config type Finch struct { - GeneralSettings + SharedSettings } diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index b9101a9a2..9f7a241f2 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/golang/mock/gomock" + "github.com/lima-vm/lima/pkg/limayaml" "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -20,6 +21,15 @@ import ( "github.com/runfinch/finch/pkg/mocks" ) +func makeConfig(vmType limayaml.VMType, memory string, cpus int, rosetta bool) *Finch { + fc := Finch{} + fc.VMType = pointer.String(vmType) + fc.Memory = pointer.String(memory) + fc.CPUs = pointer.Int(cpus) + fc.Rosetta = pointer.Bool(rosetta) + return &fc +} + func TestLoad(t *testing.T) { t.Parallel() testCases := []struct { @@ -94,12 +104,7 @@ cpus: 8 ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) c.EXPECT().Output().Return([]byte("14.0.0"), nil) }, - want: &Finch{ - Memory: pointer.String("4GiB"), - CPUs: pointer.Int(8), - VMType: pointer.String("vz"), - Rosetta: pointer.Bool(false), - }, + want: makeConfig("vz", "4GiB", 8, false), wantErr: nil, }, { @@ -120,12 +125,7 @@ cpus: 8 ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) c.EXPECT().Output().Return([]byte("14.0.0"), nil) }, - want: &Finch{ - Memory: pointer.String("3GiB"), - CPUs: pointer.Int(2), - VMType: pointer.String("vz"), - Rosetta: pointer.Bool(false), - }, + want: makeConfig("vz", "3GiB", 2, false), wantErr: nil, }, { @@ -146,12 +146,7 @@ cpus: 8 ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) c.EXPECT().Output().Return([]byte("14.0.0"), nil) }, - want: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(2), - VMType: pointer.String("vz"), - Rosetta: pointer.Bool(true), - }, + want: makeConfig("vz", "2GiB", 2, true), wantErr: nil, }, { @@ -172,12 +167,7 @@ cpus: 8 ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) c.EXPECT().Output().Return([]byte("14.0.0"), nil) }, - want: &Finch{ - Memory: pointer.String("3GiB"), - CPUs: pointer.Int(2), - VMType: pointer.String("vz"), - Rosetta: pointer.Bool(false), - }, + want: makeConfig("vz", "3GiB", 2, false), wantErr: nil, }, { @@ -198,12 +188,7 @@ cpus: 8 ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) c.EXPECT().Output().Return([]byte("14.0.0"), nil) }, - want: &Finch{ - Memory: pointer.String("3GiB"), - CPUs: pointer.Int(2), - VMType: pointer.String("vz"), - Rosetta: pointer.Bool(false), - }, + want: makeConfig("vz", "3GiB", 2, false), wantErr: nil, }, } @@ -240,9 +225,11 @@ cpus: 8 require.NoError(t, afero.WriteFile(fs, "/config.yaml", []byte(data), 0o600)) }, want: &Finch{ - Memory: pointer.String("4GiB"), - CPUs: pointer.Int(8), - VMType: pointer.String("wsl2"), + SystemSettings: SystemSettings{ + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("wsl2"), + }, + }, }, wantErr: nil, }, @@ -260,7 +247,11 @@ cpus: 8 require.NoError(t, afero.WriteFile(fs, "/config.yaml", []byte(""), 0o600)) }, want: &Finch{ - VMType: pointer.String("wsl2"), + SystemSettings: SystemSettings{ + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("wsl2"), + }, + }, }, wantErr: nil, }, @@ -275,11 +266,17 @@ cpus: 8 _ *mocks.CommandCreator, _ *gomock.Controller, ) { - require.NoError(t, afero.WriteFile(fs, "/config.yaml", []byte("memory: 2GiB"), 0o600)) + require.NoError(t, afero.WriteFile(fs, "/config.yaml", []byte("snapshotters:\n - soci"), 0o600)) }, want: &Finch{ - Memory: pointer.String("2GiB"), - VMType: pointer.String("wsl2"), + SharedSettings: SharedSettings{ + Snapshotters: []string{"soci"}, + }, + SystemSettings: SystemSettings{ + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("wsl2"), + }, + }, }, wantErr: nil, }, @@ -297,7 +294,11 @@ cpus: 8 require.NoError(t, afero.WriteFile(fs, "/config.yaml", []byte("unknownField: 2GiB"), 0o600)) }, want: &Finch{ - VMType: pointer.String("wsl2"), + SystemSettings: SystemSettings{ + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("wsl2"), + }, + }, }, wantErr: nil, }, @@ -315,7 +316,11 @@ cpus: 8 l.EXPECT().Infof("Using default values due to missing config file at %q", "/config.yaml") }, want: &Finch{ - VMType: pointer.String("wsl2"), + SystemSettings: SystemSettings{ + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("wsl2"), + }, + }, }, wantErr: nil, }, @@ -365,8 +370,10 @@ func Test_writeConfig(t *testing.T) { { name: "happy path", cfg: &Finch{ - CPUs: pointer.Int(4), - Memory: pointer.String("4GiB"), + SystemSettings: SystemSettings{ + CPUs: pointer.Int(4), + Memory: pointer.String("4GiB"), + }, }, path: "/config.yaml", mockSvc: func(_ *testing.T, _ afero.Fs) {}, @@ -641,8 +648,10 @@ func Test_loadFinchConfig(t *testing.T) { mem.EXPECT().TotalMemory().Return(uint64(6_442_450_944)) }, want: &Finch{ - CPUs: pointer.Int(2), - Memory: pointer.String("6GiB"), + SystemSettings: SystemSettings{ + CPUs: pointer.Int(2), + Memory: pointer.String("6GiB"), + }, }, errMsg: "", }, @@ -691,8 +700,10 @@ func Test_loadFinchConfig(t *testing.T) { require.NoError(t, afero.WriteFile(fs, "/config.yaml", []byte(data), 0o600)) }, want: &Finch{ - CPUs: pointer.Int(2), - Memory: pointer.String("6GiB"), + SystemSettings: SystemSettings{ + CPUs: pointer.Int(2), + Memory: pointer.String("6GiB"), + }, }, errMsg: "", }, diff --git a/pkg/config/config_windows.go b/pkg/config/config_windows.go index ee8e3e2c9..801894c6e 100644 --- a/pkg/config/config_windows.go +++ b/pkg/config/config_windows.go @@ -6,15 +6,18 @@ package config import ( - "github.com/lima-vm/lima/pkg/limayaml" "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/flog" "github.com/spf13/afero" ) +type SystemSettings struct { + SharedSystemSettings `yaml:",inline"` +} + type Finch struct { - VMType *limayaml.VMType `yaml:"vmType,omitempty"` - GeneralSettings + SystemSettings `yaml:",inline"` + SharedSettings `yaml:",inline"` } // SupportsWSL2 checks if system supports WSL2 and sets default version to 2. diff --git a/pkg/config/defaults_darwin_test.go b/pkg/config/defaults_darwin_test.go new file mode 100644 index 000000000..833ad9c2b --- /dev/null +++ b/pkg/config/defaults_darwin_test.go @@ -0,0 +1,167 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build darwin + +package config + +import ( + "fmt" + + "github.com/golang/mock/gomock" + "github.com/xorcare/pointer" + + "github.com/runfinch/finch/pkg/mocks" +) + +func applyDefaultPlatformSpecificTestCases() applyDefaultTestCases { + return []struct { + name string + cfg *Finch + mockSvc func( + deps *mocks.LoadSystemDeps, + mem *mocks.Memory, + ecc *mocks.CommandCreator, + ctrl *gomock.Controller, + ) + want *Finch + }{ + { + name: "happy path", + cfg: &Finch{}, + mockSvc: func( + deps *mocks.LoadSystemDeps, + mem *mocks.Memory, + ecc *mocks.CommandCreator, + ctrl *gomock.Controller, + ) { + deps.EXPECT().NumCPU().Return(8) + // 12,884,901,888 == 12GiB + mem.EXPECT().TotalMemory().Return(uint64(12_884_901_888)) + c := mocks.NewCommand(ctrl) + ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) + c.EXPECT().Output().Return([]byte("14.0.0"), nil) + }, + want: makeConfig("vz", "3GiB", 2, false), + }, + { + name: "fills CPUs with default when unset", + cfg: &Finch{ + SystemSettings: SystemSettings{ + Memory: pointer.String("4GiB"), + }, + }, + mockSvc: func( + deps *mocks.LoadSystemDeps, + _ *mocks.Memory, + ecc *mocks.CommandCreator, + ctrl *gomock.Controller, + ) { + deps.EXPECT().NumCPU().Return(8) + c := mocks.NewCommand(ctrl) + ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) + c.EXPECT().Output().Return([]byte("14.0.0"), nil) + }, + want: makeConfig("vz", "4GiB", 2, false), + }, + { + name: "fills memory with default when unset", + cfg: &Finch{ + SystemSettings: SystemSettings{ + CPUs: pointer.Int(6), + }, + }, + mockSvc: func( + _ *mocks.LoadSystemDeps, + mem *mocks.Memory, + ecc *mocks.CommandCreator, + ctrl *gomock.Controller, + ) { + // 12,884,901,888 == 12GiB + mem.EXPECT().TotalMemory().Return(uint64(12_884_901_888)) + c := mocks.NewCommand(ctrl) + ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) + c.EXPECT().Output().Return([]byte("14.0.0"), nil) + }, + want: makeConfig("vz", "3GiB", 6, false), + }, + { + name: "fills with fallbacks when defaults are too low", + cfg: &Finch{}, + mockSvc: func( + deps *mocks.LoadSystemDeps, + mem *mocks.Memory, + ecc *mocks.CommandCreator, + ctrl *gomock.Controller, + ) { + deps.EXPECT().NumCPU().Return(4) + // 1,073,741,824 == 1GiB + mem.EXPECT().TotalMemory().Return(uint64(1_073_741_824)) + c := mocks.NewCommand(ctrl) + ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) + c.EXPECT().Output().Return([]byte("14.0.0"), nil) + }, + want: makeConfig("vz", "2GiB", 2, false), + }, + { + name: "doesn't override existing values", + cfg: &Finch{ + SystemSettings: SystemSettings{ + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, + }, + mockSvc: func( + deps *mocks.LoadSystemDeps, + mem *mocks.Memory, + ecc *mocks.CommandCreator, + ctrl *gomock.Controller, + ) { + deps.EXPECT().NumCPU().Return(8) + // 12,884,901,888 == 12GiB + mem.EXPECT().TotalMemory().Return(uint64(12_884_901_888)) + c := mocks.NewCommand(ctrl) + ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) + c.EXPECT().Output().Return([]byte("14.0.0"), nil) + }, + want: makeConfig("qemu", "3GiB", 2, false), + }, + { + name: "falls back to qemu on old versions", + cfg: &Finch{}, + mockSvc: func( + deps *mocks.LoadSystemDeps, + mem *mocks.Memory, + ecc *mocks.CommandCreator, + ctrl *gomock.Controller, + ) { + deps.EXPECT().NumCPU().Return(8) + // 12,884,901,888 == 12GiB + mem.EXPECT().TotalMemory().Return(uint64(12_884_901_888)) + c := mocks.NewCommand(ctrl) + ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) + c.EXPECT().Output().Return([]byte("12.0.0"), nil) + }, + want: makeConfig("qemu", "3GiB", 2, false), + }, + { + name: "falls back to qemu if there's an error", + cfg: &Finch{}, + mockSvc: func( + deps *mocks.LoadSystemDeps, + mem *mocks.Memory, + ecc *mocks.CommandCreator, + ctrl *gomock.Controller, + ) { + deps.EXPECT().NumCPU().Return(8) + // 12,884,901,888 == 12GiB + mem.EXPECT().TotalMemory().Return(uint64(12_884_901_888)) + c := mocks.NewCommand(ctrl) + ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) + c.EXPECT().Output().Return([]byte("12.0.0"), fmt.Errorf("an error")) + }, + want: makeConfig("qemu", "3GiB", 2, false), + }, + } +} diff --git a/pkg/config/defaults_test.go b/pkg/config/defaults_test.go index 36fd18e9e..e6497517a 100644 --- a/pkg/config/defaults_test.go +++ b/pkg/config/defaults_test.go @@ -1,263 +1,36 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin +//go:build (darwin || windows) && !native package config import ( - "fmt" - "runtime" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" - "github.com/xorcare/pointer" "github.com/runfinch/finch/pkg/mocks" ) +type applyDefaultTestCases []struct { + name string + cfg *Finch + mockSvc func( + deps *mocks.LoadSystemDeps, + mem *mocks.Memory, + ecc *mocks.CommandCreator, + ctrl *gomock.Controller, + ) + want *Finch +} + func Test_applyDefaults(t *testing.T) { t.Parallel() - var testCases []struct { - name string - cfg *Finch - mockSvc func( - deps *mocks.LoadSystemDeps, - mem *mocks.Memory, - ecc *mocks.CommandCreator, - ctrl *gomock.Controller, - ) - want *Finch - } - darwinTestCases := []struct { - name string - cfg *Finch - mockSvc func( - deps *mocks.LoadSystemDeps, - mem *mocks.Memory, - ecc *mocks.CommandCreator, - ctrl *gomock.Controller, - ) - want *Finch - }{ - { - name: "happy path", - cfg: &Finch{}, - mockSvc: func( - deps *mocks.LoadSystemDeps, - mem *mocks.Memory, - ecc *mocks.CommandCreator, - ctrl *gomock.Controller, - ) { - deps.EXPECT().NumCPU().Return(8) - // 12,884,901,888 == 12GiB - mem.EXPECT().TotalMemory().Return(uint64(12_884_901_888)) - c := mocks.NewCommand(ctrl) - ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) - c.EXPECT().Output().Return([]byte("14.0.0"), nil) - }, - want: &Finch{ - CPUs: pointer.Int(2), - Memory: pointer.String("3GiB"), - VMType: pointer.String("vz"), - Rosetta: pointer.Bool(false), - }, - }, - { - name: "fills CPUs with default when unset", - cfg: &Finch{ - Memory: pointer.String("4GiB"), - }, - mockSvc: func( - deps *mocks.LoadSystemDeps, - _ *mocks.Memory, - ecc *mocks.CommandCreator, - ctrl *gomock.Controller, - ) { - deps.EXPECT().NumCPU().Return(8) - c := mocks.NewCommand(ctrl) - ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) - c.EXPECT().Output().Return([]byte("14.0.0"), nil) - }, - want: &Finch{ - CPUs: pointer.Int(2), - Memory: pointer.String("4GiB"), - VMType: pointer.String("vz"), - Rosetta: pointer.Bool(false), - }, - }, - { - name: "fills memory with default when unset", - cfg: &Finch{ - CPUs: pointer.Int(6), - }, - mockSvc: func( - _ *mocks.LoadSystemDeps, - mem *mocks.Memory, - ecc *mocks.CommandCreator, - ctrl *gomock.Controller, - ) { - // 12,884,901,888 == 12GiB - mem.EXPECT().TotalMemory().Return(uint64(12_884_901_888)) - c := mocks.NewCommand(ctrl) - ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) - c.EXPECT().Output().Return([]byte("14.0.0"), nil) - }, - want: &Finch{ - CPUs: pointer.Int(6), - Memory: pointer.String("3GiB"), - VMType: pointer.String("vz"), - Rosetta: pointer.Bool(false), - }, - }, - { - name: "fills with fallbacks when defaults are too low", - cfg: &Finch{}, - mockSvc: func( - deps *mocks.LoadSystemDeps, - mem *mocks.Memory, - ecc *mocks.CommandCreator, - ctrl *gomock.Controller, - ) { - deps.EXPECT().NumCPU().Return(4) - // 1,073,741,824 == 1GiB - mem.EXPECT().TotalMemory().Return(uint64(1_073_741_824)) - c := mocks.NewCommand(ctrl) - ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) - c.EXPECT().Output().Return([]byte("14.0.0"), nil) - }, - want: &Finch{ - CPUs: pointer.Int(2), - Memory: pointer.String("2GiB"), - VMType: pointer.String("vz"), - Rosetta: pointer.Bool(false), - }, - }, - { - name: "doesn't override existing values", - cfg: &Finch{ - VMType: pointer.String("qemu"), - }, - mockSvc: func( - deps *mocks.LoadSystemDeps, - mem *mocks.Memory, - ecc *mocks.CommandCreator, - ctrl *gomock.Controller, - ) { - deps.EXPECT().NumCPU().Return(8) - // 12,884,901,888 == 12GiB - mem.EXPECT().TotalMemory().Return(uint64(12_884_901_888)) - c := mocks.NewCommand(ctrl) - ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) - c.EXPECT().Output().Return([]byte("14.0.0"), nil) - }, - want: &Finch{ - CPUs: pointer.Int(2), - Memory: pointer.String("3GiB"), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - }, - }, - { - name: "falls back to qemu on old versions", - cfg: &Finch{}, - mockSvc: func( - deps *mocks.LoadSystemDeps, - mem *mocks.Memory, - ecc *mocks.CommandCreator, - ctrl *gomock.Controller, - ) { - deps.EXPECT().NumCPU().Return(8) - // 12,884,901,888 == 12GiB - mem.EXPECT().TotalMemory().Return(uint64(12_884_901_888)) - c := mocks.NewCommand(ctrl) - ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) - c.EXPECT().Output().Return([]byte("12.0.0"), nil) - }, - want: &Finch{ - CPUs: pointer.Int(2), - Memory: pointer.String("3GiB"), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - }, - }, - { - name: "falls back to qemu if there's an error", - cfg: &Finch{}, - mockSvc: func( - deps *mocks.LoadSystemDeps, - mem *mocks.Memory, - ecc *mocks.CommandCreator, - ctrl *gomock.Controller, - ) { - deps.EXPECT().NumCPU().Return(8) - // 12,884,901,888 == 12GiB - mem.EXPECT().TotalMemory().Return(uint64(12_884_901_888)) - c := mocks.NewCommand(ctrl) - ecc.EXPECT().Create("sw_vers", "-productVersion").Return(c) - c.EXPECT().Output().Return([]byte("12.0.0"), fmt.Errorf("an error")) - }, - want: &Finch{ - CPUs: pointer.Int(2), - Memory: pointer.String("3GiB"), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - }, - }, - } - - windowsTestCases := []struct { - name string - cfg *Finch - mockSvc func( - deps *mocks.LoadSystemDeps, - mem *mocks.Memory, - ecc *mocks.CommandCreator, - ctrl *gomock.Controller, - ) - want *Finch - }{ - { - name: "happy path", - cfg: &Finch{}, - mockSvc: func( - _ *mocks.LoadSystemDeps, - _ *mocks.Memory, - _ *mocks.CommandCreator, - _ *gomock.Controller, - ) { - }, - want: &Finch{ - VMType: pointer.String("wsl2"), - }, - }, - { - name: "does not fill wsl2 default when it's set to something else", - cfg: &Finch{ - VMType: pointer.String("wsl"), - }, - mockSvc: func( - _ *mocks.LoadSystemDeps, - _ *mocks.Memory, - _ *mocks.CommandCreator, - _ *gomock.Controller, - ) { - }, - want: &Finch{ - VMType: pointer.String("wsl"), - }, - }, - } - switch runtime.GOOS { - case "windows": - testCases = append(testCases, windowsTestCases...) - case "darwin": - testCases = append(testCases, darwinTestCases...) - default: - t.Skip("Not running tests for " + runtime.GOOS) - } + testCases := applyDefaultTestCases{} + testCases = append(testCases, applyDefaultPlatformSpecificTestCases()...) for _, tc := range testCases { tc := tc diff --git a/pkg/config/defaults_windows_test.go b/pkg/config/defaults_windows_test.go new file mode 100644 index 000000000..8794a676a --- /dev/null +++ b/pkg/config/defaults_windows_test.go @@ -0,0 +1,46 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build windows + +package config + +import ( + "github.com/golang/mock/gomock" + "github.com/xorcare/pointer" + + "github.com/runfinch/finch/pkg/mocks" +) + +func applyDefaultPlatformSpecificTestCases() applyDefaultTestCases { + return []struct { + name string + cfg *Finch + mockSvc func( + deps *mocks.LoadSystemDeps, + mem *mocks.Memory, + ecc *mocks.CommandCreator, + ctrl *gomock.Controller, + ) + want *Finch + }{ + { + name: "happy path", + cfg: &Finch{}, + mockSvc: func( + _ *mocks.LoadSystemDeps, + _ *mocks.Memory, + _ *mocks.CommandCreator, + _ *gomock.Controller, + ) { + }, + want: &Finch{ + SystemSettings: SystemSettings{ + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("wsl2"), + }, + }, + }, + }, + } +} diff --git a/pkg/config/lima_config_applier_darwin_test.go b/pkg/config/lima_config_applier_darwin_test.go index 535666f00..f20fe8a68 100644 --- a/pkg/config/lima_config_applier_darwin_test.go +++ b/pkg/config/lima_config_applier_darwin_test.go @@ -42,13 +42,8 @@ func TestDiskLimaConfigApplier_Apply(t *testing.T) { want error }{ { - name: "happy path", - config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - }, + name: "happy path", + config: makeConfig("qemu", "2GiB", 4, false), defaultPath: "/default.yaml", overridePath: "/override.yaml", isInit: true, @@ -85,11 +80,17 @@ func TestDiskLimaConfigApplier_Apply(t *testing.T) { { name: "adds soci script and sets soci as default snapshotter when soci is first in snapshotters array", config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - Snapshotters: []string{"soci"}, + SystemSettings: SystemSettings{ + Memory: pointer.String("2GiB"), + CPUs: pointer.Int(4), + Rosetta: pointer.Bool(false), + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, + SharedSettings: SharedSettings{ + Snapshotters: []string{"soci"}, + }, }, defaultPath: "/default.yaml", overridePath: "/override.yaml", @@ -143,11 +144,17 @@ func TestDiskLimaConfigApplier_Apply(t *testing.T) { { name: "doesn't add soci script and doesn't change default snapshotter when snapshotters is not set in config", config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - Snapshotters: []string{}, + SystemSettings: SystemSettings{ + Memory: pointer.String("2GiB"), + CPUs: pointer.Int(4), + Rosetta: pointer.Bool(false), + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, + SharedSettings: SharedSettings{ + Snapshotters: []string{}, + }, }, defaultPath: "/default.yaml", overridePath: "/override.yaml", @@ -191,11 +198,17 @@ func TestDiskLimaConfigApplier_Apply(t *testing.T) { { name: "doesn't add soci script when soci is not in snapshotters array", config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - Snapshotters: []string{"overlayfs"}, + SystemSettings: SystemSettings{ + Memory: pointer.String("2GiB"), + CPUs: pointer.Int(4), + Rosetta: pointer.Bool(false), + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, + SharedSettings: SharedSettings{ + Snapshotters: []string{"overlayfs"}, + }, }, defaultPath: "/default.yaml", overridePath: "/override.yaml", @@ -237,11 +250,17 @@ func TestDiskLimaConfigApplier_Apply(t *testing.T) { { name: "adds soci script but keeps overlayfs as default when soci is present in snapshotters array but not first element", config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - Snapshotters: []string{"overlayfs", "soci"}, + SystemSettings: SystemSettings{ + Memory: pointer.String("2GiB"), + CPUs: pointer.Int(4), + Rosetta: pointer.Bool(false), + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, + SharedSettings: SharedSettings{ + Snapshotters: []string{"overlayfs", "soci"}, + }, }, defaultPath: "/default.yaml", overridePath: "/override.yaml", @@ -296,11 +315,17 @@ func TestDiskLimaConfigApplier_Apply(t *testing.T) { { name: "doesn't add soci script when snapshotter is not set in config", config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - Snapshotters: []string{"soci", "overlayfs"}, + SystemSettings: SystemSettings{ + Memory: pointer.String("2GiB"), + CPUs: pointer.Int(4), + Rosetta: pointer.Bool(false), + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, + SharedSettings: SharedSettings{ + Snapshotters: []string{"soci", "overlayfs"}, + }, }, defaultPath: "/default.yaml", overridePath: "/override.yaml", @@ -352,13 +377,8 @@ func TestDiskLimaConfigApplier_Apply(t *testing.T) { want: nil, }, { - name: "updates vmType and removes cross-arch provisioning script and network config", - config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - VMType: pointer.String("vz"), - Rosetta: pointer.Bool(true), - }, + name: "updates vmType and removes cross-arch provisioning script and network config", + config: makeConfig("vz", "2GiB", 4, true), defaultPath: "/default.yaml", overridePath: "/override.yaml", isInit: true, @@ -418,13 +438,8 @@ func TestDiskLimaConfigApplier_Apply(t *testing.T) { want: nil, }, { - name: "updates vmType from vz to qemu and adds cross-arch provisioning script", - config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - }, + name: "updates vmType from vz to qemu and adds cross-arch provisioning script", + config: makeConfig("qemu", "2GiB", 4, false), defaultPath: "/default.yaml", overridePath: "/override.yaml", isInit: true, @@ -469,13 +484,8 @@ rosetta: want: nil, }, { - name: "does not update lima config because isInit == false", - config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - VMType: pointer.String("vz"), - Rosetta: pointer.Bool(false), - }, + name: "does not update lima config because isInit == false", + config: makeConfig("vz", "2GiB", 4, false), defaultPath: "/default.yaml", overridePath: "/override.yaml", isInit: false, @@ -503,13 +513,8 @@ mountType: "reverse-sshfs"`), 0o600) want: nil, }, { - name: "lima config file does not exist", - config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - }, + name: "lima config file does not exist", + config: makeConfig("qemu", "2GiB", 4, false), defaultPath: "/default.yaml", overridePath: "/override.yaml", isInit: true, @@ -546,13 +551,8 @@ mountType: "reverse-sshfs"`), 0o600) want: nil, }, { - name: "lima config file does not contain valid YAML", - config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), - }, + name: "lima config file does not contain valid YAML", + config: makeConfig("qemu", "2GiB", 4, false), defaultPath: "/default.yaml", overridePath: "/override.yaml", isInit: true, @@ -591,11 +591,18 @@ mountType: "reverse-sshfs"`), 0o600) { name: "lima config file with additional directories", config: &Finch{ - Memory: pointer.String("2GiB"), - CPUs: pointer.Int(4), - AdditionalDirectories: []AdditionalDirectory{{pointer.String("/Volumes")}}, - VMType: pointer.String("qemu"), - Rosetta: pointer.Bool(false), + SystemSettings: SystemSettings{ + Memory: pointer.String("2GiB"), + CPUs: pointer.Int(4), + Rosetta: pointer.Bool(false), + AdditionalDirectories: []AdditionalDirectory{{pointer.String("/Volumes")}}, + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, + SharedSettings: SharedSettings{ + Snapshotters: []string{"soci", "overlayfs"}, + }, }, defaultPath: "/default.yaml", overridePath: "/override.yaml", diff --git a/pkg/config/lima_config_applier_native.go b/pkg/config/lima_config_applier_native.go index 8c7424c01..5455e2bb9 100644 --- a/pkg/config/lima_config_applier_native.go +++ b/pkg/config/lima_config_applier_native.go @@ -36,11 +36,11 @@ func (lca *limaConfigApplier) ConfigureOverrideLimaYaml() error { return nil } -func (lca *limaConfigApplier) configureDefaultSnapshotter(limaCfg *limayaml.LimaYAML) error { +func (lca *limaConfigApplier) configureDefaultSnapshotter(_ *limayaml.LimaYAML) error { return nil } -func (lca *limaConfigApplier) provisionSnapshotters(limaCfg *limayaml.LimaYAML) error { +func (lca *limaConfigApplier) provisionSnapshotters(_ *limayaml.LimaYAML) error { return nil } diff --git a/pkg/config/nerdctl_config_applier.go b/pkg/config/nerdctl_config_applier.go index 8864d98d7..79513abcb 100644 --- a/pkg/config/nerdctl_config_applier.go +++ b/pkg/config/nerdctl_config_applier.go @@ -88,7 +88,7 @@ func updateNerdctlConfig(fs afero.Fs, homeDir string, rootless bool) error { var cfg Nerdctl cfgBuf, err := afero.ReadFile(fs, cfgPath) if err != nil { - return fmt.Errorf("failed to read config file %q: %w", cfgPath, err) + return fmt.Errorf("updateEnvironment %q: %w", cfgPath, err) } if err := toml.Unmarshal(cfgBuf, &cfg); err != nil { @@ -122,11 +122,11 @@ func (nca *nerdctlConfigApplier) Apply(remoteAddr string) error { } // rootless hardcoded to false for now to match our finch.yaml file - if err := updateNerdctlConfig(nca.fs, homeDir, false); err != nil { + if err := updateNerdctlConfig(nFs, homeDir, false); err != nil { return fmt.Errorf("failed to update the nerdctl config file: %w", err) } - if err := updateEnvironment(nFs, nca.fc, nca.finchDir, homeDir, nca.homeDir); err != nil { + if err := updateEnvironment(nFs, nca.fc, nca.finchDir, homeDir, homeDir); err != nil { return fmt.Errorf("failed to update the user's .profile file: %w", err) } return nil diff --git a/pkg/config/nerdctl_config_applier_test.go b/pkg/config/nerdctl_config_applier_test.go index fd013551a..60a6abcb5 100644 --- a/pkg/config/nerdctl_config_applier_test.go +++ b/pkg/config/nerdctl_config_applier_test.go @@ -47,7 +47,11 @@ func Test_updateEnvironment(t *testing.T) { { name: "happy path", cfg: &Finch{ - VMType: pointer.String("qemu"), + SystemSettings: SystemSettings{ + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, }, finchDir: "/finch/dir", homeDir: "/home/dir", @@ -71,7 +75,11 @@ export DOCKER_CONFIG="$FINCH_DIR" { name: "happy path, file already exists and already contains expected variables", cfg: &Finch{ - VMType: pointer.String("qemu"), + SystemSettings: SystemSettings{ + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, }, finchDir: "/finch/dir", homeDir: "/home/dir", @@ -108,7 +116,11 @@ export DOCKER_CONFIG="$FINCH_DIR" { name: ".bashrc file doesn't exist", cfg: &Finch{ - VMType: pointer.String("qemu"), + SystemSettings: SystemSettings{ + SharedSystemSettings: SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, }, finchDir: "/finch/dir", homeDir: "/home/dir", diff --git a/pkg/config/validate_darwin_test.go b/pkg/config/validate_darwin_test.go index 4616fb867..584068349 100644 --- a/pkg/config/validate_darwin_test.go +++ b/pkg/config/validate_darwin_test.go @@ -28,8 +28,10 @@ func TestValidate(t *testing.T) { { name: "happy path", cfg: &Finch{ - CPUs: pointer.Int(4), - Memory: pointer.String("4GiB"), + SystemSettings: SystemSettings{ + CPUs: pointer.Int(4), + Memory: pointer.String("4GiB"), + }, }, mockSvc: func(_ *mocks.Logger, deps *mocks.LoadSystemDeps, mem *mocks.Memory) { deps.EXPECT().NumCPU().Return(8) @@ -41,8 +43,10 @@ func TestValidate(t *testing.T) { { name: "config specifies less CPUs than required", cfg: &Finch{ - CPUs: pointer.Int(0), - Memory: pointer.String("0GiB"), + SystemSettings: SystemSettings{ + CPUs: pointer.Int(0), + Memory: pointer.String("0GiB"), + }, }, mockSvc: func(_ *mocks.Logger, _ *mocks.LoadSystemDeps, _ *mocks.Memory) {}, err: errors.New("specified number of CPUs (0) must be greater than 0"), @@ -50,8 +54,10 @@ func TestValidate(t *testing.T) { { name: "config specifies less memory than required", cfg: &Finch{ - CPUs: pointer.Int(1), - Memory: pointer.String("0GiB"), + SystemSettings: SystemSettings{ + CPUs: pointer.Int(1), + Memory: pointer.String("0GiB"), + }, }, mockSvc: func(_ *mocks.Logger, _ *mocks.LoadSystemDeps, _ *mocks.Memory) {}, err: errors.New("specified amount of memory (0GiB) must be greater than 0GiB"), @@ -59,8 +65,10 @@ func TestValidate(t *testing.T) { { name: "config specifies more CPUs than available", cfg: &Finch{ - CPUs: pointer.Int(4), - Memory: pointer.String("4GiB"), + SystemSettings: SystemSettings{ + CPUs: pointer.Int(4), + Memory: pointer.String("4GiB"), + }, }, mockSvc: func(l *mocks.Logger, deps *mocks.LoadSystemDeps, mem *mocks.Memory) { deps.EXPECT().NumCPU().Return(1) @@ -77,8 +85,10 @@ func TestValidate(t *testing.T) { { name: "config specifies more memory than available", cfg: &Finch{ - CPUs: pointer.Int(4), - Memory: pointer.String("4GiB"), + SystemSettings: SystemSettings{ + CPUs: pointer.Int(4), + Memory: pointer.String("4GiB"), + }, }, mockSvc: func(l *mocks.Logger, deps *mocks.LoadSystemDeps, mem *mocks.Memory) { deps.EXPECT().NumCPU().Return(8) diff --git a/pkg/dependency/vmnet/sudoers_file_unix.go b/pkg/dependency/vmnet/sudoers_file_unix.go index 60f25a80d..e2d125fca 100644 --- a/pkg/dependency/vmnet/sudoers_file_unix.go +++ b/pkg/dependency/vmnet/sudoers_file_unix.go @@ -21,13 +21,13 @@ import ( type sudoersFile struct { fs afero.Fs execCmdCreator command.Creator - limaCmdCreator command.LimaCmdCreator + limaCmdCreator command.NerdctlCmdCreator l flog.Logger } var _ dependency.Dependency = (*sudoersFile)(nil) -func newSudoersFile(fs afero.Fs, execCmdCreator command.Creator, limaCmdCreator command.LimaCmdCreator, l flog.Logger) *sudoersFile { +func newSudoersFile(fs afero.Fs, execCmdCreator command.Creator, limaCmdCreator command.NerdctlCmdCreator, l flog.Logger) *sudoersFile { return &sudoersFile{ fs: fs, execCmdCreator: execCmdCreator, diff --git a/pkg/dependency/vmnet/vmnet_unix.go b/pkg/dependency/vmnet/vmnet_unix.go index 6257dab3c..13363bd7e 100644 --- a/pkg/dependency/vmnet/vmnet_unix.go +++ b/pkg/dependency/vmnet/vmnet_unix.go @@ -30,7 +30,7 @@ const ( // NewDependencyGroup returns a dependency group that contains all the dependencies required to make vmnet networking work. func NewDependencyGroup( execCmdCreator command.Creator, - limaCmdCreator command.LimaCmdCreator, + limaCmdCreator command.NerdctlCmdCreator, fs afero.Fs, fp path.Finch, logger flog.Logger, @@ -41,7 +41,7 @@ func NewDependencyGroup( func newDeps( execCmdCreator command.Creator, - limaCmdCreator command.LimaCmdCreator, + limaCmdCreator command.NerdctlCmdCreator, fs afero.Fs, fp path.Finch, logger flog.Logger, diff --git a/pkg/disk/disk.go b/pkg/disk/disk.go index cb4975668..e6ff4ca05 100644 --- a/pkg/disk/disk.go +++ b/pkg/disk/disk.go @@ -29,7 +29,7 @@ type diskFS interface { } type userDataDiskManager struct { - lcc command.LimaCmdCreator + ncc command.NerdctlCmdCreator ecc command.Creator fs diskFS finch fpath.Finch @@ -40,7 +40,7 @@ type userDataDiskManager struct { // NewUserDataDiskManager is a constructor for UserDataDiskManager. func NewUserDataDiskManager( - lcc command.LimaCmdCreator, + ncc command.NerdctlCmdCreator, ecc command.Creator, fs diskFS, finch fpath.Finch, @@ -49,7 +49,7 @@ func NewUserDataDiskManager( logger flog.Logger, ) UserDataDiskManager { return &userDataDiskManager{ - lcc: lcc, + ncc: ncc, ecc: ecc, fs: fs, finch: finch, diff --git a/pkg/disk/disk_darwin.go b/pkg/disk/disk_darwin.go index 625fcef59..c7ddbc511 100644 --- a/pkg/disk/disk_darwin.go +++ b/pkg/disk/disk_darwin.go @@ -100,7 +100,7 @@ func (m *userDataDiskManager) persistentDiskExists() bool { } func (m *userDataDiskManager) limaDiskExists() bool { - cmd := m.lcc.CreateWithoutStdio("disk", "ls", diskName, "--json") + cmd := m.ncc.CreateWithoutStdio("disk", "ls", diskName, "--json") out, err := cmd.Output() if err != nil { return false @@ -158,7 +158,7 @@ func (m *userDataDiskManager) createLimaDisk() error { if err != nil { return fmt.Errorf("failed to get disk size: %w", err) } - cmd := m.lcc.CreateWithoutStdio("disk", "create", diskName, "--size", size, "--format", "raw") + cmd := m.ncc.CreateWithoutStdio("disk", "create", diskName, "--size", size, "--format", "raw") if logs, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("failed to create disk, debug logs:\n%s", logs) } @@ -208,7 +208,7 @@ func (m *userDataDiskManager) limaDiskIsLocked() bool { } func (m *userDataDiskManager) unlockLimaDisk() error { - cmd := m.lcc.CreateWithoutStdio("disk", "unlock", diskName) + cmd := m.ncc.CreateWithoutStdio("disk", "unlock", diskName) if logs, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("failed to unlock disk, debug logs:\n%s", logs) } diff --git a/pkg/disk/disk_darwin_test.go b/pkg/disk/disk_darwin_test.go index 522763af5..44315f47c 100644 --- a/pkg/disk/disk_darwin_test.go +++ b/pkg/disk/disk_darwin_test.go @@ -24,13 +24,13 @@ func TestDisk_NewUserDataDiskManager(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) ecc := mocks.NewCommandCreator(ctrl) dfs := mocks.NewMockdiskFS(ctrl) finch := fpath.Finch("mock_finch") homeDir := "mock_home" - NewUserDataDiskManager(lcc, ecc, dfs, finch, homeDir, &config.Finch{}, nil) + NewUserDataDiskManager(ncc, ecc, dfs, finch, homeDir, &config.Finch{}, nil) } func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { @@ -81,19 +81,23 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { name string cfg *config.Finch wantErr error - mockSvc func(lcc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, ecc *mocks.CommandCreator) + mockSvc func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, ecc *mocks.CommandCreator) }{ { name: "create and save disk", cfg: &config.Finch{ - VMType: pointer.String("qemu"), + SystemSettings: config.SystemSettings{ + SharedSystemSettings: config.SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, }, wantErr: nil, - mockSvc: func(lcc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { - lcc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) + mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { + ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte(""), nil) - lcc.EXPECT().CreateWithoutStdio(mockCreateArgs).Return(cmd) + ncc.EXPECT().CreateWithoutStdio(mockCreateArgs).Return(cmd) cmd.EXPECT().CombinedOutput().Return(nil, nil) dfs.EXPECT().Stat(finch.UserDataDiskPath(homeDir)).Return(nil, fs.ErrNotExist) @@ -109,11 +113,15 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { { name: "disk already exists", cfg: &config.Finch{ - VMType: pointer.String("qemu"), + SystemSettings: config.SystemSettings{ + SharedSystemSettings: config.SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, }, wantErr: nil, - mockSvc: func(lcc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { - lcc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) + mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { + ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return(listSuccessOutput, nil) dfs.EXPECT().ReadlinkIfPossible(limaPath).Return(finch.UserDataDiskPath(homeDir), nil) @@ -124,11 +132,15 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { { name: "disk exists but has not been saved", cfg: &config.Finch{ - VMType: pointer.String("qemu"), + SystemSettings: config.SystemSettings{ + SharedSystemSettings: config.SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, }, wantErr: nil, - mockSvc: func(lcc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { - lcc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) + mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { + ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return(listSuccessOutput, nil) // not a link @@ -147,14 +159,18 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { { name: "disk does not exist but a persistent disk does", cfg: &config.Finch{ - VMType: pointer.String("qemu"), + SystemSettings: config.SystemSettings{ + SharedSystemSettings: config.SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, }, wantErr: nil, - mockSvc: func(lcc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { - lcc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) + mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { + ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte(""), nil) - lcc.EXPECT().CreateWithoutStdio(mockCreateArgs).Return(cmd) + ncc.EXPECT().CreateWithoutStdio(mockCreateArgs).Return(cmd) cmd.EXPECT().CombinedOutput().Return(nil, nil) dfs.EXPECT().Stat(finch.UserDataDiskPath(homeDir)).Return(nil, nil) @@ -170,28 +186,36 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { { name: "disk already exists but is locked", cfg: &config.Finch{ - VMType: pointer.String("qemu"), + SystemSettings: config.SystemSettings{ + SharedSystemSettings: config.SharedSystemSettings{ + VMType: pointer.String("qemu"), + }, + }, }, wantErr: nil, - mockSvc: func(lcc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { - lcc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) + mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { + ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return(listSuccessOutput, nil) dfs.EXPECT().ReadlinkIfPossible(limaPath).Return(finch.UserDataDiskPath(homeDir), nil) dfs.EXPECT().Stat(lockPath).Return(nil, nil) - lcc.EXPECT().CreateWithoutStdio(mockUnlockArgs).Return(cmd) + ncc.EXPECT().CreateWithoutStdio(mockUnlockArgs).Return(cmd) cmd.EXPECT().CombinedOutput().Return(nil, nil) }, }, { name: "disk exists and using vz mode, but disk is the wrong format", cfg: &config.Finch{ - VMType: pointer.String("vz"), + SystemSettings: config.SystemSettings{ + SharedSystemSettings: config.SharedSystemSettings{ + VMType: pointer.String("vz"), + }, + }, }, wantErr: nil, - mockSvc: func(lcc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, ecc *mocks.CommandCreator) { - lcc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) + mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, ecc *mocks.CommandCreator) { + ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return(listSuccessOutput, nil) ecc.EXPECT().Create(mockQemuImgExePath, mockDiskInfoArgs).Return(cmd) @@ -222,12 +246,12 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) ecc := mocks.NewCommandCreator(ctrl) dfs := mocks.NewMockdiskFS(ctrl) cmd := mocks.NewCommand(ctrl) - tc.mockSvc(lcc, dfs, cmd, ecc) - dm := NewUserDataDiskManager(lcc, ecc, dfs, finch, homeDir, tc.cfg, nil) + tc.mockSvc(ncc, dfs, cmd, ecc) + dm := NewUserDataDiskManager(ncc, ecc, dfs, finch, homeDir, tc.cfg, nil) err := dm.EnsureUserDataDisk() assert.Equal(t, tc.wantErr, err) }) diff --git a/pkg/lima/lima.go b/pkg/lima/lima.go index c539ebfc1..f0cf25e67 100644 --- a/pkg/lima/lima.go +++ b/pkg/lima/lima.go @@ -36,7 +36,7 @@ const ( ) // GetVMStatus returns the Lima VM status. -func GetVMStatus(creator command.LimaCmdCreator, logger flog.Logger, instanceName string) (VMStatus, error) { +func GetVMStatus(creator command.NerdctlCmdCreator, logger flog.Logger, instanceName string) (VMStatus, error) { args := []string{"ls", "-f", "{{.Status}}", instanceName} cmd := creator.CreateWithoutStdio(args...) out, err := cmd.Output() @@ -48,7 +48,7 @@ func GetVMStatus(creator command.LimaCmdCreator, logger flog.Logger, instanceNam } // GetVMType returns the Lima VMType for a running instance. -func GetVMType(creator command.LimaCmdCreator, logger flog.Logger, instanceName string) (VMType, error) { +func GetVMType(creator command.NerdctlCmdCreator, logger flog.Logger, instanceName string) (VMType, error) { args := []string{"ls", "-f", "{{.VMType}}", instanceName} cmd := creator.CreateWithoutStdio(args...) out, err := cmd.Output() diff --git a/pkg/mocks/command_lima_cmd_creator.go b/pkg/mocks/command_nerdctl_cmd_creator.go similarity index 55% rename from pkg/mocks/command_lima_cmd_creator.go rename to pkg/mocks/command_nerdctl_cmd_creator.go index 03862f25a..10cf79e22 100644 --- a/pkg/mocks/command_lima_cmd_creator.go +++ b/pkg/mocks/command_nerdctl_cmd_creator.go @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/runfinch/finch/pkg/command (interfaces: LimaCmdCreator) +// Source: github.com/runfinch/finch/pkg/command (interfaces: NerdctlCmdCreator) // Package mocks is a generated GoMock package. package mocks @@ -14,31 +14,31 @@ import ( command "github.com/runfinch/finch/pkg/command" ) -// LimaCmdCreator is a mock of LimaCmdCreator interface. -type LimaCmdCreator struct { +// NerdctlCmdCreator is a mock of NerdctlCmdCreator interface. +type NerdctlCmdCreator struct { ctrl *gomock.Controller - recorder *LimaCmdCreatorMockRecorder + recorder *NerdctlCmdCreatorMockRecorder } -// LimaCmdCreatorMockRecorder is the mock recorder for LimaCmdCreator. -type LimaCmdCreatorMockRecorder struct { - mock *LimaCmdCreator +// NerdctlCmdCreatorMockRecorder is the mock recorder for NerdctlCmdCreator. +type NerdctlCmdCreatorMockRecorder struct { + mock *NerdctlCmdCreator } -// NewLimaCmdCreator creates a new mock instance. -func NewLimaCmdCreator(ctrl *gomock.Controller) *LimaCmdCreator { - mock := &LimaCmdCreator{ctrl: ctrl} - mock.recorder = &LimaCmdCreatorMockRecorder{mock} +// NewNerdctlCmdCreator creates a new mock instance. +func NewNerdctlCmdCreator(ctrl *gomock.Controller) *NerdctlCmdCreator { + mock := &NerdctlCmdCreator{ctrl: ctrl} + mock.recorder = &NerdctlCmdCreatorMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *LimaCmdCreator) EXPECT() *LimaCmdCreatorMockRecorder { +func (m *NerdctlCmdCreator) EXPECT() *NerdctlCmdCreatorMockRecorder { return m.recorder } // Create mocks base method. -func (m *LimaCmdCreator) Create(arg0 ...string) command.Command { +func (m *NerdctlCmdCreator) Create(arg0 ...string) command.Command { m.ctrl.T.Helper() varargs := []interface{}{} for _, a := range arg0 { @@ -50,13 +50,13 @@ func (m *LimaCmdCreator) Create(arg0 ...string) command.Command { } // Create indicates an expected call of Create. -func (mr *LimaCmdCreatorMockRecorder) Create(arg0 ...interface{}) *gomock.Call { +func (mr *NerdctlCmdCreatorMockRecorder) Create(arg0 ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*LimaCmdCreator)(nil).Create), arg0...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*NerdctlCmdCreator)(nil).Create), arg0...) } // CreateWithoutStdio mocks base method. -func (m *LimaCmdCreator) CreateWithoutStdio(arg0 ...string) command.Command { +func (m *NerdctlCmdCreator) CreateWithoutStdio(arg0 ...string) command.Command { m.ctrl.T.Helper() varargs := []interface{}{} for _, a := range arg0 { @@ -68,13 +68,13 @@ func (m *LimaCmdCreator) CreateWithoutStdio(arg0 ...string) command.Command { } // CreateWithoutStdio indicates an expected call of CreateWithoutStdio. -func (mr *LimaCmdCreatorMockRecorder) CreateWithoutStdio(arg0 ...interface{}) *gomock.Call { +func (mr *NerdctlCmdCreatorMockRecorder) CreateWithoutStdio(arg0 ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateWithoutStdio", reflect.TypeOf((*LimaCmdCreator)(nil).CreateWithoutStdio), arg0...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateWithoutStdio", reflect.TypeOf((*NerdctlCmdCreator)(nil).CreateWithoutStdio), arg0...) } // RunWithReplacingStdout mocks base method. -func (m *LimaCmdCreator) RunWithReplacingStdout(arg0 []command.Replacement, arg1 ...string) error { +func (m *NerdctlCmdCreator) RunWithReplacingStdout(arg0 []command.Replacement, arg1 ...string) error { m.ctrl.T.Helper() varargs := []interface{}{arg0} for _, a := range arg1 { @@ -86,8 +86,8 @@ func (m *LimaCmdCreator) RunWithReplacingStdout(arg0 []command.Replacement, arg1 } // RunWithReplacingStdout indicates an expected call of RunWithReplacingStdout. -func (mr *LimaCmdCreatorMockRecorder) RunWithReplacingStdout(arg0 interface{}, arg1 ...interface{}) *gomock.Call { +func (mr *NerdctlCmdCreatorMockRecorder) RunWithReplacingStdout(arg0 interface{}, arg1 ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{arg0}, arg1...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RunWithReplacingStdout", reflect.TypeOf((*LimaCmdCreator)(nil).RunWithReplacingStdout), varargs...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RunWithReplacingStdout", reflect.TypeOf((*NerdctlCmdCreator)(nil).RunWithReplacingStdout), varargs...) } diff --git a/pkg/mocks/lima_cmd_creator_system_deps.go b/pkg/mocks/lima_cmd_creator_system_deps.go deleted file mode 100644 index 89db0b03a..000000000 --- a/pkg/mocks/lima_cmd_creator_system_deps.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/runfinch/finch/pkg/command (interfaces: LimaCmdCreatorSystemDeps) - -// Package mocks is a generated GoMock package. -package mocks - -import ( - os "os" - reflect "reflect" - - gomock "github.com/golang/mock/gomock" -) - -// LimaCmdCreatorSystemDeps is a mock of LimaCmdCreatorSystemDeps interface. -type LimaCmdCreatorSystemDeps struct { - ctrl *gomock.Controller - recorder *LimaCmdCreatorSystemDepsMockRecorder -} - -// LimaCmdCreatorSystemDepsMockRecorder is the mock recorder for LimaCmdCreatorSystemDeps. -type LimaCmdCreatorSystemDepsMockRecorder struct { - mock *LimaCmdCreatorSystemDeps -} - -// NewLimaCmdCreatorSystemDeps creates a new mock instance. -func NewLimaCmdCreatorSystemDeps(ctrl *gomock.Controller) *LimaCmdCreatorSystemDeps { - mock := &LimaCmdCreatorSystemDeps{ctrl: ctrl} - mock.recorder = &LimaCmdCreatorSystemDepsMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *LimaCmdCreatorSystemDeps) EXPECT() *LimaCmdCreatorSystemDepsMockRecorder { - return m.recorder -} - -// Env mocks base method. -func (m *LimaCmdCreatorSystemDeps) Env(arg0 string) string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Env", arg0) - ret0, _ := ret[0].(string) - return ret0 -} - -// Env indicates an expected call of Env. -func (mr *LimaCmdCreatorSystemDepsMockRecorder) Env(arg0 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Env", reflect.TypeOf((*LimaCmdCreatorSystemDeps)(nil).Env), arg0) -} - -// Environ mocks base method. -func (m *LimaCmdCreatorSystemDeps) Environ() []string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Environ") - ret0, _ := ret[0].([]string) - return ret0 -} - -// Environ indicates an expected call of Environ. -func (mr *LimaCmdCreatorSystemDepsMockRecorder) Environ() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Environ", reflect.TypeOf((*LimaCmdCreatorSystemDeps)(nil).Environ)) -} - -// Stderr mocks base method. -func (m *LimaCmdCreatorSystemDeps) Stderr() *os.File { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Stderr") - ret0, _ := ret[0].(*os.File) - return ret0 -} - -// Stderr indicates an expected call of Stderr. -func (mr *LimaCmdCreatorSystemDepsMockRecorder) Stderr() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stderr", reflect.TypeOf((*LimaCmdCreatorSystemDeps)(nil).Stderr)) -} - -// Stdin mocks base method. -func (m *LimaCmdCreatorSystemDeps) Stdin() *os.File { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Stdin") - ret0, _ := ret[0].(*os.File) - return ret0 -} - -// Stdin indicates an expected call of Stdin. -func (mr *LimaCmdCreatorSystemDepsMockRecorder) Stdin() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stdin", reflect.TypeOf((*LimaCmdCreatorSystemDeps)(nil).Stdin)) -} - -// Stdout mocks base method. -func (m *LimaCmdCreatorSystemDeps) Stdout() *os.File { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Stdout") - ret0, _ := ret[0].(*os.File) - return ret0 -} - -// Stdout indicates an expected call of Stdout. -func (mr *LimaCmdCreatorSystemDepsMockRecorder) Stdout() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stdout", reflect.TypeOf((*LimaCmdCreatorSystemDeps)(nil).Stdout)) -} diff --git a/pkg/mocks/nerdctl_cmd_creator_system_deps.go b/pkg/mocks/nerdctl_cmd_creator_system_deps.go new file mode 100644 index 000000000..d5610fe21 --- /dev/null +++ b/pkg/mocks/nerdctl_cmd_creator_system_deps.go @@ -0,0 +1,108 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/runfinch/finch/pkg/command (interfaces: NerdctlCmdCreatorSystemDeps) + +// Package mocks is a generated GoMock package. +package mocks + +import ( + os "os" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" +) + +// NerdctlCmdCreatorSystemDeps is a mock of NerdctlCmdCreatorSystemDeps interface. +type NerdctlCmdCreatorSystemDeps struct { + ctrl *gomock.Controller + recorder *NerdctlCmdCreatorSystemDepsMockRecorder +} + +// NerdctlCmdCreatorSystemDepsMockRecorder is the mock recorder for NerdctlCmdCreatorSystemDeps. +type NerdctlCmdCreatorSystemDepsMockRecorder struct { + mock *NerdctlCmdCreatorSystemDeps +} + +// NewNerdctlCmdCreatorSystemDeps creates a new mock instance. +func NewNerdctlCmdCreatorSystemDeps(ctrl *gomock.Controller) *NerdctlCmdCreatorSystemDeps { + mock := &NerdctlCmdCreatorSystemDeps{ctrl: ctrl} + mock.recorder = &NerdctlCmdCreatorSystemDepsMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *NerdctlCmdCreatorSystemDeps) EXPECT() *NerdctlCmdCreatorSystemDepsMockRecorder { + return m.recorder +} + +// Env mocks base method. +func (m *NerdctlCmdCreatorSystemDeps) Env(arg0 string) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Env", arg0) + ret0, _ := ret[0].(string) + return ret0 +} + +// Env indicates an expected call of Env. +func (mr *NerdctlCmdCreatorSystemDepsMockRecorder) Env(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Env", reflect.TypeOf((*NerdctlCmdCreatorSystemDeps)(nil).Env), arg0) +} + +// Environ mocks base method. +func (m *NerdctlCmdCreatorSystemDeps) Environ() []string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Environ") + ret0, _ := ret[0].([]string) + return ret0 +} + +// Environ indicates an expected call of Environ. +func (mr *NerdctlCmdCreatorSystemDepsMockRecorder) Environ() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Environ", reflect.TypeOf((*NerdctlCmdCreatorSystemDeps)(nil).Environ)) +} + +// Stderr mocks base method. +func (m *NerdctlCmdCreatorSystemDeps) Stderr() *os.File { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Stderr") + ret0, _ := ret[0].(*os.File) + return ret0 +} + +// Stderr indicates an expected call of Stderr. +func (mr *NerdctlCmdCreatorSystemDepsMockRecorder) Stderr() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stderr", reflect.TypeOf((*NerdctlCmdCreatorSystemDeps)(nil).Stderr)) +} + +// Stdin mocks base method. +func (m *NerdctlCmdCreatorSystemDeps) Stdin() *os.File { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Stdin") + ret0, _ := ret[0].(*os.File) + return ret0 +} + +// Stdin indicates an expected call of Stdin. +func (mr *NerdctlCmdCreatorSystemDepsMockRecorder) Stdin() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stdin", reflect.TypeOf((*NerdctlCmdCreatorSystemDeps)(nil).Stdin)) +} + +// Stdout mocks base method. +func (m *NerdctlCmdCreatorSystemDeps) Stdout() *os.File { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Stdout") + ret0, _ := ret[0].(*os.File) + return ret0 +} + +// Stdout indicates an expected call of Stdout. +func (mr *NerdctlCmdCreatorSystemDepsMockRecorder) Stdout() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stdout", reflect.TypeOf((*NerdctlCmdCreatorSystemDeps)(nil).Stdout)) +} diff --git a/pkg/mocks/pkg_support_config.go b/pkg/mocks/pkg_support_config.go deleted file mode 100644 index f828d6135..000000000 --- a/pkg/mocks/pkg_support_config.go +++ /dev/null @@ -1,62 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/support/config.go - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" -) - -// BundleConfig is a mock of BundleConfig interface. -type BundleConfig struct { - ctrl *gomock.Controller - recorder *BundleConfigMockRecorder -} - -// BundleConfigMockRecorder is the mock recorder for BundleConfig. -type BundleConfigMockRecorder struct { - mock *BundleConfig -} - -// NewBundleConfig creates a new mock instance. -func NewBundleConfig(ctrl *gomock.Controller) *BundleConfig { - mock := &BundleConfig{ctrl: ctrl} - mock.recorder = &BundleConfigMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *BundleConfig) EXPECT() *BundleConfigMockRecorder { - return m.recorder -} - -// ConfigFiles mocks base method. -func (m *BundleConfig) ConfigFiles() []string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ConfigFiles") - ret0, _ := ret[0].([]string) - return ret0 -} - -// ConfigFiles indicates an expected call of ConfigFiles. -func (mr *BundleConfigMockRecorder) ConfigFiles() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigFiles", reflect.TypeOf((*BundleConfig)(nil).ConfigFiles)) -} - -// LogFiles mocks base method. -func (m *BundleConfig) LogFiles() []string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "LogFiles") - ret0, _ := ret[0].([]string) - return ret0 -} - -// LogFiles indicates an expected call of LogFiles. -func (mr *BundleConfigMockRecorder) LogFiles() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LogFiles", reflect.TypeOf((*BundleConfig)(nil).LogFiles)) -} diff --git a/pkg/mocks/pkg_support_support.go b/pkg/mocks/pkg_support_support.go deleted file mode 100644 index cb33f540f..000000000 --- a/pkg/mocks/pkg_support_support.go +++ /dev/null @@ -1,49 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/support/support.go - -// Package mocks is a generated GoMock package. -package mocks - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" -) - -// BundleBuilder is a mock of BundleBuilder interface. -type BundleBuilder struct { - ctrl *gomock.Controller - recorder *BundleBuilderMockRecorder -} - -// BundleBuilderMockRecorder is the mock recorder for BundleBuilder. -type BundleBuilderMockRecorder struct { - mock *BundleBuilder -} - -// NewBundleBuilder creates a new mock instance. -func NewBundleBuilder(ctrl *gomock.Controller) *BundleBuilder { - mock := &BundleBuilder{ctrl: ctrl} - mock.recorder = &BundleBuilderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *BundleBuilder) EXPECT() *BundleBuilderMockRecorder { - return m.recorder -} - -// GenerateSupportBundle mocks base method. -func (m *BundleBuilder) GenerateSupportBundle(arg0, arg1 []string) (string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GenerateSupportBundle", arg0, arg1) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GenerateSupportBundle indicates an expected call of GenerateSupportBundle. -func (mr *BundleBuilderMockRecorder) GenerateSupportBundle(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenerateSupportBundle", reflect.TypeOf((*BundleBuilder)(nil).GenerateSupportBundle), arg0, arg1) -} diff --git a/pkg/support/support.go b/pkg/support/support.go index 1a09d4ab9..0db06c830 100644 --- a/pkg/support/support.go +++ b/pkg/support/support.go @@ -53,7 +53,7 @@ type bundleBuilder struct { config BundleConfig finch fpath.Finch ecc command.Creator - lcc command.LimaCmdCreator + ncc command.NerdctlCmdCreator lima wrapper.LimaWrapper } @@ -64,7 +64,7 @@ func NewBundleBuilder( config BundleConfig, finch fpath.Finch, ecc command.Creator, - lcc command.LimaCmdCreator, + ncc command.NerdctlCmdCreator, lima wrapper.LimaWrapper, ) BundleBuilder { return &bundleBuilder{ @@ -73,7 +73,7 @@ func NewBundleBuilder( config: config, finch: finch, ecc: ecc, - lcc: lcc, + ncc: ncc, lima: lima, } } @@ -228,7 +228,7 @@ func (bb *bundleBuilder) streamFileFromVM(writer *zip.Writer, filename, prefix s errBuf := new(bytes.Buffer) _, filePathInVM, _ := strings.Cut(filename, ":") - cmd := bb.lcc.CreateWithoutStdio("shell", "finch", "sudo", "cat", filePathInVM) + cmd := bb.ncc.CreateWithoutStdio("shell", "finch", "sudo", "cat", filePathInVM) cmd.SetStdout(pipeWriter) cmd.SetStderr(errBuf) diff --git a/pkg/support/support_test.go b/pkg/support/support_test.go index d93365d43..c7f04de15 100644 --- a/pkg/support/support_test.go +++ b/pkg/support/support_test.go @@ -25,14 +25,14 @@ func TestSupport_NewBundleBuilder(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) logger := mocks.NewLogger(ctrl) fs := afero.NewMemMapFs() finch := fpath.Finch("mockfinch") lima := mocks.NewMockLimaWrapper(ctrl) config := NewBundleConfig(finch, "mockhome") - NewBundleBuilder(logger, fs, config, finch, ecc, lcc, lima) + NewBundleBuilder(logger, fs, config, finch, ecc, ncc, lima) } func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { @@ -278,7 +278,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { logger *mocks.Logger, config *mocks.BundleConfig, ecc *mocks.CommandCreator, - lcc *mocks.LimaCmdCreator, + ncc *mocks.LimaCmdCreator, cmd *mocks.Command, lima *mocks.MockLimaWrapper, _ afero.Fs, @@ -312,7 +312,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { var catWriter io.Writer waitChan := make(chan int) - lcc.EXPECT().CreateWithoutStdio("shell", "finch", "sudo", "cat", "extra1").Return(cmd) + ncc.EXPECT().CreateWithoutStdio("shell", "finch", "sudo", "cat", "extra1").Return(cmd) cmd.EXPECT().SetStdout(gomock.Any()).Do(func(writer io.Writer) { catWriter = writer }) @@ -347,7 +347,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { config := mocks.NewBundleConfig(ctrl) finch := fpath.Finch("mockfinch") ecc := mocks.NewCommandCreator(ctrl) - lcc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewLimaCmdCreator(ctrl) lima := mocks.NewMockLimaWrapper(ctrl) cmd := mocks.NewCommand(ctrl) @@ -357,7 +357,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { config: config, finch: finch, ecc: ecc, - lcc: lcc, + ncc: ncc, lima: lima, } @@ -378,7 +378,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { require.NoError(t, err) } - tc.mockSvc(logger, config, ecc, lcc, cmd, lima, fs) + tc.mockSvc(logger, config, ecc, ncc, cmd, lima, fs) zipFile, err := builder.GenerateSupportBundle(tc.include, tc.exclude) assert.NoError(t, err) From 01b5b734fc6098874effe3a02172d42c2c97bb29 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Wed, 10 Jul 2024 15:14:16 -0400 Subject: [PATCH 04/37] fix some refactoring/renaming misses Signed-off-by: Justin Alvarez --- cmd/finch/nerdctl_darwin_test.go | 60 ++++++------- cmd/finch/nerdctl_shared_test.go | 16 ++-- cmd/finch/nerdctl_windows_test.go | 84 +++++++++---------- cmd/finch/version_test.go | 30 +++---- cmd/finch/virtual_machine_init_test.go | 26 +++--- cmd/finch/virtual_machine_remove_test.go | 26 +++--- cmd/finch/virtual_machine_start_test.go | 26 +++--- cmd/finch/virtual_machine_status_test.go | 20 ++--- cmd/finch/virtual_machine_stop_test.go | 26 +++--- cmd/finch/virtual_machine_test.go | 18 ++-- pkg/command/nerdctl_test.go | 26 +++--- pkg/config/config.go | 4 +- .../vmnet/sudoers_file_unix_test.go | 24 +++--- pkg/disk/disk_darwin_test.go | 18 ++-- pkg/lima/lima_test.go | 30 +++---- pkg/mocks/pkg_support_config.go | 65 ++++++++++++++ pkg/support/config.go | 4 + pkg/support/support_test.go | 18 ++-- 18 files changed, 295 insertions(+), 226 deletions(-) create mode 100644 pkg/mocks/pkg_support_config.go diff --git a/cmd/finch/nerdctl_darwin_test.go b/cmd/finch/nerdctl_darwin_test.go index 12c8e911c..409d341eb 100644 --- a/cmd/finch/nerdctl_darwin_test.go +++ b/cmd/finch/nerdctl_darwin_test.go @@ -31,7 +31,7 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { name string cmd *cobra.Command args []string - mockSvc func(*mocks.LimaCmdCreator, *mocks.Logger, *gomock.Controller, *mocks.NerdctlCommandSystemDeps) + mockSvc func(*mocks.NerdctlCmdCreator, *mocks.Logger, *gomock.Controller, *mocks.NerdctlCommandSystemDeps) }{ { name: "happy path", @@ -39,7 +39,7 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { Use: "info", }, args: []string{}, - mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps) { getVMStatusC := mocks.NewCommand(ctrl) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -61,7 +61,7 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) ecc := mocks.NewCommandCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) @@ -83,7 +83,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr error mockSvc func( t *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, ecc *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -99,7 +99,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -127,7 +127,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -156,7 +156,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -188,7 +188,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -219,7 +219,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -251,7 +251,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( t *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -286,7 +286,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( t *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -322,7 +322,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( t *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -356,7 +356,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: &os.PathError{Op: "open", Path: envFilePath, Err: afero.ErrFileNotFound}, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, _ *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -377,7 +377,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -407,7 +407,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -436,7 +436,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: errors.New("run cmd error"), mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -465,7 +465,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -495,7 +495,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -528,7 +528,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -561,7 +561,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -591,7 +591,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -618,7 +618,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: fmt.Errorf("failed to replace"), mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -646,7 +646,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -675,7 +675,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -704,7 +704,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -737,7 +737,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, ecc *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -798,7 +798,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, ecc *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -856,7 +856,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, ecc *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -910,7 +910,7 @@ func TestNerdctlCommand_run(t *testing.T) { wantErr: nil, mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, ecc *mocks.CommandCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -961,7 +961,7 @@ func TestNerdctlCommand_run(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) ecc := mocks.NewCommandCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) diff --git a/cmd/finch/nerdctl_shared_test.go b/cmd/finch/nerdctl_shared_test.go index 5d11e8a81..c688dc64a 100644 --- a/cmd/finch/nerdctl_shared_test.go +++ b/cmd/finch/nerdctl_shared_test.go @@ -38,7 +38,7 @@ func TestNerdctlCommand_shouldReplaceForHelp(t *testing.T) { name string cmdName string args []string - mockSvc func(*mocks.LimaCmdCreator, *mocks.Logger, *gomock.Controller) + mockSvc func(*mocks.NerdctlCmdCreator, *mocks.Logger, *gomock.Controller) }{ { name: "with --help flag", @@ -86,7 +86,7 @@ func TestNerdctlCommand_shouldReplaceForHelp(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) ecc := mocks.NewCommandCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) @@ -104,7 +104,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { fc *config.Finch args []string wantErr error - mockSvc func(*testing.T, *mocks.LimaCmdCreator, *mocks.CommandCreator, *mocks.NerdctlCommandSystemDeps, *mocks.Logger, + mockSvc func(*testing.T, *mocks.NerdctlCmdCreator, *mocks.CommandCreator, *mocks.NerdctlCommandSystemDeps, *mocks.Logger, *gomock.Controller, afero.Fs) }{ { @@ -116,7 +116,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { limaInstanceName, virtualMachineRootCmd), mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, _ *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -139,7 +139,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { limaInstanceName, virtualMachineRootCmd), mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, _ *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -160,7 +160,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { wantErr: errors.New("unrecognized system status"), mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, _ *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -181,7 +181,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { wantErr: errors.New("get status error"), mockSvc: func( _ *testing.T, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.CommandCreator, _ *mocks.NerdctlCommandSystemDeps, _ *mocks.Logger, @@ -201,7 +201,7 @@ func TestNerdctlCommand_withVMErrors(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) fs := afero.NewMemMapFs() diff --git a/cmd/finch/nerdctl_windows_test.go b/cmd/finch/nerdctl_windows_test.go index 39c309024..c978030e3 100644 --- a/cmd/finch/nerdctl_windows_test.go +++ b/cmd/finch/nerdctl_windows_test.go @@ -36,7 +36,7 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { name string cmd *cobra.Command args []string - mockSvc func(*mocks.CommandCreator, *mocks.LimaCmdCreator, *mocks.Logger, *gomock.Controller, *mocks.NerdctlCommandSystemDeps) + mockSvc func(*mocks.CommandCreator, *mocks.NerdctlCmdCreator, *mocks.Logger, *gomock.Controller, *mocks.NerdctlCommandSystemDeps) }{ { name: "happy path", @@ -44,7 +44,7 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { Use: "info", }, args: []string{}, - mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) @@ -73,7 +73,7 @@ func TestNerdctlCommand_runAdaptor(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) tc.mockSvc(ecc, ncc, logger, ctrl, ncsd) @@ -92,7 +92,7 @@ func TestNerdctlCommand_run(t *testing.T) { fc *config.Finch args []string wantErr error - mockSvc func(*testing.T, *mocks.CommandCreator, *mocks.LimaCmdCreator, *mocks.Command, *mocks.NerdctlCommandSystemDeps, + mockSvc func(*testing.T, *mocks.CommandCreator, *mocks.NerdctlCmdCreator, *mocks.Command, *mocks.NerdctlCommandSystemDeps, *mocks.Logger, *gomock.Controller, afero.Fs) }{ { @@ -104,7 +104,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -143,7 +143,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -178,7 +178,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -215,7 +215,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -252,7 +252,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -290,7 +290,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( t *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -329,7 +329,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( t *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -369,7 +369,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( t *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -408,7 +408,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, _ *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -430,7 +430,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, ecc *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, cmd *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -468,7 +468,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -502,7 +502,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -536,7 +536,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, ecc *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, cmd *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -573,7 +573,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -610,7 +610,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -645,7 +645,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -678,7 +678,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -711,7 +711,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -745,7 +745,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -779,7 +779,7 @@ func TestNerdctlCommand_run(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Command, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, @@ -813,7 +813,7 @@ func TestNerdctlCommand_run(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) cmd := mocks.NewCommand(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) @@ -851,7 +851,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { cmdName string args []string wantErr error - mockSvc func(*testing.T, *mocks.CommandCreator, *mocks.LimaCmdCreator, *mocks.NerdctlCommandSystemDeps, + mockSvc func(*testing.T, *mocks.CommandCreator, *mocks.NerdctlCmdCreator, *mocks.NerdctlCommandSystemDeps, *mocks.Logger, *gomock.Controller, afero.Fs) }{ { @@ -862,7 +862,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, ctrl *gomock.Controller, @@ -897,7 +897,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, ctrl *gomock.Controller, @@ -932,7 +932,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, ctrl *gomock.Controller, @@ -967,7 +967,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, ctrl *gomock.Controller, @@ -1002,7 +1002,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { mockSvc: func( _ *testing.T, _ *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, ncsd *mocks.NerdctlCommandSystemDeps, logger *mocks.Logger, ctrl *gomock.Controller, @@ -1036,7 +1036,7 @@ func TestNerdctlCommand_Run_withBindMounts(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) fs := afero.NewMemMapFs() @@ -1057,13 +1057,13 @@ func TestNerdctlCommand_run_CpCommand(t *testing.T) { name string cmdName string args []string - mockSvc func(*mocks.CommandCreator, *mocks.LimaCmdCreator, *mocks.Logger, *gomock.Controller, *mocks.NerdctlCommandSystemDeps) + mockSvc func(*mocks.CommandCreator, *mocks.NerdctlCmdCreator, *mocks.Logger, *gomock.Controller, *mocks.NerdctlCommandSystemDeps) }{ { name: "copy into container", cmdName: "cp", args: []string{"C:\\workdir\\test", "somecontainer:/tmp"}, - mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) @@ -1092,7 +1092,7 @@ func TestNerdctlCommand_run_CpCommand(t *testing.T) { name: "copy out of container", cmdName: "cp", args: []string{"somecontainer:/tmp/test", "C:\\workdir\\test"}, - mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) @@ -1121,7 +1121,7 @@ func TestNerdctlCommand_run_CpCommand(t *testing.T) { name: "copy with options", cmdName: "cp", args: []string{"-L", "somecontainer:/tmp/test", "C:\\workdir\\test"}, - mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) @@ -1155,7 +1155,7 @@ func TestNerdctlCommand_run_CpCommand(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) tc.mockSvc(ecc, ncc, logger, ctrl, ncsd) @@ -1178,13 +1178,13 @@ func TestNerdctlCommand_run_BuildCommand(t *testing.T) { name string cmdName string args []string - mockSvc func(*mocks.CommandCreator, *mocks.LimaCmdCreator, *mocks.Logger, *gomock.Controller, *mocks.NerdctlCommandSystemDeps) + mockSvc func(*mocks.CommandCreator, *mocks.NerdctlCmdCreator, *mocks.Logger, *gomock.Controller, *mocks.NerdctlCommandSystemDeps) }{ { name: "build without options", cmdName: "build", args: []string{"C:\\workdir\\buildcontext"}, - mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) @@ -1213,7 +1213,7 @@ func TestNerdctlCommand_run_BuildCommand(t *testing.T) { name: "build with file option", cmdName: "build", args: []string{"-f", "C:\\workdir\\buildcontext", "C:\\workdir\\buildcontext"}, - mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) @@ -1242,7 +1242,7 @@ func TestNerdctlCommand_run_BuildCommand(t *testing.T) { name: "build with secret option", cmdName: "build", args: []string{"--secret", "src=C:\\workdir\\secret", "C:\\workdir\\buildcontext"}, - mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.LimaCmdCreator, logger *mocks.Logger, + mockSvc: func(_ *mocks.CommandCreator, ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller, ncsd *mocks.NerdctlCommandSystemDeps, ) { getVMStatusC := mocks.NewCommand(ctrl) @@ -1281,7 +1281,7 @@ func TestNerdctlCommand_run_BuildCommand(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) ncsd := mocks.NewNerdctlCommandSystemDeps(ctrl) logger := mocks.NewLogger(ctrl) tc.mockSvc(ecc, ncc, logger, ctrl, ncsd) diff --git a/cmd/finch/version_test.go b/cmd/finch/version_test.go index e210f0170..6176aa2aa 100644 --- a/cmd/finch/version_test.go +++ b/cmd/finch/version_test.go @@ -63,7 +63,7 @@ func TestNewVersionCommand(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) var stdOut bytes.Buffer cmd := newVersionCommand(ncc, logger, &stdOut) assert.Equal(t, cmd.Name(), "version") @@ -76,7 +76,7 @@ func TestVersionAction_runAdaptor(t *testing.T) { name string cmd func(t *testing.T) *cobra.Command args []string - mockSvc func(*mocks.LimaCmdCreator, *mocks.Logger, *gomock.Controller) + mockSvc func(*mocks.NerdctlCmdCreator, *mocks.Logger, *gomock.Controller) }{ { name: "happy path", @@ -89,7 +89,7 @@ func TestVersionAction_runAdaptor(t *testing.T) { return c }, args: []string{}, - mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -113,7 +113,7 @@ func TestVersionAction_runAdaptor(t *testing.T) { return c }, args: []string{"--format", "json"}, - mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -135,7 +135,7 @@ func TestVersionAction_runAdaptor(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) var stdOut bytes.Buffer tc.mockSvc(ncc, logger, ctrl) @@ -151,7 +151,7 @@ func TestVersionAction_run(t *testing.T) { name string wantErr error cmd func(t *testing.T) *cobra.Command - mockSvc func(*mocks.LimaCmdCreator, *mocks.Logger, *gomock.Controller) + mockSvc func(*mocks.NerdctlCmdCreator, *mocks.Logger, *gomock.Controller) postRunCheck func(t *testing.T, stdout []byte) format string }{ @@ -166,7 +166,7 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -214,7 +214,7 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) @@ -239,7 +239,7 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(ncc *mocks.LimaCmdCreator, _ *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, _ *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), errors.New("get status error")) @@ -260,7 +260,7 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -288,7 +288,7 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -316,7 +316,7 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -344,7 +344,7 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -371,7 +371,7 @@ func TestVersionAction_run(t *testing.T) { return c }, - mockSvc: func(ncc *mocks.LimaCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -397,7 +397,7 @@ func TestVersionAction_run(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) tc.mockSvc(ncc, logger, ctrl) var stdOut bytes.Buffer diff --git a/cmd/finch/virtual_machine_init_test.go b/cmd/finch/virtual_machine_init_test.go index eb3331fb4..83e9e0f1d 100644 --- a/cmd/finch/virtual_machine_init_test.go +++ b/cmd/finch/virtual_machine_init_test.go @@ -37,7 +37,7 @@ func TestInitVMAction_runAdapter(t *testing.T) { args []string groups func(*gomock.Controller) []*dependency.Group mockSvc func( - *mocks.LimaCmdCreator, + *mocks.NerdctlCmdCreator, *mocks.Logger, *mocks.LimaConfigApplier, *mocks.UserDataDiskManager, @@ -62,7 +62,7 @@ func TestInitVMAction_runAdapter(t *testing.T) { return groups }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, @@ -95,7 +95,7 @@ func TestInitVMAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) dm := mocks.NewUserDataDiskManager(ctrl) @@ -115,7 +115,7 @@ func TestInitVMAction_run(t *testing.T) { wantErr error groups func(*gomock.Controller) []*dependency.Group mockSvc func( - *mocks.LimaCmdCreator, + *mocks.NerdctlCmdCreator, *mocks.Logger, *mocks.LimaConfigApplier, *mocks.UserDataDiskManager, @@ -129,7 +129,7 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, @@ -161,7 +161,7 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, @@ -182,7 +182,7 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, @@ -201,7 +201,7 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, @@ -220,7 +220,7 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, @@ -248,7 +248,7 @@ func TestInitVMAction_run(t *testing.T) { return groups }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, @@ -288,7 +288,7 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, @@ -310,7 +310,7 @@ func TestInitVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, @@ -348,7 +348,7 @@ func TestInitVMAction_run(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) dm := mocks.NewUserDataDiskManager(ctrl) diff --git a/cmd/finch/virtual_machine_remove_test.go b/cmd/finch/virtual_machine_remove_test.go index a1d8138e5..6d63fa2fc 100644 --- a/cmd/finch/virtual_machine_remove_test.go +++ b/cmd/finch/virtual_machine_remove_test.go @@ -28,13 +28,13 @@ func TestRemoveVMAction_runAdapter(t *testing.T) { testCases := []struct { name string - mockSvc func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) + mockSvc func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) args []string }{ { name: "should remove the instance", args: []string{}, - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) @@ -51,7 +51,7 @@ func TestRemoveVMAction_runAdapter(t *testing.T) { args: []string{ "--force", }, - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) { command := mocks.NewCommand(ctrl) dm.EXPECT().DetachUserDataDisk().Return(nil) creator.EXPECT().CreateWithoutStdio("remove", "--force", limaInstanceName).Return(command) @@ -69,7 +69,7 @@ func TestRemoveVMAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) dm := mocks.NewUserDataDiskManager(ctrl) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) tc.mockSvc(logger, ncc, dm, ctrl) cmd := newRemoveVMCommand(ncc, dm, logger) @@ -85,13 +85,13 @@ func TestRemoveVMAction_run(t *testing.T) { testCases := []struct { name string wantErr error - mockSvc func(*mocks.Logger, *mocks.LimaCmdCreator, *mocks.UserDataDiskManager, *gomock.Controller) + mockSvc func(*mocks.Logger, *mocks.NerdctlCmdCreator, *mocks.UserDataDiskManager, *gomock.Controller) force bool }{ { name: "should remove the instance", wantErr: nil, - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) @@ -110,7 +110,7 @@ func TestRemoveVMAction_run(t *testing.T) { name: "running VM", wantErr: fmt.Errorf("the instance %q is running, run `finch %s stop` to stop the instance first", limaInstanceName, virtualMachineRootCmd), - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -121,7 +121,7 @@ func TestRemoveVMAction_run(t *testing.T) { { name: "nonexistent VM", wantErr: fmt.Errorf("the instance %q does not exist", limaInstanceName), - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte(""), nil) @@ -132,7 +132,7 @@ func TestRemoveVMAction_run(t *testing.T) { { name: "unknown VM status", wantErr: errors.New("unrecognized system status"), - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), nil) @@ -143,7 +143,7 @@ func TestRemoveVMAction_run(t *testing.T) { { name: "status command returns an error", wantErr: errors.New("get status error"), - mockSvc: func(_ *mocks.Logger, creator *mocks.LimaCmdCreator, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller) { + mockSvc: func(_ *mocks.Logger, creator *mocks.NerdctlCmdCreator, _ *mocks.UserDataDiskManager, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), errors.New("get status error")) @@ -153,7 +153,7 @@ func TestRemoveVMAction_run(t *testing.T) { { name: "should print error if virtual machine failed to remove", wantErr: errors.New("failed to remove instance"), - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) @@ -172,7 +172,7 @@ func TestRemoveVMAction_run(t *testing.T) { { name: "should forcibly remove the instance", wantErr: nil, - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, dm *mocks.UserDataDiskManager, ctrl *gomock.Controller) { command := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("remove", "--force", limaInstanceName).Return(command) command.EXPECT().CombinedOutput() @@ -192,7 +192,7 @@ func TestRemoveVMAction_run(t *testing.T) { ctrl := gomock.NewController(t) dm := mocks.NewUserDataDiskManager(ctrl) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) tc.mockSvc(logger, ncc, dm, ctrl) err := newRemoveVMAction(ncc, dm, logger).run(tc.force) diff --git a/cmd/finch/virtual_machine_start_test.go b/cmd/finch/virtual_machine_start_test.go index 7d8ff72f8..3bd957ab7 100644 --- a/cmd/finch/virtual_machine_start_test.go +++ b/cmd/finch/virtual_machine_start_test.go @@ -36,7 +36,7 @@ func TestStartVMAction_runAdapter(t *testing.T) { args []string groups func(*gomock.Controller) []*dependency.Group mockSvc func( - *mocks.LimaCmdCreator, + *mocks.NerdctlCmdCreator, *mocks.Logger, *mocks.LimaConfigApplier, *mocks.UserDataDiskManager, @@ -62,7 +62,7 @@ func TestStartVMAction_runAdapter(t *testing.T) { }, args: []string{}, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, @@ -94,7 +94,7 @@ func TestStartVMAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) dm := mocks.NewUserDataDiskManager(ctrl) @@ -115,7 +115,7 @@ func TestStartVMAction_run(t *testing.T) { wantErr error groups func(*gomock.Controller) []*dependency.Group mockSvc func( - *mocks.LimaCmdCreator, + *mocks.NerdctlCmdCreator, *mocks.Logger, *mocks.LimaConfigApplier, *mocks.UserDataDiskManager, @@ -137,7 +137,7 @@ func TestStartVMAction_run(t *testing.T) { return groups }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, @@ -167,7 +167,7 @@ func TestStartVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, @@ -187,7 +187,7 @@ func TestStartVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, @@ -206,7 +206,7 @@ func TestStartVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, @@ -225,7 +225,7 @@ func TestStartVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Logger, _ *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, @@ -246,7 +246,7 @@ func TestStartVMAction_run(t *testing.T) { return nil }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, _ *mocks.UserDataDiskManager, @@ -277,7 +277,7 @@ func TestStartVMAction_run(t *testing.T) { return groups }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, @@ -319,7 +319,7 @@ func TestStartVMAction_run(t *testing.T) { return groups }, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, lca *mocks.LimaConfigApplier, dm *mocks.UserDataDiskManager, @@ -354,7 +354,7 @@ func TestStartVMAction_run(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) dm := mocks.NewUserDataDiskManager(ctrl) diff --git a/cmd/finch/virtual_machine_status_test.go b/cmd/finch/virtual_machine_status_test.go index 46f9c1f31..5c44de80e 100644 --- a/cmd/finch/virtual_machine_status_test.go +++ b/cmd/finch/virtual_machine_status_test.go @@ -32,7 +32,7 @@ func TestStatusVMAction_runAdapter(t *testing.T) { command *cobra.Command args []string mockSvc func( - *mocks.LimaCmdCreator, + *mocks.NerdctlCmdCreator, *mocks.Logger, *mocks.LimaConfigApplier, *gomock.Controller, @@ -45,7 +45,7 @@ func TestStatusVMAction_runAdapter(t *testing.T) { }, args: []string{}, mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, @@ -66,7 +66,7 @@ func TestStatusVMAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) stdout := bytes.Buffer{} - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) tc.mockSvc(ncc, logger, lca, ctrl) @@ -84,7 +84,7 @@ func TestStatusVMAction_run(t *testing.T) { wantErr error wantStatusOutput string mockSvc func( - *mocks.LimaCmdCreator, + *mocks.NerdctlCmdCreator, *mocks.Logger, *mocks.LimaConfigApplier, *gomock.Controller, @@ -95,7 +95,7 @@ func TestStatusVMAction_run(t *testing.T) { wantErr: nil, wantStatusOutput: "Running\n", mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, @@ -111,7 +111,7 @@ func TestStatusVMAction_run(t *testing.T) { wantErr: nil, wantStatusOutput: "Stopped\n", mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, @@ -127,7 +127,7 @@ func TestStatusVMAction_run(t *testing.T) { wantErr: nil, wantStatusOutput: "Nonexistent\n", mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, @@ -143,7 +143,7 @@ func TestStatusVMAction_run(t *testing.T) { wantErr: errors.New("unrecognized system status"), wantStatusOutput: "", mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, logger *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, @@ -159,7 +159,7 @@ func TestStatusVMAction_run(t *testing.T) { wantErr: errors.New("get status error"), wantStatusOutput: "", mockSvc: func( - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, _ *mocks.Logger, _ *mocks.LimaConfigApplier, ctrl *gomock.Controller, @@ -179,7 +179,7 @@ func TestStatusVMAction_run(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) stdout := bytes.Buffer{} - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) lca := mocks.NewLimaConfigApplier(ctrl) tc.mockSvc(ncc, logger, lca, ctrl) diff --git a/cmd/finch/virtual_machine_stop_test.go b/cmd/finch/virtual_machine_stop_test.go index 62671ce08..39c5bf690 100644 --- a/cmd/finch/virtual_machine_stop_test.go +++ b/cmd/finch/virtual_machine_stop_test.go @@ -28,14 +28,14 @@ func TestStopVMAction_runAdapter(t *testing.T) { testCases := []struct { name string - mockSvc func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) + mockSvc func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) args []string wantErr error }{ { name: "should stop the instance", args: []string{}, - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -55,7 +55,7 @@ func TestStopVMAction_runAdapter(t *testing.T) { args: []string{ "--force", }, - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) { command := mocks.NewCommand(ctrl) dm.EXPECT().DetachUserDataDisk().Return(nil) creator.EXPECT().CreateWithoutStdio("stop", "--force", limaInstanceName).Return(command) @@ -74,7 +74,7 @@ func TestStopVMAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) dm := mocks.NewUserDataDiskManager(ctrl) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) tc.mockSvc(logger, ncc, ctrl, dm) cmd := newStopVMCommand(ncc, dm, logger) @@ -91,13 +91,13 @@ func TestStopVMAction_run(t *testing.T) { testCases := []struct { name string wantErr error - mockSvc func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) + mockSvc func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) force bool }{ { name: "should stop the instance", wantErr: nil, - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -115,7 +115,7 @@ func TestStopVMAction_run(t *testing.T) { { name: "stopped VM", wantErr: fmt.Errorf("the instance %q is already stopped", limaInstanceName), - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, ctrl *gomock.Controller, _ *mocks.UserDataDiskManager) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, ctrl *gomock.Controller, _ *mocks.UserDataDiskManager) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Stopped"), nil) @@ -126,7 +126,7 @@ func TestStopVMAction_run(t *testing.T) { { name: "nonexistent VM", wantErr: fmt.Errorf("the instance %q does not exist", limaInstanceName), - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, ctrl *gomock.Controller, _ *mocks.UserDataDiskManager) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, ctrl *gomock.Controller, _ *mocks.UserDataDiskManager) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte(""), nil) @@ -137,7 +137,7 @@ func TestStopVMAction_run(t *testing.T) { { name: "unknown VM status", wantErr: errors.New("unrecognized system status"), - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, ctrl *gomock.Controller, _ *mocks.UserDataDiskManager) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, ctrl *gomock.Controller, _ *mocks.UserDataDiskManager) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), nil) @@ -148,7 +148,7 @@ func TestStopVMAction_run(t *testing.T) { { name: "status command returns an error", wantErr: errors.New("get status error"), - mockSvc: func(_ *mocks.Logger, creator *mocks.LimaCmdCreator, ctrl *gomock.Controller, _ *mocks.UserDataDiskManager) { + mockSvc: func(_ *mocks.Logger, creator *mocks.NerdctlCmdCreator, ctrl *gomock.Controller, _ *mocks.UserDataDiskManager) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Broken"), errors.New("get status error")) @@ -158,7 +158,7 @@ func TestStopVMAction_run(t *testing.T) { { name: "should print error if virtual machine failed to stop", wantErr: errors.New("error"), - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) { getVMStatusC := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("ls", "-f", "{{.Status}}", limaInstanceName).Return(getVMStatusC) getVMStatusC.EXPECT().Output().Return([]byte("Running"), nil) @@ -177,7 +177,7 @@ func TestStopVMAction_run(t *testing.T) { { name: "should force stop virtual machine", wantErr: nil, - mockSvc: func(logger *mocks.Logger, creator *mocks.LimaCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) { + mockSvc: func(logger *mocks.Logger, creator *mocks.NerdctlCmdCreator, ctrl *gomock.Controller, dm *mocks.UserDataDiskManager) { command := mocks.NewCommand(ctrl) creator.EXPECT().CreateWithoutStdio("stop", "--force", limaInstanceName).Return(command) command.EXPECT().CombinedOutput() @@ -197,7 +197,7 @@ func TestStopVMAction_run(t *testing.T) { ctrl := gomock.NewController(t) dm := mocks.NewUserDataDiskManager(ctrl) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) tc.mockSvc(logger, ncc, ctrl, dm) err := newStopVMAction(ncc, dm, logger).run(tc.force) diff --git a/cmd/finch/virtual_machine_test.go b/cmd/finch/virtual_machine_test.go index 58c00e5bb..2a2bc5ef7 100644 --- a/cmd/finch/virtual_machine_test.go +++ b/cmd/finch/virtual_machine_test.go @@ -31,14 +31,14 @@ func TestPostVMStartInitAction_runAdapter(t *testing.T) { testCases := []struct { name string - mockSvc func(*mocks.Logger, *mocks.LimaCmdCreator, *mocks.Command, *mocks.NerdctlConfigApplier) + mockSvc func(*mocks.Logger, *mocks.NerdctlCmdCreator, *mocks.Command, *mocks.NerdctlConfigApplier) cmd *cobra.Command args []string wantErr error }{ { name: "config files are applied after boot", - mockSvc: func(logger *mocks.Logger, ncc *mocks.LimaCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { + mockSvc: func(logger *mocks.Logger, ncc *mocks.NerdctlCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { logger.EXPECT().Debugln("Applying guest configuration options") command.EXPECT().Output().Return([]byte("80"), nil) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) @@ -59,7 +59,7 @@ func TestPostVMStartInitAction_runAdapter(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) command := mocks.NewCommand(ctrl) nca := mocks.NewNerdctlConfigApplier(ctrl) tc.mockSvc(logger, ncc, command, nca) @@ -75,12 +75,12 @@ func TestPostVMStartInitAction_run(t *testing.T) { testCases := []struct { name string - mockSvc func(*mocks.Logger, *mocks.LimaCmdCreator, *mocks.Command, *mocks.NerdctlConfigApplier) + mockSvc func(*mocks.Logger, *mocks.NerdctlCmdCreator, *mocks.Command, *mocks.NerdctlConfigApplier) wantErr error }{ { name: "config files are applied after boot", - mockSvc: func(logger *mocks.Logger, ncc *mocks.LimaCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { + mockSvc: func(logger *mocks.Logger, ncc *mocks.NerdctlCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { logger.EXPECT().Debugln("Applying guest configuration options") command.EXPECT().Output().Return([]byte("80"), nil) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) @@ -90,7 +90,7 @@ func TestPostVMStartInitAction_run(t *testing.T) { }, { name: "should return an error if sshPortCmd has an error output", - mockSvc: func(logger *mocks.Logger, ncc *mocks.LimaCmdCreator, command *mocks.Command, _ *mocks.NerdctlConfigApplier) { + mockSvc: func(logger *mocks.Logger, ncc *mocks.NerdctlCmdCreator, command *mocks.Command, _ *mocks.NerdctlConfigApplier) { logger.EXPECT().Debugln("Applying guest configuration options") command.EXPECT().Output().Return(nil, errors.New("ssh port error")) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) @@ -99,7 +99,7 @@ func TestPostVMStartInitAction_run(t *testing.T) { }, { name: "should print info and return without error if port is 0", - mockSvc: func(logger *mocks.Logger, ncc *mocks.LimaCmdCreator, command *mocks.Command, _ *mocks.NerdctlConfigApplier) { + mockSvc: func(logger *mocks.Logger, ncc *mocks.NerdctlCmdCreator, command *mocks.Command, _ *mocks.NerdctlConfigApplier) { logger.EXPECT().Debugln("Applying guest configuration options") command.EXPECT().Output().Return([]byte("0"), nil) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) @@ -109,7 +109,7 @@ func TestPostVMStartInitAction_run(t *testing.T) { }, { name: "should return error if applyNerdctlConfig has an error", - mockSvc: func(logger *mocks.Logger, ncc *mocks.LimaCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { + mockSvc: func(logger *mocks.Logger, ncc *mocks.NerdctlCmdCreator, command *mocks.Command, nca *mocks.NerdctlConfigApplier) { logger.EXPECT().Debugln("Applying guest configuration options") command.EXPECT().Output().Return([]byte("80"), nil) ncc.EXPECT().CreateWithoutStdio("ls", "-f", "{{.SSHLocalPort}}", limaInstanceName).Return(command) @@ -126,7 +126,7 @@ func TestPostVMStartInitAction_run(t *testing.T) { ctrl := gomock.NewController(t) logger := mocks.NewLogger(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) command := mocks.NewCommand(ctrl) nca := mocks.NewNerdctlConfigApplier(ctrl) tc.mockSvc(logger, ncc, command, nca) diff --git a/pkg/command/nerdctl_test.go b/pkg/command/nerdctl_test.go index 3937ac2ec..addc91091 100644 --- a/pkg/command/nerdctl_test.go +++ b/pkg/command/nerdctl_test.go @@ -36,13 +36,13 @@ func TestLimaCmdCreator_Create(t *testing.T) { testCases := []struct { name string - mockSvc func(*mocks.Logger, *mocks.CommandCreator, *mocks.Command, *mocks.LimaCmdCreatorSystemDeps) + mockSvc func(*mocks.Logger, *mocks.CommandCreator, *mocks.Command, *mocks.NerdctlCmdCreatorSystemDeps) wantErr error }{ { name: "happy path", wantErr: nil, - mockSvc: func(logger *mocks.Logger, cmdCreator *mocks.CommandCreator, cmd *mocks.Command, lcd *mocks.LimaCmdCreatorSystemDeps) { + mockSvc: func(logger *mocks.Logger, cmdCreator *mocks.CommandCreator, cmd *mocks.Command, lcd *mocks.NerdctlCmdCreatorSystemDeps) { logger.EXPECT().Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", mockArgs, envKeyLimaHome, mockLimaHomePath) cmdCreator.EXPECT().Create(mockLimactlPath, mockArgs).Return(cmd) lcd.EXPECT().Environ().Return([]string{}) @@ -70,7 +70,7 @@ func TestLimaCmdCreator_Create(t *testing.T) { cmdCreator := mocks.NewCommandCreator(ctrl) cmd := mocks.NewCommand(ctrl) logger := mocks.NewLogger(ctrl) - lcd := mocks.NewLimaCmdCreatorSystemDeps(ctrl) + lcd := mocks.NewNerdctlCmdCreatorSystemDeps(ctrl) tc.mockSvc(logger, cmdCreator, cmd, lcd) command.NewNerdctlCmdCreator(cmdCreator, logger, mockLimaHomePath, mockLimactlPath, mockQemuBinPath, lcd).Create(mockArgs...) }) @@ -82,13 +82,13 @@ func TestLimaCmdCreator_CreateWithoutStdio(t *testing.T) { testCases := []struct { name string - mockSvc func(*mocks.Logger, *mocks.CommandCreator, *mocks.Command, *mocks.LimaCmdCreatorSystemDeps) + mockSvc func(*mocks.Logger, *mocks.CommandCreator, *mocks.Command, *mocks.NerdctlCmdCreatorSystemDeps) wantErr error }{ { name: "happy path", wantErr: nil, - mockSvc: func(logger *mocks.Logger, cmdCreator *mocks.CommandCreator, cmd *mocks.Command, lcd *mocks.LimaCmdCreatorSystemDeps) { + mockSvc: func(logger *mocks.Logger, cmdCreator *mocks.CommandCreator, cmd *mocks.Command, lcd *mocks.NerdctlCmdCreatorSystemDeps) { logger.EXPECT().Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", mockArgs, envKeyLimaHome, mockLimaHomePath) cmdCreator.EXPECT().Create(mockLimactlPath, mockArgs).Return(cmd) lcd.EXPECT().Environ().Return([]string{}) @@ -113,7 +113,7 @@ func TestLimaCmdCreator_CreateWithoutStdio(t *testing.T) { cmdCreator := mocks.NewCommandCreator(ctrl) cmd := mocks.NewCommand(ctrl) logger := mocks.NewLogger(ctrl) - lcd := mocks.NewLimaCmdCreatorSystemDeps(ctrl) + lcd := mocks.NewNerdctlCmdCreatorSystemDeps(ctrl) tc.mockSvc(logger, cmdCreator, cmd, lcd) command.NewNerdctlCmdCreator(cmdCreator, logger, mockLimaHomePath, mockLimactlPath, mockQemuBinPath, lcd). CreateWithoutStdio(mockArgs...) @@ -126,7 +126,7 @@ func TestLimaCmdCreator_RunWithReplacingStdout(t *testing.T) { testCases := []struct { name string - mockSvc func(*mocks.Logger, *mocks.CommandCreator, *mocks.LimaCmdCreatorSystemDeps, *gomock.Controller, string, *os.File) + mockSvc func(*mocks.Logger, *mocks.CommandCreator, *mocks.NerdctlCmdCreatorSystemDeps, *gomock.Controller, string, *os.File) wantErr error stdoutRs []command.Replacement inOut string @@ -139,7 +139,7 @@ func TestLimaCmdCreator_RunWithReplacingStdout(t *testing.T) { inOut: "s1 s2 ,s3 /s4 s1.s5", outOut: "t1 s2 ,t3 /s4 t1.s5", mockSvc: func(logger *mocks.Logger, cmdCreator *mocks.CommandCreator, - lcd *mocks.LimaCmdCreatorSystemDeps, ctrl *gomock.Controller, inOut string, f *os.File, + lcd *mocks.NerdctlCmdCreatorSystemDeps, ctrl *gomock.Controller, inOut string, f *os.File, ) { logger.EXPECT().Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", mockArgs, envKeyLimaHome, mockLimaHomePath) cmd := mocks.NewCommand(ctrl) @@ -171,7 +171,7 @@ func TestLimaCmdCreator_RunWithReplacingStdout(t *testing.T) { inOut: "s1 s2 ,s3 /s4 s1.s5", outOut: "s3 s3 ,s3 /s4 s3.s5", mockSvc: func(logger *mocks.Logger, cmdCreator *mocks.CommandCreator, - lcd *mocks.LimaCmdCreatorSystemDeps, ctrl *gomock.Controller, inOut string, f *os.File, + lcd *mocks.NerdctlCmdCreatorSystemDeps, ctrl *gomock.Controller, inOut string, f *os.File, ) { logger.EXPECT().Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", mockArgs, envKeyLimaHome, mockLimaHomePath) @@ -204,7 +204,7 @@ func TestLimaCmdCreator_RunWithReplacingStdout(t *testing.T) { inOut: "s1 s2 ,s3 /s4 .s5", outOut: "s1 s2 ,s3 /s4 .s5", mockSvc: func(logger *mocks.Logger, cmdCreator *mocks.CommandCreator, - lcd *mocks.LimaCmdCreatorSystemDeps, ctrl *gomock.Controller, inOut string, f *os.File, + lcd *mocks.NerdctlCmdCreatorSystemDeps, ctrl *gomock.Controller, inOut string, f *os.File, ) { logger.EXPECT().Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", mockArgs, envKeyLimaHome, mockLimaHomePath) cmd := mocks.NewCommand(ctrl) @@ -236,7 +236,7 @@ func TestLimaCmdCreator_RunWithReplacingStdout(t *testing.T) { inOut: "source-out", outOut: "", mockSvc: func(logger *mocks.Logger, cmdCreator *mocks.CommandCreator, - lcd *mocks.LimaCmdCreatorSystemDeps, ctrl *gomock.Controller, _ string, _ *os.File, + lcd *mocks.NerdctlCmdCreatorSystemDeps, ctrl *gomock.Controller, _ string, _ *os.File, ) { logger.EXPECT().Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", mockArgs, envKeyLimaHome, mockLimaHomePath) cmd := mocks.NewCommand(ctrl) @@ -262,7 +262,7 @@ func TestLimaCmdCreator_RunWithReplacingStdout(t *testing.T) { inOut: "source-out", outOut: "", mockSvc: func(logger *mocks.Logger, cmdCreator *mocks.CommandCreator, - lcd *mocks.LimaCmdCreatorSystemDeps, ctrl *gomock.Controller, inOut string, _ *os.File, + lcd *mocks.NerdctlCmdCreatorSystemDeps, ctrl *gomock.Controller, inOut string, _ *os.File, ) { logger.EXPECT().Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", mockArgs, envKeyLimaHome, mockLimaHomePath) cmd := mocks.NewCommand(ctrl) @@ -297,7 +297,7 @@ func TestLimaCmdCreator_RunWithReplacingStdout(t *testing.T) { ctrl := gomock.NewController(t) cmdCreator := mocks.NewCommandCreator(ctrl) logger := mocks.NewLogger(ctrl) - lcd := mocks.NewLimaCmdCreatorSystemDeps(ctrl) + lcd := mocks.NewNerdctlCmdCreatorSystemDeps(ctrl) stdoutFilepath := filepath.Clean(filepath.Join(t.TempDir(), "test")) stdoutFile, err := os.Create(stdoutFilepath) diff --git a/pkg/config/config.go b/pkg/config/config.go index d41a82a36..0af5641fd 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -29,12 +29,12 @@ type AdditionalDirectory struct { Path *string `yaml:"path"` } -// SystemSettings represents all settings shared by virtualized Finch configurations. +// SharedSystemSettings represents all settings shared by virtualized Finch configurations. type SharedSystemSettings struct { VMType *limayaml.VMType `yaml:"vmType,omitempty"` } -// GeneralSettings represents settings shared by all Finch configurations. +// SharedSettings represents settings shared by all Finch configurations. type SharedSettings struct { Snapshotters []string `yaml:"snapshotters,omitempty"` CredsHelpers []string `yaml:"creds_helpers,omitempty"` diff --git a/pkg/dependency/vmnet/sudoers_file_unix_test.go b/pkg/dependency/vmnet/sudoers_file_unix_test.go index 0863c4d4c..5a656be55 100644 --- a/pkg/dependency/vmnet/sudoers_file_unix_test.go +++ b/pkg/dependency/vmnet/sudoers_file_unix_test.go @@ -44,12 +44,12 @@ func TestSudoers_Installed(t *testing.T) { testCases := []struct { name string - mockSvc func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, lc *mocks.LimaCmdCreator, l *mocks.Logger) + mockSvc func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, lc *mocks.NerdctlCmdCreator, l *mocks.Logger) want bool }{ { name: "happy path", - mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, lc *mocks.LimaCmdCreator, _ *mocks.Logger) { + mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, lc *mocks.NerdctlCmdCreator, _ *mocks.Logger) { sudoersData := []byte("test data") err := afero.WriteFile(mFs, "/etc/sudoers.d/finch-lima", sudoersData, 0o666) @@ -62,7 +62,7 @@ func TestSudoers_Installed(t *testing.T) { }, { name: "sudoers path doesn't exist", - mockSvc: func(_ *testing.T, _ *mocks.Command, _ afero.Fs, _ *mocks.LimaCmdCreator, l *mocks.Logger) { + mockSvc: func(_ *testing.T, _ *mocks.Command, _ afero.Fs, _ *mocks.NerdctlCmdCreator, l *mocks.Logger) { var pathErr fs.PathError pathErr.Op = "open" pathErr.Path = "/etc/sudoers.d/finch-lima" @@ -74,7 +74,7 @@ func TestSudoers_Installed(t *testing.T) { }, { name: "sudoers command throws an error", - mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, lc *mocks.LimaCmdCreator, l *mocks.Logger) { + mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, lc *mocks.NerdctlCmdCreator, l *mocks.Logger) { sudoersData := []byte("test data") wantErr := errors.New("some error") @@ -89,7 +89,7 @@ func TestSudoers_Installed(t *testing.T) { }, { name: "paths exist, but contents don't match", - mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, lc *mocks.LimaCmdCreator, _ *mocks.Logger) { + mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, lc *mocks.NerdctlCmdCreator, _ *mocks.Logger) { sudoersData1 := []byte("test data") sudoersData2 := []byte("different test data") @@ -112,7 +112,7 @@ func TestSudoers_Installed(t *testing.T) { cmd := mocks.NewCommand(ctrl) l := mocks.NewLogger(ctrl) mFs := afero.NewMemMapFs() - mLimaCreator := mocks.NewLimaCmdCreator(ctrl) + mLimaCreator := mocks.NewNerdctlCmdCreator(ctrl) tc.mockSvc(t, cmd, mFs, mLimaCreator, l) got := newSudoersFile(mFs, nil, mLimaCreator, l).Installed() @@ -129,12 +129,12 @@ func TestSudoers_Install(t *testing.T) { testCases := []struct { name string - mockSvc func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, ec *mocks.CommandCreator, lc *mocks.LimaCmdCreator) + mockSvc func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, ec *mocks.CommandCreator, lc *mocks.NerdctlCmdCreator) want error }{ { name: "happy path", - mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, ec *mocks.CommandCreator, lc *mocks.LimaCmdCreator) { + mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, ec *mocks.CommandCreator, lc *mocks.NerdctlCmdCreator) { sudoersData := []byte("test data") mockSudoersOut := []byte("mock_sudoers_out") @@ -153,7 +153,7 @@ func TestSudoers_Install(t *testing.T) { }, { name: "lima sudoers command throws err", - mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, _ *mocks.CommandCreator, lc *mocks.LimaCmdCreator) { + mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, _ *mocks.CommandCreator, lc *mocks.NerdctlCmdCreator) { sudoersData := []byte("test data") err := afero.WriteFile(mFs, "/etc/sudoers.d/finch-lima", sudoersData, 0o666) @@ -166,7 +166,7 @@ func TestSudoers_Install(t *testing.T) { }, { name: "sudo tee command throws err", - mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, ec *mocks.CommandCreator, lc *mocks.LimaCmdCreator) { + mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, ec *mocks.CommandCreator, lc *mocks.NerdctlCmdCreator) { sudoersData := []byte("test data") mockSudoersOut := []byte("mock_sudoers_out") @@ -183,7 +183,7 @@ func TestSudoers_Install(t *testing.T) { }, { name: "sudo chmod command throws err", - mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, ec *mocks.CommandCreator, lc *mocks.LimaCmdCreator) { + mockSvc: func(t *testing.T, cmd *mocks.Command, mFs afero.Fs, ec *mocks.CommandCreator, lc *mocks.NerdctlCmdCreator) { sudoersData := []byte("test data") mockSudoersOut := []byte("mock_sudoers_out") @@ -211,7 +211,7 @@ func TestSudoers_Install(t *testing.T) { cmd := mocks.NewCommand(ctrl) mFs := afero.NewMemMapFs() mExecCreator := mocks.NewCommandCreator(ctrl) - mLimaCreator := mocks.NewLimaCmdCreator(ctrl) + mLimaCreator := mocks.NewNerdctlCmdCreator(ctrl) tc.mockSvc(t, cmd, mFs, mExecCreator, mLimaCreator) got := newSudoersFile(mFs, mExecCreator, mLimaCreator, nil).Install() diff --git a/pkg/disk/disk_darwin_test.go b/pkg/disk/disk_darwin_test.go index 44315f47c..12c27343e 100644 --- a/pkg/disk/disk_darwin_test.go +++ b/pkg/disk/disk_darwin_test.go @@ -24,7 +24,7 @@ func TestDisk_NewUserDataDiskManager(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) ecc := mocks.NewCommandCreator(ctrl) dfs := mocks.NewMockdiskFS(ctrl) finch := fpath.Finch("mock_finch") @@ -81,7 +81,7 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { name string cfg *config.Finch wantErr error - mockSvc func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, ecc *mocks.CommandCreator) + mockSvc func(ncc *mocks.NerdctlCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, ecc *mocks.CommandCreator) }{ { name: "create and save disk", @@ -93,7 +93,7 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { }, }, wantErr: nil, - mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte(""), nil) @@ -120,7 +120,7 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { }, }, wantErr: nil, - mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return(listSuccessOutput, nil) @@ -139,7 +139,7 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { }, }, wantErr: nil, - mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return(listSuccessOutput, nil) @@ -166,7 +166,7 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { }, }, wantErr: nil, - mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte(""), nil) @@ -193,7 +193,7 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { }, }, wantErr: nil, - mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, _ *mocks.CommandCreator) { ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return(listSuccessOutput, nil) @@ -214,7 +214,7 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { }, }, wantErr: nil, - mockSvc: func(ncc *mocks.LimaCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, ecc *mocks.CommandCreator) { + mockSvc: func(ncc *mocks.NerdctlCmdCreator, dfs *mocks.MockdiskFS, cmd *mocks.Command, ecc *mocks.CommandCreator) { ncc.EXPECT().CreateWithoutStdio(mockListArgs).Return(cmd) cmd.EXPECT().Output().Return(listSuccessOutput, nil) @@ -246,7 +246,7 @@ func TestUserDataDiskManager_InitializeUserDataDisk(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) ecc := mocks.NewCommandCreator(ctrl) dfs := mocks.NewMockdiskFS(ctrl) cmd := mocks.NewCommand(ctrl) diff --git a/pkg/lima/lima_test.go b/pkg/lima/lima_test.go index f4cc717bf..21a90f7a0 100644 --- a/pkg/lima/lima_test.go +++ b/pkg/lima/lima_test.go @@ -23,13 +23,13 @@ func TestGetVMStatus(t *testing.T) { name string want lima.VMStatus wantErr error - mockSvc func(*mocks.LimaCmdCreator, *mocks.Logger, *mocks.Command) + mockSvc func(*mocks.NerdctlCmdCreator, *mocks.Logger, *mocks.Command) }{ { name: "running VM", want: lima.Running, wantErr: nil, - mockSvc: func(creator *mocks.LimaCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { + mockSvc: func(creator *mocks.NerdctlCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { creator.EXPECT().CreateWithoutStdio(mockArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte("Running "), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Running") @@ -39,7 +39,7 @@ func TestGetVMStatus(t *testing.T) { name: "stopped VM", want: lima.Stopped, wantErr: nil, - mockSvc: func(creator *mocks.LimaCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { + mockSvc: func(creator *mocks.NerdctlCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { creator.EXPECT().CreateWithoutStdio(mockArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte("Stopped "), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Stopped") @@ -49,7 +49,7 @@ func TestGetVMStatus(t *testing.T) { name: "nonexistent VM", want: lima.Nonexistent, wantErr: nil, - mockSvc: func(creator *mocks.LimaCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { + mockSvc: func(creator *mocks.NerdctlCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { creator.EXPECT().CreateWithoutStdio(mockArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte(" "), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "") @@ -59,7 +59,7 @@ func TestGetVMStatus(t *testing.T) { name: "unknown VM status", want: lima.Unknown, wantErr: errors.New("unrecognized system status"), - mockSvc: func(creator *mocks.LimaCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { + mockSvc: func(creator *mocks.NerdctlCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { creator.EXPECT().CreateWithoutStdio(mockArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte("Broken "), nil) logger.EXPECT().Debugf("Status of virtual machine: %s", "Broken") @@ -69,7 +69,7 @@ func TestGetVMStatus(t *testing.T) { name: "status command returns an error", want: lima.Unknown, wantErr: errors.New("get status error"), - mockSvc: func(creator *mocks.LimaCmdCreator, _ *mocks.Logger, cmd *mocks.Command) { + mockSvc: func(creator *mocks.NerdctlCmdCreator, _ *mocks.Logger, cmd *mocks.Command) { creator.EXPECT().CreateWithoutStdio(mockArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte("Broken "), errors.New("get status error")) }, @@ -82,7 +82,7 @@ func TestGetVMStatus(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - creator := mocks.NewLimaCmdCreator(ctrl) + creator := mocks.NewNerdctlCmdCreator(ctrl) statusCmd := mocks.NewCommand(ctrl) logger := mocks.NewLogger(ctrl) tc.mockSvc(creator, logger, statusCmd) @@ -102,13 +102,13 @@ func TestGetVMType(t *testing.T) { name string want lima.VMType wantErr error - mockSvc func(*mocks.LimaCmdCreator, *mocks.Logger, *mocks.Command) + mockSvc func(*mocks.NerdctlCmdCreator, *mocks.Logger, *mocks.Command) }{ { name: "qemu VM", want: lima.QEMU, wantErr: nil, - mockSvc: func(creator *mocks.LimaCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { + mockSvc: func(creator *mocks.NerdctlCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { creator.EXPECT().CreateWithoutStdio(mockArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte("qemu"), nil) logger.EXPECT().Debugf("VMType of virtual machine: %s", "qemu") @@ -118,7 +118,7 @@ func TestGetVMType(t *testing.T) { name: "vz VM", want: lima.VZ, wantErr: nil, - mockSvc: func(creator *mocks.LimaCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { + mockSvc: func(creator *mocks.NerdctlCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { creator.EXPECT().CreateWithoutStdio(mockArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte("vz"), nil) logger.EXPECT().Debugf("VMType of virtual machine: %s", "vz") @@ -128,7 +128,7 @@ func TestGetVMType(t *testing.T) { name: "wsl VM", want: lima.WSL, wantErr: nil, - mockSvc: func(creator *mocks.LimaCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { + mockSvc: func(creator *mocks.NerdctlCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { creator.EXPECT().CreateWithoutStdio(mockArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte("wsl2"), nil) logger.EXPECT().Debugf("VMType of virtual machine: %s", "wsl2") @@ -138,7 +138,7 @@ func TestGetVMType(t *testing.T) { name: "nonexistent VM", want: lima.NonexistentVMType, wantErr: nil, - mockSvc: func(creator *mocks.LimaCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { + mockSvc: func(creator *mocks.NerdctlCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { creator.EXPECT().CreateWithoutStdio(mockArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte(" "), nil) logger.EXPECT().Debugf("VMType of virtual machine: %s", "") @@ -148,7 +148,7 @@ func TestGetVMType(t *testing.T) { name: "unknown VM type", want: lima.UnknownVMType, wantErr: errors.New("unrecognized VMType"), - mockSvc: func(creator *mocks.LimaCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { + mockSvc: func(creator *mocks.NerdctlCmdCreator, logger *mocks.Logger, cmd *mocks.Command) { creator.EXPECT().CreateWithoutStdio(mockArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte("Broken "), nil) logger.EXPECT().Debugf("VMType of virtual machine: %s", "Broken") @@ -158,7 +158,7 @@ func TestGetVMType(t *testing.T) { name: "type command returns an error", want: lima.UnknownVMType, wantErr: errors.New("get VMType error"), - mockSvc: func(creator *mocks.LimaCmdCreator, _ *mocks.Logger, cmd *mocks.Command) { + mockSvc: func(creator *mocks.NerdctlCmdCreator, _ *mocks.Logger, cmd *mocks.Command) { creator.EXPECT().CreateWithoutStdio(mockArgs).Return(cmd) cmd.EXPECT().Output().Return([]byte("Broken "), errors.New("get VMType error")) }, @@ -171,7 +171,7 @@ func TestGetVMType(t *testing.T) { t.Parallel() ctrl := gomock.NewController(t) - creator := mocks.NewLimaCmdCreator(ctrl) + creator := mocks.NewNerdctlCmdCreator(ctrl) statusCmd := mocks.NewCommand(ctrl) logger := mocks.NewLogger(ctrl) tc.mockSvc(creator, logger, statusCmd) diff --git a/pkg/mocks/pkg_support_config.go b/pkg/mocks/pkg_support_config.go new file mode 100644 index 000000000..9e15bbfce --- /dev/null +++ b/pkg/mocks/pkg_support_config.go @@ -0,0 +1,65 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/runfinch/finch/pkg/support (interfaces: BundleConfig) + +// Package mocks is a generated GoMock package. +package mocks + +import ( + reflect "reflect" + + gomock "github.com/golang/mock/gomock" +) + +// BundleConfig is a mock of BundleConfig interface. +type BundleConfig struct { + ctrl *gomock.Controller + recorder *BundleConfigMockRecorder +} + +// BundleConfigMockRecorder is the mock recorder for BundleConfig. +type BundleConfigMockRecorder struct { + mock *BundleConfig +} + +// NewBundleConfig creates a new mock instance. +func NewBundleConfig(ctrl *gomock.Controller) *BundleConfig { + mock := &BundleConfig{ctrl: ctrl} + mock.recorder = &BundleConfigMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *BundleConfig) EXPECT() *BundleConfigMockRecorder { + return m.recorder +} + +// ConfigFiles mocks base method. +func (m *BundleConfig) ConfigFiles() []string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ConfigFiles") + ret0, _ := ret[0].([]string) + return ret0 +} + +// ConfigFiles indicates an expected call of ConfigFiles. +func (mr *BundleConfigMockRecorder) ConfigFiles() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigFiles", reflect.TypeOf((*BundleConfig)(nil).ConfigFiles)) +} + +// LogFiles mocks base method. +func (m *BundleConfig) LogFiles() []string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "LogFiles") + ret0, _ := ret[0].([]string) + return ret0 +} + +// LogFiles indicates an expected call of LogFiles. +func (mr *BundleConfigMockRecorder) LogFiles() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LogFiles", reflect.TypeOf((*BundleConfig)(nil).LogFiles)) +} diff --git a/pkg/support/config.go b/pkg/support/config.go index a1d970432..6ffd99a09 100644 --- a/pkg/support/config.go +++ b/pkg/support/config.go @@ -12,6 +12,8 @@ import ( ) // BundleConfig provides methods that configure what is included in a support bundle. +// +//go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/pkg_support_config.go -package=mocks -mock_names BundleConfig=BundleConfig . BundleConfig type BundleConfig interface { LogFiles() []string ConfigFiles() []string @@ -23,6 +25,8 @@ type bundleConfig struct { } // NewBundleConfig creates a new bundleConfig. +// +//go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/pkg_support_config.go -package=mocks -mock_names NewBundleConfig=NewBundleConfig . NewBundleConfig func NewBundleConfig(finch fpath.Finch, homeDir string) BundleConfig { return &bundleConfig{ finch: finch, diff --git a/pkg/support/support_test.go b/pkg/support/support_test.go index c7f04de15..8996e7aa8 100644 --- a/pkg/support/support_test.go +++ b/pkg/support/support_test.go @@ -25,7 +25,7 @@ func TestSupport_NewBundleBuilder(t *testing.T) { ctrl := gomock.NewController(t) ecc := mocks.NewCommandCreator(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) logger := mocks.NewLogger(ctrl) fs := afero.NewMemMapFs() finch := fpath.Finch("mockfinch") @@ -48,7 +48,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { *mocks.Logger, *mocks.BundleConfig, *mocks.CommandCreator, - *mocks.LimaCmdCreator, + *mocks.NerdctlCmdCreator, *mocks.Command, *mocks.MockLimaWrapper, afero.Fs, @@ -62,7 +62,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { logger *mocks.Logger, config *mocks.BundleConfig, ecc *mocks.CommandCreator, - _ *mocks.LimaCmdCreator, + _ *mocks.NerdctlCmdCreator, cmd *mocks.Command, lima *mocks.MockLimaWrapper, _ afero.Fs, @@ -108,7 +108,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { logger *mocks.Logger, config *mocks.BundleConfig, ecc *mocks.CommandCreator, - _ *mocks.LimaCmdCreator, + _ *mocks.NerdctlCmdCreator, cmd *mocks.Command, lima *mocks.MockLimaWrapper, _ afero.Fs, @@ -151,7 +151,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { logger *mocks.Logger, config *mocks.BundleConfig, ecc *mocks.CommandCreator, - _ *mocks.LimaCmdCreator, + _ *mocks.NerdctlCmdCreator, cmd *mocks.Command, lima *mocks.MockLimaWrapper, _ afero.Fs, @@ -193,7 +193,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { logger *mocks.Logger, config *mocks.BundleConfig, ecc *mocks.CommandCreator, - _ *mocks.LimaCmdCreator, + _ *mocks.NerdctlCmdCreator, cmd *mocks.Command, lima *mocks.MockLimaWrapper, _ afero.Fs, @@ -235,7 +235,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { logger *mocks.Logger, config *mocks.BundleConfig, ecc *mocks.CommandCreator, - _ *mocks.LimaCmdCreator, + _ *mocks.NerdctlCmdCreator, cmd *mocks.Command, lima *mocks.MockLimaWrapper, _ afero.Fs, @@ -278,7 +278,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { logger *mocks.Logger, config *mocks.BundleConfig, ecc *mocks.CommandCreator, - ncc *mocks.LimaCmdCreator, + ncc *mocks.NerdctlCmdCreator, cmd *mocks.Command, lima *mocks.MockLimaWrapper, _ afero.Fs, @@ -347,7 +347,7 @@ func TestSupportBundleBuilder_GenerateSupportBundle(t *testing.T) { config := mocks.NewBundleConfig(ctrl) finch := fpath.Finch("mockfinch") ecc := mocks.NewCommandCreator(ctrl) - ncc := mocks.NewLimaCmdCreator(ctrl) + ncc := mocks.NewNerdctlCmdCreator(ctrl) lima := mocks.NewMockLimaWrapper(ctrl) cmd := mocks.NewCommand(ctrl) From 26c56dc1aacaf264f1bc4aa4c4277816cdddb756 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 23 Jul 2024 14:55:27 -0400 Subject: [PATCH 05/37] fix unit tests Signed-off-by: Justin Alvarez --- pkg/config/lima_config_applier_darwin_test.go | 3 ++- pkg/config/nerdctl_config_applier.go | 2 +- pkg/config/nerdctl_config_applier_native.go | 2 +- pkg/config/nerdctl_config_applier_remote.go | 6 ++---- pkg/config/nerdctl_config_applier_test.go | 9 +++++---- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/pkg/config/lima_config_applier_darwin_test.go b/pkg/config/lima_config_applier_darwin_test.go index f20fe8a68..35337ab41 100644 --- a/pkg/config/lima_config_applier_darwin_test.go +++ b/pkg/config/lima_config_applier_darwin_test.go @@ -612,12 +612,13 @@ mountType: "reverse-sshfs"`), 0o600) _ *mocks.Logger, cmd *mocks.Command, creator *mocks.CommandCreator, - _ *mocks.LimaConfigApplierSystemDeps, + deps *mocks.LimaConfigApplierSystemDeps, ) { err := afero.WriteFile(fs, "/lima.yaml", []byte("memory: 4GiB\ncpus: 8"), 0o600) require.NoError(t, err) cmd.EXPECT().Output().Return([]byte("13.0.0"), nil) creator.EXPECT().Create("sw_vers", "-productVersion").Return(cmd) + deps.EXPECT().Arch() }, postRunCheck: func(t *testing.T, fs afero.Fs) { buf, err := afero.ReadFile(fs, "/override.yaml") diff --git a/pkg/config/nerdctl_config_applier.go b/pkg/config/nerdctl_config_applier.go index 79513abcb..f6eb45d42 100644 --- a/pkg/config/nerdctl_config_applier.go +++ b/pkg/config/nerdctl_config_applier.go @@ -111,7 +111,7 @@ func updateNerdctlConfig(fs afero.Fs, homeDir string, rootless bool) error { // Apply updates the nerdctl config. func (nca *nerdctlConfigApplier) Apply(remoteAddr string) error { - nFs, err := nerdctlFs(nca.fs, nca.privateKeyPath, remoteAddr) + nFs, err := nca.nerdctlFs(nca.fs, nca.privateKeyPath, remoteAddr) if err != nil { return fmt.Errorf("failed to get nerdctlFs: %w", err) } diff --git a/pkg/config/nerdctl_config_applier_native.go b/pkg/config/nerdctl_config_applier_native.go index a5a149f3e..6198f8de2 100644 --- a/pkg/config/nerdctl_config_applier_native.go +++ b/pkg/config/nerdctl_config_applier_native.go @@ -8,7 +8,7 @@ import ( const nerdctlRootfulCfgPath = "/etc/finch/nerdctl/nerdctl.toml" -func nerdctlFs(hostFs afero.Fs, _ string, _ string) (afero.Fs, error) { +func (nca *nerdctlConfigApplier) nerdctlFs(hostFs afero.Fs, _ string, _ string) (afero.Fs, error) { return hostFs, nil } diff --git a/pkg/config/nerdctl_config_applier_remote.go b/pkg/config/nerdctl_config_applier_remote.go index 901da2c5d..a7584f418 100644 --- a/pkg/config/nerdctl_config_applier_remote.go +++ b/pkg/config/nerdctl_config_applier_remote.go @@ -16,16 +16,14 @@ import ( const nerdctlRootfulCfgPath = "/etc/nerdctl/nerdctl.toml" -func nerdctlFs(hostFs afero.Fs, privateKeyPath string, remoteAddr string) (afero.Fs, error) { +func (nca *nerdctlConfigApplier) nerdctlFs(hostFs afero.Fs, privateKeyPath string, remoteAddr string) (afero.Fs, error) { user := "root" sshCfg, err := fssh.NewClientConfig(hostFs, user, privateKeyPath) if err != nil { return nil, fmt.Errorf("failed to create ssh client config: %w", err) } - dialer := fssh.NewDialer() - - sshClient, err := dialer.Dial("tcp", remoteAddr, sshCfg) + sshClient, err := nca.dialer.Dial("tcp", remoteAddr, sshCfg) if err != nil { return nil, fmt.Errorf("failed to setup ssh client: %w", err) } diff --git a/pkg/config/nerdctl_config_applier_test.go b/pkg/config/nerdctl_config_applier_test.go index 60a6abcb5..401ed859e 100644 --- a/pkg/config/nerdctl_config_applier_test.go +++ b/pkg/config/nerdctl_config_applier_test.go @@ -259,11 +259,11 @@ func TestNerdctlConfigApplier_Apply(t *testing.T) { mockSvc: func(_ *testing.T, _ afero.Fs, _ *mocks.Dialer) { }, want: fmt.Errorf( - "failed to create ssh client config: %w", - fmt.Errorf( + "failed to get nerdctlFs: %w", + fmt.Errorf("failed to create ssh client config: %w", fmt.Errorf( "failed to open private key file: %w", &fs.PathError{Op: "open", Path: privateKeyPath, Err: errors.New("file does not exist")}, - ), + )), ), }, { @@ -276,7 +276,8 @@ func TestNerdctlConfigApplier_Apply(t *testing.T) { d.EXPECT().Dial("tcp", "deadbeef", gomock.Any()).Return(nil, fmt.Errorf("some error")) }, - want: fmt.Errorf("failed to setup ssh client: %w", fmt.Errorf("some error")), + want: fmt.Errorf("failed to get nerdctlFs: %w", + fmt.Errorf("failed to setup ssh client: %w", fmt.Errorf("some error"))), }, } From 7c52c4d49f41ed8b0cfedc4a6ff8f96a854620f0 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 23 Jul 2024 15:29:46 -0400 Subject: [PATCH 06/37] fix linting Signed-off-by: Justin Alvarez --- pkg/config/config_darwin.go | 1 + pkg/config/config_native.go | 1 + pkg/config/config_windows.go | 2 ++ 3 files changed, 4 insertions(+) diff --git a/pkg/config/config_darwin.go b/pkg/config/config_darwin.go index fc9687ed1..c2f991789 100644 --- a/pkg/config/config_darwin.go +++ b/pkg/config/config_darwin.go @@ -18,6 +18,7 @@ import ( "github.com/runfinch/finch/pkg/system" ) +// SystemSettings represents the system configuration specifc to macOS. type SystemSettings struct { CPUs *int `yaml:"cpus,omitempty"` Memory *string `yaml:"memory,omitempty"` diff --git a/pkg/config/config_native.go b/pkg/config/config_native.go index 6509dbb0d..e9769f25a 100644 --- a/pkg/config/config_native.go +++ b/pkg/config/config_native.go @@ -5,6 +5,7 @@ package config +// Finch represents the configuration file for Finch CLI. type Finch struct { SharedSettings } diff --git a/pkg/config/config_windows.go b/pkg/config/config_windows.go index 801894c6e..16a652b64 100644 --- a/pkg/config/config_windows.go +++ b/pkg/config/config_windows.go @@ -11,10 +11,12 @@ import ( "github.com/spf13/afero" ) +// SystemSettings represents the system configuration specifc to Windows. type SystemSettings struct { SharedSystemSettings `yaml:",inline"` } +// Finch represents the configuration file for Finch CLI. type Finch struct { SystemSettings `yaml:",inline"` SharedSettings `yaml:",inline"` From efc06d553f5b70eabeee2f6de3d132f5bc063b35 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 23 Jul 2024 15:30:03 -0400 Subject: [PATCH 07/37] remove unnecessary mockgen call Signed-off-by: Justin Alvarez --- pkg/support/config.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/pkg/support/config.go b/pkg/support/config.go index 6ffd99a09..b636063ec 100644 --- a/pkg/support/config.go +++ b/pkg/support/config.go @@ -25,8 +25,6 @@ type bundleConfig struct { } // NewBundleConfig creates a new bundleConfig. -// -//go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/pkg_support_config.go -package=mocks -mock_names NewBundleConfig=NewBundleConfig . NewBundleConfig func NewBundleConfig(finch fpath.Finch, homeDir string) BundleConfig { return &bundleConfig{ finch: finch, From 44b2fd5d5f4d02462a78c3c2ea674353588f1d4f Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 23 Jul 2024 15:30:21 -0400 Subject: [PATCH 08/37] remove unused code Signed-off-by: Justin Alvarez --- pkg/config/config.go | 7 ------- 1 file changed, 7 deletions(-) diff --git a/pkg/config/config.go b/pkg/config/config.go index 0af5641fd..4a52dd8f3 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -85,13 +85,6 @@ type NerdctlConfigApplier interface { Apply(remoteAddr string) error } -// // NerdctlConfigApplierSystemDeps provides system dependencies. -// // -// //go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/pkg_config_nerdctl_config_applier_system_deps.go -package=mocks -mock_names NerdctlConfigApplierSystemDeps=NerdctlConfigApplierSystemDeps . NerdctlConfigApplierSystemDeps -// type NerdctlConfigApplierSystemDeps interface { -// system.UserHomeDir -// } - // LoadSystemDeps contains the system dependencies for Load. // //go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/pkg_config_load_system_deps.go -package=mocks -mock_names LoadSystemDeps=LoadSystemDeps . LoadSystemDeps From e4c14edf9d042bed84a6784c566ad9e11beeaf4b Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 23 Jul 2024 15:46:43 -0400 Subject: [PATCH 09/37] fix windows unit tests Signed-off-by: Justin Alvarez --- ....go => virtual_machine_settings_darwin.go} | 2 +- ...> virtual_machine_settings_test_darwin.go} | 2 +- cmd/finch/virtual_machine_settings_windows.go | 61 +++++++++++++++++++ pkg/config/config_windows.go | 7 --- 4 files changed, 63 insertions(+), 9 deletions(-) rename cmd/finch/{virtual_machine_settings.go => virtual_machine_settings_darwin.go} (98%) rename cmd/finch/{virtual_machine_settings_test.go => virtual_machine_settings_test_darwin.go} (99%) create mode 100644 cmd/finch/virtual_machine_settings_windows.go diff --git a/cmd/finch/virtual_machine_settings.go b/cmd/finch/virtual_machine_settings_darwin.go similarity index 98% rename from cmd/finch/virtual_machine_settings.go rename to cmd/finch/virtual_machine_settings_darwin.go index 7265642e8..15f104f1b 100644 --- a/cmd/finch/virtual_machine_settings.go +++ b/cmd/finch/virtual_machine_settings_darwin.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin || windows +//go:build darwin package main diff --git a/cmd/finch/virtual_machine_settings_test.go b/cmd/finch/virtual_machine_settings_test_darwin.go similarity index 99% rename from cmd/finch/virtual_machine_settings_test.go rename to cmd/finch/virtual_machine_settings_test_darwin.go index 60a8bf776..9437c95b3 100644 --- a/cmd/finch/virtual_machine_settings_test.go +++ b/cmd/finch/virtual_machine_settings_test_darwin.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin || windows +//go:build darwin package main diff --git a/cmd/finch/virtual_machine_settings_windows.go b/cmd/finch/virtual_machine_settings_windows.go new file mode 100644 index 000000000..45a873884 --- /dev/null +++ b/cmd/finch/virtual_machine_settings_windows.go @@ -0,0 +1,61 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build windows + +package main + +import ( + "io" + + "github.com/runfinch/finch/pkg/config" + "github.com/runfinch/finch/pkg/flog" + + "github.com/spf13/afero" + "github.com/spf13/cobra" +) + +func newSettingsVMCommand( + logger flog.Logger, + lca config.LimaConfigApplier, + fs afero.Fs, + stdout io.Writer, +) *cobra.Command { + settingsVMCommand := &cobra.Command{ + Use: "settings", + Short: "Disabled on Windows as there are currently no configurable VM settings", + Hidden: true, + RunE: newSettingsVMAction(logger, lca, fs, stdout).runAdapter, + } + + return settingsVMCommand +} + +type settingsVMAction struct { + logger flog.Logger + limaConfigApplier config.LimaConfigApplier + fs afero.Fs + stdout io.Writer +} + +func newSettingsVMAction( + logger flog.Logger, + lca config.LimaConfigApplier, + fs afero.Fs, + stdout io.Writer, +) *settingsVMAction { + return &settingsVMAction{ + logger: logger, + limaConfigApplier: lca, + fs: fs, + stdout: stdout, + } +} + +func (sva *settingsVMAction) runAdapter(_ *cobra.Command, _ []string) error { + return sva.run(config.VMConfigOpts{}) +} + +func (sva *settingsVMAction) run(_ config.VMConfigOpts) error { + return nil +} diff --git a/pkg/config/config_windows.go b/pkg/config/config_windows.go index 16a652b64..9a4fff62c 100644 --- a/pkg/config/config_windows.go +++ b/pkg/config/config_windows.go @@ -7,8 +7,6 @@ package config import ( "github.com/runfinch/finch/pkg/command" - "github.com/runfinch/finch/pkg/flog" - "github.com/spf13/afero" ) // SystemSettings represents the system configuration specifc to Windows. @@ -26,8 +24,3 @@ type Finch struct { func SupportsWSL2(cmdCreator command.Creator) error { return cmdCreator.Create("wsl", "--set-default-version", "2").Run() } - -// ModifyFinchConfig Modify Finch's configuration from user inputs. -func ModifyFinchConfig(_ afero.Fs, _ flog.Logger, _ string, _ VMConfigOpts) (bool, error) { - return true, nil -} From e65052c0800b7f520462b31f1a5cb40fab558814 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 23 Jul 2024 19:39:37 -0400 Subject: [PATCH 10/37] fix linux linting errors Signed-off-by: Justin Alvarez --- cmd/finch/main_native.go | 28 ------------------- cmd/finch/nerdctl_native.go | 8 ++++-- cmd/finch/virtual_machine_local.go | 16 +++++------ ...> virtual_machine_settings_darwin_test.go} | 0 e2e/vm/additional_disk_test.go | 2 ++ e2e/vm/config_darwin_test.go | 1 + e2e/vm/config_test.go | 2 ++ e2e/vm/cred_helper_test.go | 2 ++ e2e/vm/finch_config_file_test.go | 2 ++ e2e/vm/lifecycle_test.go | 2 ++ e2e/vm/soci_test.go | 2 ++ e2e/vm/support_bundle_test.go | 2 ++ e2e/vm/version_test.go | 2 ++ e2e/vm/vm_test.go | 2 ++ pkg/command/nerdctl.go | 15 ---------- pkg/command/nerdctl_remote.go | 13 +++++++++ pkg/command/nerdctl_test.go | 11 ++++++-- pkg/config/config.go | 21 +------------- pkg/config/config_darwin.go | 19 +++++++++++++ pkg/config/lima_config_applier.go | 16 ++--------- pkg/config/lima_config_applier_native.go | 12 -------- pkg/config/nerdctl_config_applier.go | 12 -------- pkg/config/nerdctl_config_applier_native.go | 15 ++++++++++ pkg/config/nerdctl_config_applier_remote.go | 25 +++++++++++++++++ pkg/disk/disk_native.go | 8 ------ 25 files changed, 118 insertions(+), 120 deletions(-) delete mode 100644 cmd/finch/main_native.go rename cmd/finch/{virtual_machine_settings_test_darwin.go => virtual_machine_settings_darwin_test.go} (100%) diff --git a/cmd/finch/main_native.go b/cmd/finch/main_native.go deleted file mode 100644 index 24b7e3bce..000000000 --- a/cmd/finch/main_native.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -//go:build linux || native - -package main - -import ( - "github.com/spf13/afero" - - "github.com/runfinch/finch/pkg/command" - "github.com/runfinch/finch/pkg/config" - "github.com/runfinch/finch/pkg/dependency" - "github.com/runfinch/finch/pkg/flog" - "github.com/runfinch/finch/pkg/path" -) - -func dependencies( - _ command.Creator, - _ *config.Finch, - _ path.Finch, - _ afero.Fs, - _ command.NerdctlCmdCreator, - _ flog.Logger, - _ string, -) []*dependency.Group { - return []*dependency.Group{} -} diff --git a/cmd/finch/nerdctl_native.go b/cmd/finch/nerdctl_native.go index 8a432482a..6e68bdfb1 100644 --- a/cmd/finch/nerdctl_native.go +++ b/cmd/finch/nerdctl_native.go @@ -20,10 +20,14 @@ func (nc *nerdctlCommand) GetCmdArgs() []string { return []string{""} } -func (nc *nerdctlCommand) assertVMIsRunning(creator command.NerdctlCmdCreator, logger flog.Logger) error { +func (nc *nerdctlCommand) assertVMIsRunning(_ command.NerdctlCmdCreator, _ flog.Logger) error { return nil } -func resolveIP(host string, logger flog.Logger, _ command.Creator) (string, error) { +func resolveIP(_ string, _ flog.Logger, _ command.Creator) (string, error) { return "0.0.0.0", nil } + +func convertToWSLPath(_ NerdctlCommandSystemDeps, _ string) (string, error) { + return "", nil +} diff --git a/cmd/finch/virtual_machine_local.go b/cmd/finch/virtual_machine_local.go index af4a92002..32f30650d 100644 --- a/cmd/finch/virtual_machine_local.go +++ b/cmd/finch/virtual_machine_local.go @@ -16,14 +16,14 @@ import ( ) func virtualMachineCommands( - logger flog.Logger, - fp path.Finch, - ncc command.NerdctlCmdCreator, - ecc command.Creator, - fs afero.Fs, - fc *config.Finch, - home string, - finchRootPath string, + _ flog.Logger, + _ path.Finch, + _ command.NerdctlCmdCreator, + _ command.Creator, + _ afero.Fs, + _ *config.Finch, + _ string, + _ string, ) *cobra.Command { return &cobra.Command{} } diff --git a/cmd/finch/virtual_machine_settings_test_darwin.go b/cmd/finch/virtual_machine_settings_darwin_test.go similarity index 100% rename from cmd/finch/virtual_machine_settings_test_darwin.go rename to cmd/finch/virtual_machine_settings_darwin_test.go diff --git a/e2e/vm/additional_disk_test.go b/e2e/vm/additional_disk_test.go index 6e45ead74..5735fcfd0 100644 --- a/e2e/vm/additional_disk_test.go +++ b/e2e/vm/additional_disk_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package vm import ( diff --git a/e2e/vm/config_darwin_test.go b/e2e/vm/config_darwin_test.go index c9e1bebb5..aec60bc5f 100644 --- a/e2e/vm/config_darwin_test.go +++ b/e2e/vm/config_darwin_test.go @@ -1,5 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 + //go:build darwin package vm diff --git a/e2e/vm/config_test.go b/e2e/vm/config_test.go index 0ff58dd51..5233644fd 100644 --- a/e2e/vm/config_test.go +++ b/e2e/vm/config_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package vm import ( diff --git a/e2e/vm/cred_helper_test.go b/e2e/vm/cred_helper_test.go index e86ebbf34..398f35390 100644 --- a/e2e/vm/cred_helper_test.go +++ b/e2e/vm/cred_helper_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package vm import ( diff --git a/e2e/vm/finch_config_file_test.go b/e2e/vm/finch_config_file_test.go index 0137c8b8f..85c88c06e 100644 --- a/e2e/vm/finch_config_file_test.go +++ b/e2e/vm/finch_config_file_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package vm import ( diff --git a/e2e/vm/lifecycle_test.go b/e2e/vm/lifecycle_test.go index ef5a9c7e5..ad39d080b 100644 --- a/e2e/vm/lifecycle_test.go +++ b/e2e/vm/lifecycle_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package vm import ( diff --git a/e2e/vm/soci_test.go b/e2e/vm/soci_test.go index bd0c65dc4..323ea2137 100644 --- a/e2e/vm/soci_test.go +++ b/e2e/vm/soci_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package vm import ( diff --git a/e2e/vm/support_bundle_test.go b/e2e/vm/support_bundle_test.go index c3df3a416..baed0eef4 100644 --- a/e2e/vm/support_bundle_test.go +++ b/e2e/vm/support_bundle_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package vm import ( diff --git a/e2e/vm/version_test.go b/e2e/vm/version_test.go index e6bfcf69e..9befa5234 100644 --- a/e2e/vm/version_test.go +++ b/e2e/vm/version_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package vm import ( diff --git a/e2e/vm/vm_test.go b/e2e/vm/vm_test.go index efb05e1bc..dcb38f894 100644 --- a/e2e/vm/vm_test.go +++ b/e2e/vm/vm_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package vm import ( diff --git a/pkg/command/nerdctl.go b/pkg/command/nerdctl.go index 3e43da3e7..84974550b 100644 --- a/pkg/command/nerdctl.go +++ b/pkg/command/nerdctl.go @@ -5,10 +5,6 @@ package command import ( "bytes" - "fmt" - "strings" - - "golang.org/x/exp/slices" "github.com/runfinch/finch/pkg/flog" "github.com/runfinch/finch/pkg/system" @@ -114,14 +110,3 @@ func (ncc *nerdctlCmdCreator) replaceBytes(s []byte, rs []Replacement) []byte { } return s } - -func replaceOrAppend(orig []string, varName, newVar string) []string { - envIdx := slices.IndexFunc(orig, func(envVar string) bool { - return strings.HasPrefix(envVar, fmt.Sprintf("%s=", varName)) - }) - - if envIdx != -1 { - return slices.Replace(orig, envIdx, envIdx+1, newVar) - } - return append(orig, newVar) -} diff --git a/pkg/command/nerdctl_remote.go b/pkg/command/nerdctl_remote.go index bd61dcb80..a9d1ef62f 100644 --- a/pkg/command/nerdctl_remote.go +++ b/pkg/command/nerdctl_remote.go @@ -9,6 +9,8 @@ import ( "fmt" "io" "runtime" + "slices" + "strings" ) const ( @@ -45,3 +47,14 @@ func (ncc *nerdctlCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, cmd.SetStderr(stderr) return cmd } + +func replaceOrAppend(orig []string, varName, newVar string) []string { + envIdx := slices.IndexFunc(orig, func(envVar string) bool { + return strings.HasPrefix(envVar, fmt.Sprintf("%s=", varName)) + }) + + if envIdx != -1 { + return slices.Replace(orig, envIdx, envIdx+1, newVar) + } + return append(orig, newVar) +} diff --git a/pkg/command/nerdctl_test.go b/pkg/command/nerdctl_test.go index addc91091..6cfebc638 100644 --- a/pkg/command/nerdctl_test.go +++ b/pkg/command/nerdctl_test.go @@ -304,8 +304,15 @@ func TestLimaCmdCreator_RunWithReplacingStdout(t *testing.T) { require.NoError(t, err) tc.mockSvc(logger, cmdCreator, lcd, ctrl, tc.inOut, stdoutFile) - assert.Equal(t, tc.wantErr, command.NewNerdctlCmdCreator(cmdCreator, logger, mockLimaHomePath, mockLimactlPath, mockQemuBinPath, lcd). - RunWithReplacingStdout(tc.stdoutRs, mockArgs...)) + assert.Equal(t, tc.wantErr, + command.NewNerdctlCmdCreator( + cmdCreator, + logger, + mockLimaHomePath, + mockLimactlPath, + mockQemuBinPath, + lcd, + ).RunWithReplacingStdout(tc.stdoutRs, mockArgs...)) stdout, err := os.ReadFile(stdoutFilepath) require.NoError(t, err) diff --git a/pkg/config/config.go b/pkg/config/config.go index 4a52dd8f3..0d02ed55c 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -41,8 +41,7 @@ type SharedSettings struct { } // Nerdctl is a copy from github.com/containerd/nerdctl/cmd/nerdctl/main.go -// TODO: make PR to nerdctl repo to move this config out of the main package -// so it can be imported on macOS. +// TODO: this should be importable on macOS once nerdctl v2 is released. type Nerdctl struct { Debug bool `toml:"debug,omitempty"` DebugFull bool `toml:"debug_full1,omitempty"` @@ -161,21 +160,3 @@ func Load( return defCfg, nil } - -// loadFinchConfig Load Finch's configuration from a YAML file. -func loadFinchConfig(fs afero.Fs, finchConfigPath string, logger flog.Logger, systemDeps LoadSystemDeps, mem fmemory.Memory) (*Finch, error) { - b, err := afero.ReadFile(fs, finchConfigPath) - if err != nil { - return nil, fmt.Errorf("failed to read config file: %w", err) - } - - var cfg Finch - if err := yaml.Unmarshal(b, &cfg); err != nil { - return nil, fmt.Errorf("failed to unmarshal config file: %w", err) - } - if err := validate(&cfg, logger, systemDeps, mem); err != nil { - return nil, fmt.Errorf("failed to validate config file: %w", err) - } - - return &cfg, nil -} diff --git a/pkg/config/config_darwin.go b/pkg/config/config_darwin.go index c2f991789..1e38aaea3 100644 --- a/pkg/config/config_darwin.go +++ b/pkg/config/config_darwin.go @@ -11,6 +11,7 @@ import ( "strings" "github.com/spf13/afero" + "gopkg.in/yaml.v3" "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/flog" @@ -93,3 +94,21 @@ func ModifyFinchConfig(fs afero.Fs, logger flog.Logger, finchConfigPath string, return isConfigUpdated, nil } + +// loadFinchConfig Load Finch's configuration from a YAML file. +func loadFinchConfig(fs afero.Fs, finchConfigPath string, logger flog.Logger, systemDeps LoadSystemDeps, mem fmemory.Memory) (*Finch, error) { + b, err := afero.ReadFile(fs, finchConfigPath) + if err != nil { + return nil, fmt.Errorf("failed to read config file: %w", err) + } + + var cfg Finch + if err := yaml.Unmarshal(b, &cfg); err != nil { + return nil, fmt.Errorf("failed to unmarshal config file: %w", err) + } + if err := validate(&cfg, logger, systemDeps, mem); err != nil { + return nil, fmt.Errorf("failed to validate config file: %w", err) + } + + return &cfg, nil +} diff --git a/pkg/config/lima_config_applier.go b/pkg/config/lima_config_applier.go index 8cd8a84e6..8ed13bd47 100644 --- a/pkg/config/lima_config_applier.go +++ b/pkg/config/lima_config_applier.go @@ -1,9 +1,9 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + package config import ( - "github.com/spf13/afero" - - "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/system" ) @@ -15,14 +15,4 @@ type LimaConfigApplierSystemDeps interface { system.RuntimeOSGetter } -type limaConfigApplier struct { - cfg *Finch - cmdCreator command.Creator - fs afero.Fs - limaDefaultConfigPath string - limaOverrideConfigPath string - systemDeps LimaConfigApplierSystemDeps - finchConfigPath string -} - var _ LimaConfigApplier = (*limaConfigApplier)(nil) diff --git a/pkg/config/lima_config_applier_native.go b/pkg/config/lima_config_applier_native.go index 5455e2bb9..c856032cb 100644 --- a/pkg/config/lima_config_applier_native.go +++ b/pkg/config/lima_config_applier_native.go @@ -6,7 +6,6 @@ package config import ( - "github.com/lima-vm/lima/pkg/limayaml" "github.com/spf13/afero" "github.com/runfinch/finch/pkg/command" @@ -36,17 +35,6 @@ func (lca *limaConfigApplier) ConfigureOverrideLimaYaml() error { return nil } -func (lca *limaConfigApplier) configureDefaultSnapshotter(_ *limayaml.LimaYAML) error { - return nil -} - -func (lca *limaConfigApplier) provisionSnapshotters(_ *limayaml.LimaYAML) error { - return nil -} - -func (lca *limaConfigApplier) provisionSociSnapshotter(limaCfg *limayaml.LimaYAML) { -} - func (lca *limaConfigApplier) GetFinchConfigPath() string { return lca.finchConfigPath } diff --git a/pkg/config/nerdctl_config_applier.go b/pkg/config/nerdctl_config_applier.go index f6eb45d42..254a1453c 100644 --- a/pkg/config/nerdctl_config_applier.go +++ b/pkg/config/nerdctl_config_applier.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "path" - "strings" toml "github.com/pelletier/go-toml" "github.com/spf13/afero" @@ -53,17 +52,6 @@ func NewNerdctlApplier( } } -func addLineToBashrc(fs afero.Fs, profileFilePath string, profStr string, cmd string) (string, error) { - if !strings.Contains(profStr, cmd) { - profBufWithCmd := fmt.Sprintf("%s\n%s", profStr, cmd) - if err := afero.WriteFile(fs, profileFilePath, []byte(profBufWithCmd), 0o600); err != nil { - return "", fmt.Errorf("failed to write to profile file: %w", err) - } - return profBufWithCmd, nil - } - return profStr, nil -} - // updateNerdctlConfig reads from the nerdctl config and updates values. func updateNerdctlConfig(fs afero.Fs, homeDir string, rootless bool) error { nerdctlRootlessCfgPath := fmt.Sprintf("%s/.config/nerdctl/nerdctl.toml", homeDir) diff --git a/pkg/config/nerdctl_config_applier_native.go b/pkg/config/nerdctl_config_applier_native.go index 6198f8de2..d81da4b08 100644 --- a/pkg/config/nerdctl_config_applier_native.go +++ b/pkg/config/nerdctl_config_applier_native.go @@ -1,11 +1,26 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + //go:build linux || native package config import ( "github.com/spf13/afero" + + "github.com/runfinch/finch/pkg/command" ) +type limaConfigApplier struct { + _ *Finch + _ command.Creator + _ afero.Fs + _ string + _ string + _ LimaConfigApplierSystemDeps + finchConfigPath string +} + const nerdctlRootfulCfgPath = "/etc/finch/nerdctl/nerdctl.toml" func (nca *nerdctlConfigApplier) nerdctlFs(hostFs afero.Fs, _ string, _ string) (afero.Fs, error) { diff --git a/pkg/config/nerdctl_config_applier_remote.go b/pkg/config/nerdctl_config_applier_remote.go index a7584f418..3bcb90929 100644 --- a/pkg/config/nerdctl_config_applier_remote.go +++ b/pkg/config/nerdctl_config_applier_remote.go @@ -1,3 +1,6 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + //go:build (darwin || windows) && !native package config @@ -11,9 +14,20 @@ import ( "github.com/spf13/afero" "github.com/spf13/afero/sftpfs" + "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/fssh" ) +type limaConfigApplier struct { + cfg *Finch + cmdCreator command.Creator + fs afero.Fs + limaDefaultConfigPath string + limaOverrideConfigPath string + systemDeps LimaConfigApplierSystemDeps + finchConfigPath string +} + const nerdctlRootfulCfgPath = "/etc/nerdctl/nerdctl.toml" func (nca *nerdctlConfigApplier) nerdctlFs(hostFs afero.Fs, privateKeyPath string, remoteAddr string) (afero.Fs, error) { @@ -119,3 +133,14 @@ func getHomeDir(localFs afero.Fs, remoteFs afero.Fs, limaInstanceDir string, cfg return "/home/" + user + ".linux", nil } + +func addLineToBashrc(fs afero.Fs, profileFilePath string, profStr string, cmd string) (string, error) { + if !strings.Contains(profStr, cmd) { + profBufWithCmd := fmt.Sprintf("%s\n%s", profStr, cmd) + if err := afero.WriteFile(fs, profileFilePath, []byte(profBufWithCmd), 0o600); err != nil { + return "", fmt.Errorf("failed to write to profile file: %w", err) + } + return profBufWithCmd, nil + } + return profStr, nil +} diff --git a/pkg/disk/disk_native.go b/pkg/disk/disk_native.go index 7fc13d506..9fcf009c9 100644 --- a/pkg/disk/disk_native.go +++ b/pkg/disk/disk_native.go @@ -15,11 +15,3 @@ func (m *userDataDiskManager) EnsureUserDataDisk() error { func (m *userDataDiskManager) DetachUserDataDisk() error { return nil } - -func (m *userDataDiskManager) createDisk(_ string) error { - return nil -} - -func (m *userDataDiskManager) attachDisk(_ string) error { - return nil -} From b6a070b4eaefed0bb1cfd5b210ff9770bcd2f3ac Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Thu, 25 Jul 2024 14:37:58 -0400 Subject: [PATCH 11/37] refactor to use standard Linux config path Signed-off-by: Justin Alvarez --- cmd/finch/main.go | 8 +- cmd/finch/main_local.go | 23 ++++ cmd/finch/main_remote.go | 23 ++++ pkg/path/finch.go | 96 +---------------- pkg/path/finch_native_linux.go | 35 ++++++ pkg/path/finch_remote.go | 101 ++++++++++++++++++ .../{finch_unix.go => finch_remote_darwin.go} | 3 +- ...nch_windows.go => finch_remote_windows.go} | 1 - pkg/path/finch_test.go | 2 + 9 files changed, 187 insertions(+), 105 deletions(-) create mode 100644 cmd/finch/main_local.go create mode 100644 cmd/finch/main_remote.go create mode 100644 pkg/path/finch_native_linux.go create mode 100644 pkg/path/finch_remote.go rename pkg/path/{finch_unix.go => finch_remote_darwin.go} (90%) rename pkg/path/{finch_windows.go => finch_remote_windows.go} (98%) diff --git a/cmd/finch/main.go b/cmd/finch/main.go index f596f148d..d02d0a87f 100644 --- a/cmd/finch/main.go +++ b/cmd/finch/main.go @@ -111,13 +111,7 @@ var newApp = func( return nil } - ncc := command.NewNerdctlCmdCreator(ecc, - logger, - fp.LimaHomePath(), - fp.LimactlPath(), - fp.QEMUBinDir(), - system.NewStdLib(), - ) + ncc := nerdctlCmdCreator(ecc, logger, fp) lima := wrapper.NewLimaWrapper() supportBundleBuilder := support.NewBundleBuilder( logger, diff --git a/cmd/finch/main_local.go b/cmd/finch/main_local.go new file mode 100644 index 000000000..26e0ddb58 --- /dev/null +++ b/cmd/finch/main_local.go @@ -0,0 +1,23 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux + +package main + +import ( + "github.com/runfinch/finch/pkg/command" + "github.com/runfinch/finch/pkg/flog" + "github.com/runfinch/finch/pkg/path" + "github.com/runfinch/finch/pkg/system" +) + +func nerdctlCmdCreator(ecc command.Creator, logger flog.Logger, _ path.Finch) command.NerdctlCmdCreator { + return command.NewNerdctlCmdCreator(ecc, + logger, + "", + "", + "", + system.NewStdLib(), + ) +} diff --git a/cmd/finch/main_remote.go b/cmd/finch/main_remote.go new file mode 100644 index 000000000..4e00509fb --- /dev/null +++ b/cmd/finch/main_remote.go @@ -0,0 +1,23 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build (darwin || windows) && !native + +package main + +import ( + "github.com/runfinch/finch/pkg/command" + "github.com/runfinch/finch/pkg/flog" + "github.com/runfinch/finch/pkg/path" + "github.com/runfinch/finch/pkg/system" +) + +func nerdctlCmdCreator(ecc command.Creator, logger flog.Logger, fp path.Finch) command.NerdctlCmdCreator { + return command.NewNerdctlCmdCreator(ecc, + logger, + fp.LimaHomePath(), + fp.LimactlPath(), + fp.QEMUBinDir(), + system.NewStdLib(), + ) +} diff --git a/pkg/path/finch.go b/pkg/path/finch.go index b8b60eff1..340b740b8 100644 --- a/pkg/path/finch.go +++ b/pkg/path/finch.go @@ -4,89 +4,11 @@ // Package path contains functions to find/calculate path used in the project. package path -import ( - "crypto/sha256" - "fmt" - "path/filepath" - "runtime" - - "github.com/runfinch/finch/pkg/system" -) +import "github.com/runfinch/finch/pkg/system" // Finch provides a set of methods that calculate paths relative to the Finch path. type Finch string -// FinchDir returns the path to the Finch config directory. -func (Finch) FinchDir(rootDir string) string { - return filepath.Join(rootDir, ".finch") -} - -// ConfigFilePath returns the path to Finch config file. -func (Finch) ConfigFilePath(rootDir string) string { - return filepath.Join(rootDir, ".finch", "finch.yaml") -} - -// UserDataDiskPath returns the path to the permanent storage location of the Finch -// user data disk. -func (w Finch) UserDataDiskPath(rootDir string) string { - disksPath := filepath.Join(rootDir, ".finch", ".disks") - if runtime.GOOS == "windows" { - return filepath.Join(disksPath, w.generatePathSum()+".vhdx") - } - return filepath.Join(disksPath, w.generatePathSum()) -} - -// LimaHomePath returns the path that should be set to LIMA_HOME for Finch. -func (w Finch) LimaHomePath() string { - return filepath.Join(string(w), "lima", "data") -} - -// LimaInstancePath returns the path to the Lima instance of the Finch VM. -func (w Finch) LimaInstancePath() string { - return filepath.Join(string(w), "lima", "data", "finch") -} - -// LimactlPath returns the limactl path. -func (w Finch) LimactlPath() string { - return filepath.Join(string(w), "lima", "bin", "limactl") -} - -// QEMUBinDir returns the path to the directory that contains all the binaries QEMU depends on. -// It's used to enable users to always use the pinned versions of the binaries. -func (w Finch) QEMUBinDir() string { - return filepath.Join(string(w), "lima", "bin") -} - -// BaseYamlFilePath returns the base yaml file path. -func (w Finch) BaseYamlFilePath() string { - return filepath.Join(string(w), "os", "finch.yaml") -} - -// LimaConfigDirectoryPath returns the lima config directory path. -func (w Finch) LimaConfigDirectoryPath() string { - return filepath.Join(string(w), "lima", "data", "_config") -} - -// LimaDefaultConfigPath returns the lima override config file path. -func (w Finch) LimaDefaultConfigPath() string { - return filepath.Join(string(w), "lima", "data", "_config", "default.yaml") -} - -// LimaOverrideConfigPath returns the lima override config file path. -func (w Finch) LimaOverrideConfigPath() string { - return filepath.Join(string(w), "lima", "data", "_config", "override.yaml") -} - -// LimaSSHPrivateKeyPath returns the lima user key path. -func (w Finch) LimaSSHPrivateKeyPath() string { - return filepath.Join(string(w), "lima", "data", "_config", "user") -} - -func (w Finch) generatePathSum() string { - sum := sha256.Sum256([]byte(w.LimaInstancePath())) - return fmt.Sprintf("%x", sum[:8]) -} - // FinchFinderDeps provides all the dependencies FindFinch needs to find Finch. // //go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/finch_finder_deps.go -package=mocks -mock_names FinchFinderDeps=FinchFinderDeps . FinchFinderDeps @@ -97,19 +19,3 @@ type FinchFinderDeps interface { system.EnvGetter system.UserHomeDir } - -// FindFinch finds the installation path of Finch. -func FindFinch(deps FinchFinderDeps) (Finch, error) { - exe, err := deps.Executable() - if err != nil { - return "", fmt.Errorf("failed to locate the executable that starts this process: %w", err) - } - realPath, err := deps.EvalSymlinks(exe) - if err != nil { - return "", fmt.Errorf("failed to find the real path of the executable: %w", err) - } - // The directory structure is finch_home/bin/finch, - // where the last path comment (i.e., finch) is the executable that starts this process. - res := deps.FilePathJoin(realPath, "..", "..") - return Finch(res), nil -} diff --git a/pkg/path/finch_native_linux.go b/pkg/path/finch_native_linux.go new file mode 100644 index 000000000..b20f7eae5 --- /dev/null +++ b/pkg/path/finch_native_linux.go @@ -0,0 +1,35 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux + +package path + +import ( + "fmt" + "path/filepath" +) + +// FinchRootDir returns the path to the Finch root directory, which is $HOME on UNIX. +func (Finch) FinchRootDir(_ FinchFinderDeps) (string, error) { + return filepath.Join("etc", "finch"), nil +} + +// FinchDir returns the path to the Finch config directory. +func (Finch) FinchDir(rootDir string) string { + return filepath.Join(rootDir) +} + +// ConfigFilePath returns the path to Finch config file. +func (Finch) ConfigFilePath(rootDir string) string { + return filepath.Join(rootDir, "finch.yaml") +} + +// FindFinch finds the installation path of Finch. +func FindFinch(deps FinchFinderDeps) (Finch, error) { + exe, err := deps.Executable() + if err != nil { + return "", fmt.Errorf("failed to locate the executable that starts this process: %w", err) + } + return Finch(exe), nil +} diff --git a/pkg/path/finch_remote.go b/pkg/path/finch_remote.go new file mode 100644 index 000000000..edaab0218 --- /dev/null +++ b/pkg/path/finch_remote.go @@ -0,0 +1,101 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build (darwin || windows) && !native + +// Package path contains functions to find/calculate path used in the project. +package path + +import ( + "crypto/sha256" + "fmt" + "path/filepath" + "runtime" +) + +// FinchDir returns the path to the Finch config directory. +func (Finch) FinchDir(rootDir string) string { + return filepath.Join(rootDir, ".finch") +} + +// ConfigFilePath returns the path to Finch config file. +func (Finch) ConfigFilePath(rootDir string) string { + return filepath.Join(rootDir, ".finch", "finch.yaml") +} + +// UserDataDiskPath returns the path to the permanent storage location of the Finch +// user data disk. +func (w Finch) UserDataDiskPath(rootDir string) string { + disksPath := filepath.Join(rootDir, ".finch", ".disks") + if runtime.GOOS == "windows" { + return filepath.Join(disksPath, w.generatePathSum()+".vhdx") + } + return filepath.Join(disksPath, w.generatePathSum()) +} + +// LimaHomePath returns the path that should be set to LIMA_HOME for Finch. +func (w Finch) LimaHomePath() string { + return filepath.Join(string(w), "lima", "data") +} + +// LimaInstancePath returns the path to the Lima instance of the Finch VM. +func (w Finch) LimaInstancePath() string { + return filepath.Join(string(w), "lima", "data", "finch") +} + +// LimactlPath returns the limactl path. +func (w Finch) LimactlPath() string { + return filepath.Join(string(w), "lima", "bin", "limactl") +} + +// QEMUBinDir returns the path to the directory that contains all the binaries QEMU depends on. +// It's used to enable users to always use the pinned versions of the binaries. +func (w Finch) QEMUBinDir() string { + return filepath.Join(string(w), "lima", "bin") +} + +// BaseYamlFilePath returns the base yaml file path. +func (w Finch) BaseYamlFilePath() string { + return filepath.Join(string(w), "os", "finch.yaml") +} + +// LimaConfigDirectoryPath returns the lima config directory path. +func (w Finch) LimaConfigDirectoryPath() string { + return filepath.Join(string(w), "lima", "data", "_config") +} + +// LimaDefaultConfigPath returns the lima override config file path. +func (w Finch) LimaDefaultConfigPath() string { + return filepath.Join(string(w), "lima", "data", "_config", "default.yaml") +} + +// LimaOverrideConfigPath returns the lima override config file path. +func (w Finch) LimaOverrideConfigPath() string { + return filepath.Join(string(w), "lima", "data", "_config", "override.yaml") +} + +// LimaSSHPrivateKeyPath returns the lima user key path. +func (w Finch) LimaSSHPrivateKeyPath() string { + return filepath.Join(string(w), "lima", "data", "_config", "user") +} + +func (w Finch) generatePathSum() string { + sum := sha256.Sum256([]byte(w.LimaInstancePath())) + return fmt.Sprintf("%x", sum[:8]) +} + +// FindFinch finds the installation path of Finch. +func FindFinch(deps FinchFinderDeps) (Finch, error) { + exe, err := deps.Executable() + if err != nil { + return "", fmt.Errorf("failed to locate the executable that starts this process: %w", err) + } + realPath, err := deps.EvalSymlinks(exe) + if err != nil { + return "", fmt.Errorf("failed to find the real path of the executable: %w", err) + } + // The directory structure is finch_home/bin/finch, + // where the last path comment (i.e., finch) is the executable that starts this process. + res := deps.FilePathJoin(realPath, "..", "..") + return Finch(res), nil +} diff --git a/pkg/path/finch_unix.go b/pkg/path/finch_remote_darwin.go similarity index 90% rename from pkg/path/finch_unix.go rename to pkg/path/finch_remote_darwin.go index 164018a54..86ba857ca 100644 --- a/pkg/path/finch_unix.go +++ b/pkg/path/finch_remote_darwin.go @@ -1,8 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows -// +build !windows +//go:build darwin package path diff --git a/pkg/path/finch_windows.go b/pkg/path/finch_remote_windows.go similarity index 98% rename from pkg/path/finch_windows.go rename to pkg/path/finch_remote_windows.go index 599401824..3663bfb73 100644 --- a/pkg/path/finch_windows.go +++ b/pkg/path/finch_remote_windows.go @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 //go:build windows -// +build windows package path diff --git a/pkg/path/finch_test.go b/pkg/path/finch_test.go index db462d3f3..2b2230da5 100644 --- a/pkg/path/finch_test.go +++ b/pkg/path/finch_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package path import ( From 6e4ab1bfe95f98c29903054aa96a761afa87d224 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Thu, 25 Jul 2024 14:38:14 -0400 Subject: [PATCH 12/37] update docs Signed-off-by: Justin Alvarez --- pkg/command/nerdctl.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pkg/command/nerdctl.go b/pkg/command/nerdctl.go index 84974550b..e8af7454c 100644 --- a/pkg/command/nerdctl.go +++ b/pkg/command/nerdctl.go @@ -48,7 +48,7 @@ type nerdctlCmdCreator struct { var _ NerdctlCmdCreator = (*nerdctlCmdCreator)(nil) -// NerdctlCmdCreatorSystemDeps contains the system dependencies for NewLimaCmdCreator. +// NerdctlCmdCreatorSystemDeps contains the system dependencies for NewNerdctlCmdCreator. // //go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/nerdctl_cmd_creator_system_deps.go -package=mocks -mock_names NerdctlCmdCreatorSystemDeps=NerdctlCmdCreatorSystemDeps . NerdctlCmdCreatorSystemDeps type NerdctlCmdCreatorSystemDeps interface { @@ -59,7 +59,9 @@ type NerdctlCmdCreatorSystemDeps interface { system.EnvGetter } -// NewNerdctlCmdCreator returns a LimaCmdCreator that creates limactl commands based on the provided lima-related paths. +// NewNerdctlCmdCreator returns a NerdctlCmdCreator that creates nerdctl commands. +// In "remote" mode, it uses limactl commands, configured to use binaries at lima-related paths and then executes nerdctl. +// In "native" mode, it directly executes nerdctl from the user's PATH. func NewNerdctlCmdCreator( cmdCreator Creator, logger flog.Logger, From 0712bcd9f43ee3edf3af971f5f53a204148c9d23 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Thu, 25 Jul 2024 14:38:28 -0400 Subject: [PATCH 13/37] fix shared settings not being inlined Signed-off-by: Justin Alvarez --- pkg/config/config_native.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/config/config_native.go b/pkg/config/config_native.go index e9769f25a..31e4642b3 100644 --- a/pkg/config/config_native.go +++ b/pkg/config/config_native.go @@ -7,5 +7,5 @@ package config // Finch represents the configuration file for Finch CLI. type Finch struct { - SharedSettings + SharedSettings `yaml:",inline"` } From eec59bf0c6d97b5b4d99498665122c1b4a7042d5 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Thu, 25 Jul 2024 14:38:58 -0400 Subject: [PATCH 14/37] refactor support bundles to only export files that would be relevant on Linux Signed-off-by: Justin Alvarez --- pkg/support/config.go | 23 ---------------------- pkg/support/config_native_linux.go | 18 +++++++++++++++++ pkg/support/config_remote.go | 31 ++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 23 deletions(-) create mode 100644 pkg/support/config_native_linux.go create mode 100644 pkg/support/config_remote.go diff --git a/pkg/support/config.go b/pkg/support/config.go index b636063ec..9d9a6f762 100644 --- a/pkg/support/config.go +++ b/pkg/support/config.go @@ -4,10 +4,6 @@ package support import ( - "path" - "path/filepath" - "runtime" - fpath "github.com/runfinch/finch/pkg/path" ) @@ -31,22 +27,3 @@ func NewBundleConfig(finch fpath.Finch, homeDir string) BundleConfig { homeDir: homeDir, } } - -func (bc *bundleConfig) LogFiles() []string { - files := []string{ - filepath.Join(bc.finch.LimaInstancePath(), "ha.stderr.log"), - filepath.Join(bc.finch.LimaInstancePath(), "ha.stdout.log"), - } - - if runtime.GOOS != "windows" { - files = append(files, filepath.Join(bc.finch.LimaInstancePath(), "serial.log")) - } - return files -} - -func (bc *bundleConfig) ConfigFiles() []string { - return []string{ - path.Join(bc.finch.LimaInstancePath(), "lima.yaml"), - bc.finch.ConfigFilePath(bc.homeDir), - } -} diff --git a/pkg/support/config_native_linux.go b/pkg/support/config_native_linux.go new file mode 100644 index 000000000..2257f26a5 --- /dev/null +++ b/pkg/support/config_native_linux.go @@ -0,0 +1,18 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build linux + +package support + +func (bc *bundleConfig) LogFiles() []string { + // TODO: add support for dumping logs from journalctl? + files := []string{} + return files +} + +func (bc *bundleConfig) ConfigFiles() []string { + return []string{ + bc.finch.ConfigFilePath(bc.homeDir), + } +} diff --git a/pkg/support/config_remote.go b/pkg/support/config_remote.go new file mode 100644 index 000000000..eeaa28fd5 --- /dev/null +++ b/pkg/support/config_remote.go @@ -0,0 +1,31 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build (darwin || windows) && !native + +package support + +import ( + "path" + "path/filepath" + "runtime" +) + +func (bc *bundleConfig) LogFiles() []string { + files := []string{ + filepath.Join(bc.finch.LimaInstancePath(), "ha.stderr.log"), + filepath.Join(bc.finch.LimaInstancePath(), "ha.stdout.log"), + } + + if runtime.GOOS != "windows" { + files = append(files, filepath.Join(bc.finch.LimaInstancePath(), "serial.log")) + } + return files +} + +func (bc *bundleConfig) ConfigFiles() []string { + return []string{ + path.Join(bc.finch.LimaInstancePath(), "lima.yaml"), + bc.finch.ConfigFilePath(bc.homeDir), + } +} From 8b454e7831199d56726c262a70e7015518f87d3a Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Thu, 25 Jul 2024 14:39:11 -0400 Subject: [PATCH 15/37] update build guards Signed-off-by: Justin Alvarez --- pkg/dependency/vmnet/binaries_unix.go | 2 +- pkg/dependency/vmnet/binaries_unix_test.go | 3 +-- pkg/dependency/vmnet/sudoers_file_unix.go | 2 +- pkg/dependency/vmnet/sudoers_file_unix_test.go | 3 +-- pkg/dependency/vmnet/update_network_lima_config_unix.go | 2 +- pkg/dependency/vmnet/update_network_lima_config_unix_test.go | 3 +-- pkg/dependency/vmnet/vmnet_unix.go | 2 +- pkg/dependency/vmnet/vmnet_unix_test.go | 3 +-- 8 files changed, 8 insertions(+), 12 deletions(-) diff --git a/pkg/dependency/vmnet/binaries_unix.go b/pkg/dependency/vmnet/binaries_unix.go index 799427ac6..10c1659d3 100644 --- a/pkg/dependency/vmnet/binaries_unix.go +++ b/pkg/dependency/vmnet/binaries_unix.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows +//go:build darwin && !native package vmnet diff --git a/pkg/dependency/vmnet/binaries_unix_test.go b/pkg/dependency/vmnet/binaries_unix_test.go index 55b80bd3a..d68872cff 100644 --- a/pkg/dependency/vmnet/binaries_unix_test.go +++ b/pkg/dependency/vmnet/binaries_unix_test.go @@ -1,8 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows -// +build !windows +//go:build darwin && !native // Ensures that the binaries required for networking are installed in a privileged location. // More information here: https://github.com/lima-vm/socket_vmnet diff --git a/pkg/dependency/vmnet/sudoers_file_unix.go b/pkg/dependency/vmnet/sudoers_file_unix.go index e2d125fca..9c81048dc 100644 --- a/pkg/dependency/vmnet/sudoers_file_unix.go +++ b/pkg/dependency/vmnet/sudoers_file_unix.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows +//go:build darwin && !native package vmnet diff --git a/pkg/dependency/vmnet/sudoers_file_unix_test.go b/pkg/dependency/vmnet/sudoers_file_unix_test.go index 5a656be55..0a19ea537 100644 --- a/pkg/dependency/vmnet/sudoers_file_unix_test.go +++ b/pkg/dependency/vmnet/sudoers_file_unix_test.go @@ -1,8 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows -// +build !windows +//go:build darwin && !native // Ensures that output of `lima sudoers` is output to the correct directory. // This is necessary for networking to work without prompting the user diff --git a/pkg/dependency/vmnet/update_network_lima_config_unix.go b/pkg/dependency/vmnet/update_network_lima_config_unix.go index e68107b14..9235ef72d 100644 --- a/pkg/dependency/vmnet/update_network_lima_config_unix.go +++ b/pkg/dependency/vmnet/update_network_lima_config_unix.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows +//go:build darwin && !native package vmnet diff --git a/pkg/dependency/vmnet/update_network_lima_config_unix_test.go b/pkg/dependency/vmnet/update_network_lima_config_unix_test.go index c7fba4b02..0ec5941f8 100644 --- a/pkg/dependency/vmnet/update_network_lima_config_unix_test.go +++ b/pkg/dependency/vmnet/update_network_lima_config_unix_test.go @@ -1,8 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows -// +build !windows +//go:build darwin && !native package vmnet diff --git a/pkg/dependency/vmnet/vmnet_unix.go b/pkg/dependency/vmnet/vmnet_unix.go index 13363bd7e..21f299d07 100644 --- a/pkg/dependency/vmnet/vmnet_unix.go +++ b/pkg/dependency/vmnet/vmnet_unix.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows +//go:build darwin && !native // Package vmnet handles installation and configuration of dependencies needed for Lima's managed networking // and port-forwarding to work, with minimal user interaction. diff --git a/pkg/dependency/vmnet/vmnet_unix_test.go b/pkg/dependency/vmnet/vmnet_unix_test.go index f7c46f4aa..d20dbcfee 100644 --- a/pkg/dependency/vmnet/vmnet_unix_test.go +++ b/pkg/dependency/vmnet/vmnet_unix_test.go @@ -1,8 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows -// +build !windows +//go:build darwin && !native package vmnet From 6fbb0ecef8d0d9fb4aa54f8479210aa91899bbd5 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Thu, 25 Jul 2024 17:28:31 -0400 Subject: [PATCH 16/37] fix FinchRootDir Signed-off-by: Justin Alvarez --- pkg/path/finch_native_linux.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/path/finch_native_linux.go b/pkg/path/finch_native_linux.go index b20f7eae5..e4a610754 100644 --- a/pkg/path/finch_native_linux.go +++ b/pkg/path/finch_native_linux.go @@ -12,12 +12,12 @@ import ( // FinchRootDir returns the path to the Finch root directory, which is $HOME on UNIX. func (Finch) FinchRootDir(_ FinchFinderDeps) (string, error) { - return filepath.Join("etc", "finch"), nil + return filepath.Join("/", "etc", "finch"), nil } // FinchDir returns the path to the Finch config directory. func (Finch) FinchDir(rootDir string) string { - return filepath.Join(rootDir) + return rootDir } // ConfigFilePath returns the path to Finch config file. From 5f0d7cf4942e697e834b2a2f4b391e4bdeddd2ae Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Thu, 25 Jul 2024 17:28:52 -0400 Subject: [PATCH 17/37] refactor cmd/nerdctl for Linux Signed-off-by: Justin Alvarez --- cmd/finch/nerdctl.go | 193 ----------------------------------- cmd/finch/nerdctl_native.go | 41 ++++++-- cmd/finch/nerdctl_remote.go | 194 ++++++++++++++++++++++++++++++++++++ 3 files changed, 225 insertions(+), 203 deletions(-) diff --git a/cmd/finch/nerdctl.go b/cmd/finch/nerdctl.go index 388b0b9c8..c19bbe0b4 100644 --- a/cmd/finch/nerdctl.go +++ b/cmd/finch/nerdctl.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "path/filepath" - "runtime" "strings" "golang.org/x/exp/slices" @@ -25,8 +24,6 @@ import ( "k8s.io/apimachinery/pkg/util/sets" ) -const nerdctlCmdName = "nerdctl" - // NerdctlCommandSystemDeps contains the system dependencies for newNerdctlCommand. // //go:generate mockgen -copyright_file=../../copyright_header -destination=../../pkg/mocks/nerdctl_cmd_system_deps.go -package=mocks -mock_names NerdctlCommandSystemDeps=NerdctlCommandSystemDeps -source=nerdctl.go NerdctlCommandSystemDeps @@ -101,196 +98,6 @@ func (nc *nerdctlCommand) runAdapter(cmd *cobra.Command, args []string) error { return nc.run(cmd.Name(), args) } -func (nc *nerdctlCommand) run(cmdName string, args []string) error { - err := nc.assertVMIsRunning(nc.ncc, nc.logger) - if err != nil { - return err - } - var ( - nerdctlArgs, envs, fileEnvs []string - skip, hasCmdHander, hasArgHandler bool - cmdHandler commandHandler - aMap map[string]argHandler - envArgPos int - isDebug int - ) - - alias, hasAlias := aliasMap[cmdName] - if hasAlias { - cmdName = alias - cmdHandler, hasCmdHander = commandHandlerMap[alias] - aMap, hasArgHandler = argHandlerMap[alias] - } else { - // Check if the command has a handler - cmdHandler, hasCmdHander = commandHandlerMap[cmdName] - aMap, hasArgHandler = argHandlerMap[cmdName] - - if !hasCmdHander && !hasArgHandler && len(args) > 0 { - // for commands like image build, container run - key := fmt.Sprintf("%s %s", cmdName, args[0]) - cmdHandler, hasCmdHander = commandHandlerMap[key] - aMap, hasArgHandler = argHandlerMap[key] - } - } - - // First check if the command has command handler - if hasCmdHander { - err := cmdHandler(nc.systemDeps, args) - if err != nil { - return err - } - } - - // envArgPos is used to preserve the position of first environment parameter - envArgPos = -1 - // if a debug flag is passed before env arg pos we reduce the env arg pos by 1 to account for skipping debug flag - isDebug = 0 - for i, arg := range args { - // Check if command requires arg handling - if hasArgHandler { - // Check if argument for the command needs handling, sometimes it can be --file= - b, _, _ := strings.Cut(arg, "=") - h, ok := aMap[b] - if ok { - err = h(nc.systemDeps, args, i) - if err != nil { - return err - } - // This is required when the positional argument at i is mutated by argHandler, eg -v=C:\Users:/tmp:ro - arg = args[i] - } - } - // parsing environment values from the command line may pre-fetch and - // consume the next argument; this loop variable will skip these pre-consumed - // entries from the command line - if skip { - skip = false - continue - } - switch { - case arg == "--debug": - // explicitly setting log level to avoid `--debug` flag being interpreted as nerdctl command - if envArgPos == -1 { - isDebug = 1 - } - nc.logger.SetLevel(flog.Debug) - case argIsEnv(arg): - if envArgPos == -1 { - envArgPos = i - isDebug - } - shouldSkip, addEnv := handleEnv(nc.systemDeps, arg, args[i+1]) - skip = shouldSkip - if addEnv != "" { - envs = append(envs, addEnv) - } - case strings.HasPrefix(arg, "--env-file"): - if envArgPos == -1 { - envArgPos = i - isDebug - } - - shouldSkip, addEnvs, err := handleEnvFile(nc.fs, nc.systemDeps, arg, args[i+1]) - if err != nil { - return err - } - skip = shouldSkip - fileEnvs = append(fileEnvs, addEnvs...) - case strings.HasPrefix(arg, "--add-host"): - switch arg { - case "--add-host": - args[i+1], err = resolveIP(args[i+1], nc.logger, nc.ecc) - if err != nil { - return err - } - default: - resolvedIP, err := resolveIP(arg[11:], nc.logger, nc.ecc) - if err != nil { - return err - } - arg = fmt.Sprintf("%s%s", arg[0:11], resolvedIP) - } - nerdctlArgs = append(nerdctlArgs, arg) - if err != nil { - return err - } - default: - nerdctlArgs = append(nerdctlArgs, arg) - } - } - - // to handle environment variables properly, we add all entries found via - // env-file includes to the map first and then all command line environment - // flags, making sure that command line overrides environment file options, - // and that later command line flags override earlier ones - envVars := make(map[string]string) - - for _, e := range fileEnvs { - evar, eval, _ := strings.Cut(e, "=") - envVars[evar] = eval - } - for _, e := range envs { - evar, eval, _ := strings.Cut(e, "=") - envVars[evar] = eval - } - - passedEnvs := []string{ - "COSIGN_PASSWORD", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", - "AWS_SESSION_TOKEN", "COMPOSE_FILE", - } - - var passedEnvArgs []string - for _, e := range passedEnvs { - v, b := nc.systemDeps.LookupEnv(e) - if !b { - continue - } - if runtime.GOOS == "windows" && e == "COMPOSE_FILE" { - wslPath, err := convertToWSLPath(nc.systemDeps, v) - if err != nil { - return err - } - v = wslPath - } - passedEnvArgs = append(passedEnvArgs, fmt.Sprintf("%s=%s", e, v)) - } - - var additionalEnv []string - switch cmdName { - case "image": - if slices.Contains(args, "build") || slices.Contains(args, "pull") || slices.Contains(args, "push") { - ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) - } - case "container": - if slices.Contains(args, "run") { - ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) - } - case "build", "pull", "push", "run": - ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) - } - - // Add -E to sudo command in order to preserve existing environment variables, more info: - // https://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo/8633575#8633575 - limaArgs := append(nc.GetCmdArgs(), append(additionalEnv, passedEnvArgs...)...) - - limaArgs = append(limaArgs, append([]string{nerdctlCmdName}, strings.Fields(cmdName)...)...) - - var envArgs []string - for key, val := range envVars { - envArgs = append(envArgs, "-e", fmt.Sprintf("%s=%s", key, val)) - } - if envArgPos > -1 { - nerdctlArgs = append(nerdctlArgs[:envArgPos], append(envArgs, nerdctlArgs[envArgPos:]...)...) - } - // Add -E to sudo command in order to preserve existing environment variables, more info: - // https://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo/8633575#8633575 - limaArgs = append(limaArgs, nerdctlArgs...) - - if nc.shouldReplaceForHelp(cmdName, args) { - return nc.ncc.RunWithReplacingStdout([]command.Replacement{{Source: "nerdctl", Target: "finch"}}, limaArgs...) - } - - return nc.ncc.Create(limaArgs...).Run() -} - // shouldReplaceForHelp returns true if we should replace "nerdctl" with "finch" for the output of the given command. func (nc *nerdctlCommand) shouldReplaceForHelp(cmdName string, args []string) bool { // The implicit help commands mean that if users input "finch" without any args, it will return the help of it. diff --git a/cmd/finch/nerdctl_native.go b/cmd/finch/nerdctl_native.go index 6e68bdfb1..1853ca514 100644 --- a/cmd/finch/nerdctl_native.go +++ b/cmd/finch/nerdctl_native.go @@ -6,10 +6,14 @@ package main import ( + "golang.org/x/exp/slices" + "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/flog" ) +const nerdctlCmdName = "" + var aliasMap = map[string]string{} var argHandlerMap = map[string]map[string]argHandler{} @@ -20,14 +24,31 @@ func (nc *nerdctlCommand) GetCmdArgs() []string { return []string{""} } -func (nc *nerdctlCommand) assertVMIsRunning(_ command.NerdctlCmdCreator, _ flog.Logger) error { - return nil -} - -func resolveIP(_ string, _ flog.Logger, _ command.Creator) (string, error) { - return "0.0.0.0", nil -} - -func convertToWSLPath(_ NerdctlCommandSystemDeps, _ string) (string, error) { - return "", nil +func (nc *nerdctlCommand) run(cmdName string, args []string) error { + var additionalEnv []string + switch cmdName { + case "image": + if slices.Contains(args, "build") || slices.Contains(args, "pull") || slices.Contains(args, "push") { + ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) + } + case "container": + if slices.Contains(args, "run") { + ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) + } + case "build", "pull", "push", "run": + ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) + } + + if nc.shouldReplaceForHelp(cmdName, args) { + return nc.ncc.RunWithReplacingStdout([]command.Replacement{{Source: "nerdctl", Target: "finch"}}, args...) + } + + // eat the debug arg, and set the log level to avoid nerdctl parsing this flag + dbgIdx := slices.Index(args, "--debug") + if dbgIdx >= 0 { + args = append(args[:dbgIdx], args[dbgIdx+1:]...) + nc.logger.SetLevel(flog.Debug) + } + + return nc.ncc.Create(append([]string{cmdName}, args...)...).Run() } diff --git a/cmd/finch/nerdctl_remote.go b/cmd/finch/nerdctl_remote.go index 4fe82511d..bd9d754e5 100644 --- a/cmd/finch/nerdctl_remote.go +++ b/cmd/finch/nerdctl_remote.go @@ -7,12 +7,17 @@ package main import ( "fmt" + "runtime" + "strings" "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/flog" "github.com/runfinch/finch/pkg/lima" + "golang.org/x/exp/slices" ) +const nerdctlCmdName = "nerdctl" + func (nc *nerdctlCommand) assertVMIsRunning(creator command.NerdctlCmdCreator, logger flog.Logger) error { // Extra call to check VM before running nerdctl commands. These are the reasons of not doing message replacing // 1. for the non-help commands, replacing stdout may cause "stdin is not a terminal" error for the commands that need input. @@ -34,3 +39,192 @@ func (nc *nerdctlCommand) assertVMIsRunning(creator command.NerdctlCmdCreator, l return nil } } + +func (nc *nerdctlCommand) run(cmdName string, args []string) error { + err := nc.assertVMIsRunning(nc.ncc, nc.logger) + if err != nil { + return err + } + var ( + nerdctlArgs, envs, fileEnvs []string + skip, hasCmdHander, hasArgHandler bool + cmdHandler commandHandler + aMap map[string]argHandler + envArgPos int + isDebug int + ) + + alias, hasAlias := aliasMap[cmdName] + if hasAlias { + cmdName = alias + cmdHandler, hasCmdHander = commandHandlerMap[alias] + aMap, hasArgHandler = argHandlerMap[alias] + } else { + // Check if the command has a handler + cmdHandler, hasCmdHander = commandHandlerMap[cmdName] + aMap, hasArgHandler = argHandlerMap[cmdName] + + if !hasCmdHander && !hasArgHandler && len(args) > 0 { + // for commands like image build, container run + key := fmt.Sprintf("%s %s", cmdName, args[0]) + cmdHandler, hasCmdHander = commandHandlerMap[key] + aMap, hasArgHandler = argHandlerMap[key] + } + } + + // First check if the command has command handler + if hasCmdHander { + err := cmdHandler(nc.systemDeps, args) + if err != nil { + return err + } + } + + // envArgPos is used to preserve the position of first environment parameter + envArgPos = -1 + // if a debug flag is passed before env arg pos we reduce the env arg pos by 1 to account for skipping debug flag + isDebug = 0 + for i, arg := range args { + // Check if command requires arg handling + if hasArgHandler { + // Check if argument for the command needs handling, sometimes it can be --file= + b, _, _ := strings.Cut(arg, "=") + h, ok := aMap[b] + if ok { + err = h(nc.systemDeps, args, i) + if err != nil { + return err + } + // This is required when the positional argument at i is mutated by argHandler, eg -v=C:\Users:/tmp:ro + arg = args[i] + } + } + // parsing environment values from the command line may pre-fetch and + // consume the next argument; this loop variable will skip these pre-consumed + // entries from the command line + if skip { + skip = false + continue + } + switch { + case arg == "--debug": + // explicitly setting log level to avoid `--debug` flag being interpreted as nerdctl command + if envArgPos == -1 { + isDebug = 1 + } + nc.logger.SetLevel(flog.Debug) + case argIsEnv(arg): + if envArgPos == -1 { + envArgPos = i - isDebug + } + shouldSkip, addEnv := handleEnv(nc.systemDeps, arg, args[i+1]) + skip = shouldSkip + if addEnv != "" { + envs = append(envs, addEnv) + } + case strings.HasPrefix(arg, "--env-file"): + if envArgPos == -1 { + envArgPos = i - isDebug + } + + shouldSkip, addEnvs, err := handleEnvFile(nc.fs, nc.systemDeps, arg, args[i+1]) + if err != nil { + return err + } + skip = shouldSkip + fileEnvs = append(fileEnvs, addEnvs...) + case strings.HasPrefix(arg, "--add-host"): + switch arg { + case "--add-host": + args[i+1], err = resolveIP(args[i+1], nc.logger, nc.ecc) + if err != nil { + return err + } + default: + resolvedIP, err := resolveIP(arg[11:], nc.logger, nc.ecc) + if err != nil { + return err + } + arg = fmt.Sprintf("%s%s", arg[0:11], resolvedIP) + } + nerdctlArgs = append(nerdctlArgs, arg) + if err != nil { + return err + } + default: + nerdctlArgs = append(nerdctlArgs, arg) + } + } + + // to handle environment variables properly, we add all entries found via + // env-file includes to the map first and then all command line environment + // flags, making sure that command line overrides environment file options, + // and that later command line flags override earlier ones + envVars := make(map[string]string) + + for _, e := range fileEnvs { + evar, eval, _ := strings.Cut(e, "=") + envVars[evar] = eval + } + for _, e := range envs { + evar, eval, _ := strings.Cut(e, "=") + envVars[evar] = eval + } + + passedEnvs := []string{ + "COSIGN_PASSWORD", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", + "AWS_SESSION_TOKEN", "COMPOSE_FILE", + } + + var passedEnvArgs []string + for _, e := range passedEnvs { + v, b := nc.systemDeps.LookupEnv(e) + if !b { + continue + } + if runtime.GOOS == "windows" && e == "COMPOSE_FILE" { + wslPath, err := convertToWSLPath(nc.systemDeps, v) + if err != nil { + return err + } + v = wslPath + } + passedEnvArgs = append(passedEnvArgs, fmt.Sprintf("%s=%s", e, v)) + } + + var additionalEnv []string + switch cmdName { + case "image": + if slices.Contains(args, "build") || slices.Contains(args, "pull") || slices.Contains(args, "push") { + ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) + } + case "container": + if slices.Contains(args, "run") { + ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) + } + case "build", "pull", "push", "run": + ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) + } + + // Add -E to sudo command in order to preserve existing environment variables, more info: + // https://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo/8633575#8633575 + limaArgs := append(nc.GetCmdArgs(), append(additionalEnv, passedEnvArgs...)...) + limaArgs = append(limaArgs, append([]string{nerdctlCmdName}, strings.Fields(cmdName)...)...) + var envArgs []string + for key, val := range envVars { + envArgs = append(envArgs, "-e", fmt.Sprintf("%s=%s", key, val)) + } + if envArgPos > -1 { + nerdctlArgs = append(nerdctlArgs[:envArgPos], append(envArgs, nerdctlArgs[envArgPos:]...)...) + } + + // Add -E to sudo command in order to preserve existing environment variables, more info: + // https://stackoverflow.com/questions/8633461/how-to-keep-environment-variables-when-using-sudo/8633575#8633575 + limaArgs = append(limaArgs, nerdctlArgs...) + + if nc.shouldReplaceForHelp(cmdName, args) { + return nc.ncc.RunWithReplacingStdout([]command.Replacement{{Source: "nerdctl", Target: "finch"}}, limaArgs...) + } + + return nc.ncc.Create(limaArgs...).Run() +} From 03e23ef41f1d14a01bf851fdca643e80dc506871 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Thu, 25 Jul 2024 20:21:54 -0400 Subject: [PATCH 18/37] refactor nerdctl to use custom paths for buildkit socket and nerdctl.toml Signed-off-by: Justin Alvarez --- cmd/finch/main.go | 6 +++- cmd/finch/main_local.go | 20 +++++++++++-- cmd/finch/main_remote.go | 7 ++++- pkg/command/nerdctl.go | 33 +++++---------------- pkg/command/nerdctl_native.go | 29 ++++++++++++++++++ pkg/command/nerdctl_remote.go | 23 ++++++++++++++ pkg/command/nerdctl_test.go | 2 ++ pkg/command/nerdctl_unix_test.go | 3 +- pkg/config/lima_config_applier.go | 13 ++++++++ pkg/config/nerdctl_config_applier_native.go | 12 -------- pkg/config/nerdctl_config_applier_remote.go | 11 ------- pkg/path/finch_native_linux.go | 10 +++++++ 12 files changed, 114 insertions(+), 55 deletions(-) diff --git a/cmd/finch/main.go b/cmd/finch/main.go index d02d0a87f..3d7ed3455 100644 --- a/cmd/finch/main.go +++ b/cmd/finch/main.go @@ -111,7 +111,7 @@ var newApp = func( return nil } - ncc := nerdctlCmdCreator(ecc, logger, fp) + ncc := nerdctlCmdCreator(ecc, logger, fp, finchRootPath) lima := wrapper.NewLimaWrapper() supportBundleBuilder := support.NewBundleBuilder( logger, @@ -135,6 +135,10 @@ var newApp = func( rootCmd.AddCommand(allCommands...) + if err := configureNerdctl(fs); err != nil { + logger.Fatal(err) + } + return rootCmd } diff --git a/cmd/finch/main_local.go b/cmd/finch/main_local.go index 26e0ddb58..35d47f716 100644 --- a/cmd/finch/main_local.go +++ b/cmd/finch/main_local.go @@ -6,18 +6,32 @@ package main import ( + "github.com/spf13/afero" + "github.com/runfinch/finch/pkg/command" + "github.com/runfinch/finch/pkg/config" "github.com/runfinch/finch/pkg/flog" "github.com/runfinch/finch/pkg/path" "github.com/runfinch/finch/pkg/system" ) -func nerdctlCmdCreator(ecc command.Creator, logger flog.Logger, _ path.Finch) command.NerdctlCmdCreator { +func nerdctlCmdCreator(ecc command.Creator, logger flog.Logger, fp path.Finch, finchRootPath string) command.NerdctlCmdCreator { return command.NewNerdctlCmdCreator(ecc, logger, + fp.NerdctlConfigFilePath(finchRootPath), + fp.BuildkitSocketPath(finchRootPath), + system.NewStdLib(), + ) +} + +func configureNerdctl(fs afero.Fs) error { + return config.NewNerdctlApplier( + nil, + fs, "", "", "", - system.NewStdLib(), - ) + "", + nil, + ).Apply("") } diff --git a/cmd/finch/main_remote.go b/cmd/finch/main_remote.go index 4e00509fb..a7b0d5bbf 100644 --- a/cmd/finch/main_remote.go +++ b/cmd/finch/main_remote.go @@ -10,9 +10,10 @@ import ( "github.com/runfinch/finch/pkg/flog" "github.com/runfinch/finch/pkg/path" "github.com/runfinch/finch/pkg/system" + "github.com/spf13/afero" ) -func nerdctlCmdCreator(ecc command.Creator, logger flog.Logger, fp path.Finch) command.NerdctlCmdCreator { +func nerdctlCmdCreator(ecc command.Creator, logger flog.Logger, fp path.Finch, _ string) command.NerdctlCmdCreator { return command.NewNerdctlCmdCreator(ecc, logger, fp.LimaHomePath(), @@ -21,3 +22,7 @@ func nerdctlCmdCreator(ecc command.Creator, logger flog.Logger, fp path.Finch) c system.NewStdLib(), ) } + +func configureNerdctl(_ afero.Fs) error { + return nil +} diff --git a/pkg/command/nerdctl.go b/pkg/command/nerdctl.go index e8af7454c..67f222844 100644 --- a/pkg/command/nerdctl.go +++ b/pkg/command/nerdctl.go @@ -38,12 +38,14 @@ type Replacement struct { } type nerdctlCmdCreator struct { - cmdCreator Creator - logger flog.Logger - systemDeps NerdctlCmdCreatorSystemDeps - limaHomePath string - limactlPath string - binPath string + cmdCreator Creator + logger flog.Logger + systemDeps NerdctlCmdCreatorSystemDeps + limaHomePath string + limactlPath string + binPath string + nerdctlConfigPath string + buildkitSocketPath string } var _ NerdctlCmdCreator = (*nerdctlCmdCreator)(nil) @@ -59,25 +61,6 @@ type NerdctlCmdCreatorSystemDeps interface { system.EnvGetter } -// NewNerdctlCmdCreator returns a NerdctlCmdCreator that creates nerdctl commands. -// In "remote" mode, it uses limactl commands, configured to use binaries at lima-related paths and then executes nerdctl. -// In "native" mode, it directly executes nerdctl from the user's PATH. -func NewNerdctlCmdCreator( - cmdCreator Creator, - logger flog.Logger, - limaHomePath, limactlPath string, binPath string, - systemDeps NerdctlCmdCreatorSystemDeps, -) NerdctlCmdCreator { - return &nerdctlCmdCreator{ - cmdCreator: cmdCreator, - logger: logger, - limaHomePath: limaHomePath, - limactlPath: limactlPath, - binPath: binPath, - systemDeps: systemDeps, - } -} - func (ncc *nerdctlCmdCreator) Create(args ...string) Command { return ncc.create(ncc.systemDeps.Stdin(), ncc.systemDeps.Stdout(), ncc.systemDeps.Stderr(), args...) } diff --git a/pkg/command/nerdctl_native.go b/pkg/command/nerdctl_native.go index bdde82d8c..4a6a06141 100644 --- a/pkg/command/nerdctl_native.go +++ b/pkg/command/nerdctl_native.go @@ -6,13 +6,42 @@ package command import ( + "fmt" "io" + + "github.com/runfinch/finch/pkg/flog" ) +// NewNerdctlCmdCreator returns a NerdctlCmdCreator that creates nerdctl commands. +// In "remote" mode, it uses limactl commands, configured to use binaries at lima-related paths and then executes nerdctl. +// In "native" mode, it directly executes nerdctl from the user's PATH. +func NewNerdctlCmdCreator( + cmdCreator Creator, + logger flog.Logger, + nerdctlConfigPath string, + buildkitSocketPath string, + systemDeps NerdctlCmdCreatorSystemDeps, +) NerdctlCmdCreator { + return &nerdctlCmdCreator{ + cmdCreator: cmdCreator, + logger: logger, + nerdctlConfigPath: nerdctlConfigPath, + buildkitSocketPath: buildkitSocketPath, + systemDeps: systemDeps, + } +} + func (ncc *nerdctlCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, args ...string) Command { ncc.logger.Debugf("Creating nerdctl command: ARGUMENTS: %v", args) cmd := ncc.cmdCreator.Create("nerdctl", args...) + env := append( + ncc.systemDeps.Environ(), + fmt.Sprintf("NERDCTL_TOML=%s", ncc.nerdctlConfigPath), + fmt.Sprintf("BUILDKIT_HOST=%s", ncc.buildkitSocketPath), + ) + + cmd.SetEnv(env) cmd.SetStdin(stdin) cmd.SetStdout(stdout) cmd.SetStderr(stderr) diff --git a/pkg/command/nerdctl_remote.go b/pkg/command/nerdctl_remote.go index a9d1ef62f..b9ed148e9 100644 --- a/pkg/command/nerdctl_remote.go +++ b/pkg/command/nerdctl_remote.go @@ -11,6 +11,8 @@ import ( "runtime" "slices" "strings" + + "github.com/runfinch/finch/pkg/flog" ) const ( @@ -19,6 +21,27 @@ const ( envKeyWinPath = "Path" ) +// NewNerdctlCmdCreator returns a NerdctlCmdCreator that creates nerdctl commands. +// In "remote" mode, it uses limactl commands, configured to use binaries at lima-related paths and then executes nerdctl. +// In "native" mode, it directly executes nerdctl from the user's PATH. +func NewNerdctlCmdCreator( + cmdCreator Creator, + logger flog.Logger, + limaHomePath, + limactlPath string, + binPath string, + systemDeps NerdctlCmdCreatorSystemDeps, +) NerdctlCmdCreator { + return &nerdctlCmdCreator{ + cmdCreator: cmdCreator, + logger: logger, + limaHomePath: limaHomePath, + limactlPath: limactlPath, + binPath: binPath, + systemDeps: systemDeps, + } +} + func (ncc *nerdctlCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, args ...string) Command { ncc.logger.Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", args, envKeyLimaHome, ncc.limaHomePath) cmd := ncc.cmdCreator.Create(ncc.limactlPath, args...) diff --git a/pkg/command/nerdctl_test.go b/pkg/command/nerdctl_test.go index 6cfebc638..b41bf7172 100644 --- a/pkg/command/nerdctl_test.go +++ b/pkg/command/nerdctl_test.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + // Package command_test is not named as command to avoid circular dependency (command <-> mocks). package command_test diff --git a/pkg/command/nerdctl_unix_test.go b/pkg/command/nerdctl_unix_test.go index d1b704313..cf0254f5a 100644 --- a/pkg/command/nerdctl_unix_test.go +++ b/pkg/command/nerdctl_unix_test.go @@ -1,8 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build !windows -// +build !windows +//go:build darwin && !native package command_test diff --git a/pkg/config/lima_config_applier.go b/pkg/config/lima_config_applier.go index 8ed13bd47..a813f2c1f 100644 --- a/pkg/config/lima_config_applier.go +++ b/pkg/config/lima_config_applier.go @@ -4,6 +4,9 @@ package config import ( + "github.com/spf13/afero" + + "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/system" ) @@ -15,4 +18,14 @@ type LimaConfigApplierSystemDeps interface { system.RuntimeOSGetter } +type limaConfigApplier struct { + cfg *Finch + cmdCreator command.Creator + fs afero.Fs + limaDefaultConfigPath string + limaOverrideConfigPath string + systemDeps LimaConfigApplierSystemDeps + finchConfigPath string +} + var _ LimaConfigApplier = (*limaConfigApplier)(nil) diff --git a/pkg/config/nerdctl_config_applier_native.go b/pkg/config/nerdctl_config_applier_native.go index d81da4b08..6d4dc0664 100644 --- a/pkg/config/nerdctl_config_applier_native.go +++ b/pkg/config/nerdctl_config_applier_native.go @@ -7,20 +7,8 @@ package config import ( "github.com/spf13/afero" - - "github.com/runfinch/finch/pkg/command" ) -type limaConfigApplier struct { - _ *Finch - _ command.Creator - _ afero.Fs - _ string - _ string - _ LimaConfigApplierSystemDeps - finchConfigPath string -} - const nerdctlRootfulCfgPath = "/etc/finch/nerdctl/nerdctl.toml" func (nca *nerdctlConfigApplier) nerdctlFs(hostFs afero.Fs, _ string, _ string) (afero.Fs, error) { diff --git a/pkg/config/nerdctl_config_applier_remote.go b/pkg/config/nerdctl_config_applier_remote.go index 3bcb90929..8813f88e5 100644 --- a/pkg/config/nerdctl_config_applier_remote.go +++ b/pkg/config/nerdctl_config_applier_remote.go @@ -14,20 +14,9 @@ import ( "github.com/spf13/afero" "github.com/spf13/afero/sftpfs" - "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/fssh" ) -type limaConfigApplier struct { - cfg *Finch - cmdCreator command.Creator - fs afero.Fs - limaDefaultConfigPath string - limaOverrideConfigPath string - systemDeps LimaConfigApplierSystemDeps - finchConfigPath string -} - const nerdctlRootfulCfgPath = "/etc/nerdctl/nerdctl.toml" func (nca *nerdctlConfigApplier) nerdctlFs(hostFs afero.Fs, privateKeyPath string, remoteAddr string) (afero.Fs, error) { diff --git a/pkg/path/finch_native_linux.go b/pkg/path/finch_native_linux.go index e4a610754..dfa52c721 100644 --- a/pkg/path/finch_native_linux.go +++ b/pkg/path/finch_native_linux.go @@ -25,6 +25,16 @@ func (Finch) ConfigFilePath(rootDir string) string { return filepath.Join(rootDir, "finch.yaml") } +// NerdctlConfigFilePath returns the path to Finch config file. +func (Finch) NerdctlConfigFilePath(rootDir string) string { + return filepath.Join(rootDir, "nerdctl", "nerdctl.toml") +} + +// BuildkitSocketPath returns the path to Finch config file. +func (Finch) BuildkitSocketPath(rootDir string) string { + return filepath.Join(rootDir, "buildkit", "buildkitd.toml") +} + // FindFinch finds the installation path of Finch. func FindFinch(deps FinchFinderDeps) (Finch, error) { exe, err := deps.Executable() From 350d07f68cd5400a8813d7d1640ba4fe4c4ad73a Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Fri, 26 Jul 2024 11:38:34 -0400 Subject: [PATCH 19/37] fix linting Signed-off-by: Justin Alvarez --- cmd/finch/main_remote.go | 3 +- cmd/finch/nerdctl.go | 94 -------- cmd/finch/nerdctl_native.go | 12 - cmd/finch/nerdctl_remote.go | 98 ++++++++- pkg/command/nerdctl.go | 12 - pkg/command/nerdctl_native.go | 8 + pkg/command/nerdctl_remote.go | 9 + pkg/config/lima_config_applier.go | 257 ++++++++++++++++++++++ pkg/config/lima_config_applier_native.go | 40 ---- pkg/config/lima_config_applier_remote.go | 267 ----------------------- 10 files changed, 373 insertions(+), 427 deletions(-) delete mode 100644 pkg/config/lima_config_applier_native.go delete mode 100644 pkg/config/lima_config_applier_remote.go diff --git a/cmd/finch/main_remote.go b/cmd/finch/main_remote.go index a7b0d5bbf..5b88e9955 100644 --- a/cmd/finch/main_remote.go +++ b/cmd/finch/main_remote.go @@ -6,11 +6,12 @@ package main import ( + "github.com/spf13/afero" + "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/flog" "github.com/runfinch/finch/pkg/path" "github.com/runfinch/finch/pkg/system" - "github.com/spf13/afero" ) func nerdctlCmdCreator(ecc command.Creator, logger flog.Logger, fp path.Finch, _ string) command.NerdctlCmdCreator { diff --git a/cmd/finch/nerdctl.go b/cmd/finch/nerdctl.go index c19bbe0b4..3c9e786d1 100644 --- a/cmd/finch/nerdctl.go +++ b/cmd/finch/nerdctl.go @@ -4,11 +4,8 @@ package main import ( - "bufio" "encoding/json" "fmt" - "path/filepath" - "strings" "golang.org/x/exp/slices" @@ -44,11 +41,6 @@ type nerdctlCommandCreator struct { fc *config.Finch } -type ( - argHandler func(systemDeps NerdctlCommandSystemDeps, args []string, index int) error - commandHandler func(systemDeps NerdctlCommandSystemDeps, args []string) error -) - func newNerdctlCommandCreator( ncc command.NerdctlCmdCreator, ecc command.Creator, @@ -119,92 +111,6 @@ func (nc *nerdctlCommand) shouldReplaceForHelp(cmdName string, args []string) bo return false } -func argIsEnv(arg string) bool { - if strings.HasPrefix(arg, "-e") || (strings.HasPrefix(arg, "--env") && !strings.HasPrefix(arg, "--env-file")) { - return true - } - return false -} - -func handleEnv(systemDeps NerdctlCommandSystemDeps, arg, arg2 string) (bool, string) { - var ( - envVar string - skip bool - ) - switch arg { - case "-e", "--env": - skip = true - envVar = arg2 - default: - // flag and value are in the same string - if strings.HasPrefix(arg, "-e") { - envVar = arg[2:] - } else { - // only other case is "--env="; skip that prefix - envVar = arg[6:] - } - } - - if strings.Contains(envVar, "=") { - return skip, envVar - } - // if no value was provided we need to check the OS environment - // for a value and only set if it exists in the current env - if val, ok := systemDeps.LookupEnv(envVar); ok { - return skip, fmt.Sprintf("%s=%s", envVar, val) - } - // no value found; do not set the variable in the env - return skip, "" -} - -func handleEnvFile(fs afero.Fs, systemDeps NerdctlCommandSystemDeps, arg, arg2 string) (bool, []string, error) { - var ( - filename string - skip bool - ) - - switch arg { - case "--env-file": - skip = true - filename = arg2 - default: - filename = arg[11:] - } - - file, err := fs.Open(filepath.Clean(filename)) - if err != nil { - return false, []string{}, err - } - defer file.Close() //nolint:errcheck // We did not write to the file, and the file will be closed when the CLI process exits anyway. - - scanner := bufio.NewScanner(file) - - var envs []string - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - if len(line) == 0 { - continue - } - switch { - case strings.HasPrefix(line, "#"): - // ignore comments - continue - case !strings.Contains(line, "="): - // only has the variable name; need to lookup value - if val, ok := systemDeps.LookupEnv(line); ok { - envs = append(envs, fmt.Sprintf("%s=%s", line, val)) - } - default: - // contains a name and value - envs = append(envs, line) - } - } - if err := scanner.Err(); err != nil { - return skip, []string{}, err - } - return skip, envs, nil -} - // ensureRemoteCredentials is called before any actions that may require remote resources, in order // to ensure that fresh credentials are available inside the VM. // For more details on how `aws configure export-credentials` works, checks the docs. diff --git a/cmd/finch/nerdctl_native.go b/cmd/finch/nerdctl_native.go index 1853ca514..cee9cf5e4 100644 --- a/cmd/finch/nerdctl_native.go +++ b/cmd/finch/nerdctl_native.go @@ -12,18 +12,6 @@ import ( "github.com/runfinch/finch/pkg/flog" ) -const nerdctlCmdName = "" - -var aliasMap = map[string]string{} - -var argHandlerMap = map[string]map[string]argHandler{} - -var commandHandlerMap = map[string]commandHandler{} - -func (nc *nerdctlCommand) GetCmdArgs() []string { - return []string{""} -} - func (nc *nerdctlCommand) run(cmdName string, args []string) error { var additionalEnv []string switch cmdName { diff --git a/cmd/finch/nerdctl_remote.go b/cmd/finch/nerdctl_remote.go index bd9d754e5..5f7305708 100644 --- a/cmd/finch/nerdctl_remote.go +++ b/cmd/finch/nerdctl_remote.go @@ -6,18 +6,28 @@ package main import ( + "bufio" "fmt" + "path/filepath" "runtime" "strings" + "golang.org/x/exp/slices" + + "github.com/spf13/afero" + "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/flog" "github.com/runfinch/finch/pkg/lima" - "golang.org/x/exp/slices" ) const nerdctlCmdName = "nerdctl" +type ( + argHandler func(systemDeps NerdctlCommandSystemDeps, args []string, index int) error + commandHandler func(systemDeps NerdctlCommandSystemDeps, args []string) error +) + func (nc *nerdctlCommand) assertVMIsRunning(creator command.NerdctlCmdCreator, logger flog.Logger) error { // Extra call to check VM before running nerdctl commands. These are the reasons of not doing message replacing // 1. for the non-help commands, replacing stdout may cause "stdin is not a terminal" error for the commands that need input. @@ -228,3 +238,89 @@ func (nc *nerdctlCommand) run(cmdName string, args []string) error { return nc.ncc.Create(limaArgs...).Run() } + +func argIsEnv(arg string) bool { + if strings.HasPrefix(arg, "-e") || (strings.HasPrefix(arg, "--env") && !strings.HasPrefix(arg, "--env-file")) { + return true + } + return false +} + +func handleEnv(systemDeps NerdctlCommandSystemDeps, arg, arg2 string) (bool, string) { + var ( + envVar string + skip bool + ) + switch arg { + case "-e", "--env": + skip = true + envVar = arg2 + default: + // flag and value are in the same string + if strings.HasPrefix(arg, "-e") { + envVar = arg[2:] + } else { + // only other case is "--env="; skip that prefix + envVar = arg[6:] + } + } + + if strings.Contains(envVar, "=") { + return skip, envVar + } + // if no value was provided we need to check the OS environment + // for a value and only set if it exists in the current env + if val, ok := systemDeps.LookupEnv(envVar); ok { + return skip, fmt.Sprintf("%s=%s", envVar, val) + } + // no value found; do not set the variable in the env + return skip, "" +} + +func handleEnvFile(fs afero.Fs, systemDeps NerdctlCommandSystemDeps, arg, arg2 string) (bool, []string, error) { + var ( + filename string + skip bool + ) + + switch arg { + case "--env-file": + skip = true + filename = arg2 + default: + filename = arg[11:] + } + + file, err := fs.Open(filepath.Clean(filename)) + if err != nil { + return false, []string{}, err + } + defer file.Close() //nolint:errcheck // We did not write to the file, and the file will be closed when the CLI process exits anyway. + + scanner := bufio.NewScanner(file) + + var envs []string + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if len(line) == 0 { + continue + } + switch { + case strings.HasPrefix(line, "#"): + // ignore comments + continue + case !strings.Contains(line, "="): + // only has the variable name; need to lookup value + if val, ok := systemDeps.LookupEnv(line); ok { + envs = append(envs, fmt.Sprintf("%s=%s", line, val)) + } + default: + // contains a name and value + envs = append(envs, line) + } + } + if err := scanner.Err(); err != nil { + return skip, []string{}, err + } + return skip, envs, nil +} diff --git a/pkg/command/nerdctl.go b/pkg/command/nerdctl.go index 67f222844..e42ce7867 100644 --- a/pkg/command/nerdctl.go +++ b/pkg/command/nerdctl.go @@ -6,7 +6,6 @@ package command import ( "bytes" - "github.com/runfinch/finch/pkg/flog" "github.com/runfinch/finch/pkg/system" ) @@ -37,17 +36,6 @@ type Replacement struct { Source, Target string } -type nerdctlCmdCreator struct { - cmdCreator Creator - logger flog.Logger - systemDeps NerdctlCmdCreatorSystemDeps - limaHomePath string - limactlPath string - binPath string - nerdctlConfigPath string - buildkitSocketPath string -} - var _ NerdctlCmdCreator = (*nerdctlCmdCreator)(nil) // NerdctlCmdCreatorSystemDeps contains the system dependencies for NewNerdctlCmdCreator. diff --git a/pkg/command/nerdctl_native.go b/pkg/command/nerdctl_native.go index 4a6a06141..229ef3b74 100644 --- a/pkg/command/nerdctl_native.go +++ b/pkg/command/nerdctl_native.go @@ -12,6 +12,14 @@ import ( "github.com/runfinch/finch/pkg/flog" ) +type nerdctlCmdCreator struct { + cmdCreator Creator + logger flog.Logger + systemDeps NerdctlCmdCreatorSystemDeps + nerdctlConfigPath string + buildkitSocketPath string +} + // NewNerdctlCmdCreator returns a NerdctlCmdCreator that creates nerdctl commands. // In "remote" mode, it uses limactl commands, configured to use binaries at lima-related paths and then executes nerdctl. // In "native" mode, it directly executes nerdctl from the user's PATH. diff --git a/pkg/command/nerdctl_remote.go b/pkg/command/nerdctl_remote.go index b9ed148e9..d453e2fa0 100644 --- a/pkg/command/nerdctl_remote.go +++ b/pkg/command/nerdctl_remote.go @@ -21,6 +21,15 @@ const ( envKeyWinPath = "Path" ) +type nerdctlCmdCreator struct { + cmdCreator Creator + logger flog.Logger + systemDeps NerdctlCmdCreatorSystemDeps + limaHomePath string + limactlPath string + binPath string +} + // NewNerdctlCmdCreator returns a NerdctlCmdCreator that creates nerdctl commands. // In "remote" mode, it uses limactl commands, configured to use binaries at lima-related paths and then executes nerdctl. // In "native" mode, it directly executes nerdctl from the user's PATH. diff --git a/pkg/config/lima_config_applier.go b/pkg/config/lima_config_applier.go index a813f2c1f..426f7458e 100644 --- a/pkg/config/lima_config_applier.go +++ b/pkg/config/lima_config_applier.go @@ -1,15 +1,88 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build (darwin || windows) && !native + package config import ( + "fmt" + "strings" + + "github.com/lima-vm/lima/pkg/limayaml" "github.com/spf13/afero" + "github.com/xorcare/pointer" + "golang.org/x/exp/slices" + "gopkg.in/yaml.v3" "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/system" ) +const ( + sociVersion = "0.5.0" + sociAMD64Sha256Sum = "768f73dbd2c772386df1d12d0a371e9cbcefebea4856623335a2e8ea5170691c" + sociARM64Sha256Sum = "9238e00426ec67a725d511e232476248f2379d66a4ccab224a50ad4c56a0292e" + snapshotterProvisioningScriptHeader = "# snapshotter provisioning script" + sociInstallationProvisioningScriptHeader = snapshotterProvisioningScriptHeader + ": soci" + sociFileNameFormat = "soci-snapshotter-%s-linux-%s.tar.gz" + sociDownloadURLFormat = "https://github.com/awslabs/soci-snapshotter/releases/download/v%s/%s" + sociServiceDownloadURLFormat = "https://raw.githubusercontent.com/awslabs/soci-snapshotter/v%s/soci-snapshotter.service" + //nolint:lll // command string + sociInstallationScriptFormat = `%s +if [ ! -f /usr/local/bin/soci ]; then + # download soci + set -e + + # pull release tarball + release_tarball="%s" + curl --retry 2 --retry-max-time 120 -OL "%s" + + # validate shasum + (sha256sum "${release_tarball}" | cut -d ' ' -f 1 | grep -xq "^%s$") || \ + (echo "error: shasum verification failed for SOCI release tarball" && rm -f "${release_tarball}" && exit 1) + + # move to usr/local/bin + tar -C /usr/local/bin -xvf ${release_tarball} ./soci ./soci-snapshotter-grpc + + # install as a systemd service + curl --retry 2 --retry-max-time 120 -OL "%s" + mv soci-snapshotter.service /usr/local/lib/systemd/system/ + ln -s /usr/local/lib/systemd/system/soci-snapshotter.service /etc/systemd/system/multi-user.target.wants/ + restorecon -v /usr/local/lib/systemd/system/soci-snapshotter.service + systemctl daemon-reload + sudo mkdir -p /usr/local/lib/systemd/system/soci-snapshotter.service.d/ + printf '[Unit]\nPartOf=containerd.service\n\n[Service]\nKillSignal=SIGTERM\n' | sudo tee /usr/local/lib/systemd/system/soci-snapshotter.service.d/finch.conf + systemctl enable --now soci-snapshotter +fi + +# changing containerd config, this seems to get reset on every VM stop/start +if ! grep -q soci /etc/containerd/config.toml; then + printf ' [proxy_plugins.soci]\n type = "snapshot"\n address = "/run/soci-snapshotter-grpc/soci-snapshotter-grpc.sock"\n' >> /etc/containerd/config.toml +fi + +sudo systemctl restart containerd.service +` + + userModeEmulationProvisioningScriptHeader = "# cross-arch tools" + wslDiskFormatScriptHeader = "# wsl disk format script" + qemuPkgInstallationScript = `%s +#!/bin/bash +qemu_pkgs="" +if [ ! -f /usr/bin/qemu-aarch64-static ]; then + qemu_pkgs="$qemu_pkgs qemu-user-static-aarch64" +elif [ ! -f /usr/bin/qemu-aarch64-static ]; then + qemu_pkgs="$qemu_pkgs qemu-user-static-arm" +elif [ ! -f /usr/bin/qemu-aarch64-static ]; then + qemu_pkgs="$qemu_pkgs qemu-user-static-x86" +fi + +if [[ $qemu_pkgs ]]; then + dnf install -y --setopt=install_weak_deps=False ${qemu_pkgs} +fi +` +) + // LimaConfigApplierSystemDeps contains the system dependencies for LimaConfigApplier. // //go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/pkg_config_lima_config_applier_system_deps.go -package=mocks -mock_names LimaConfigApplierSystemDeps=LimaConfigApplierSystemDeps . LimaConfigApplierSystemDeps @@ -29,3 +102,187 @@ type limaConfigApplier struct { } var _ LimaConfigApplier = (*limaConfigApplier)(nil) + +// NewLimaApplier creates a new LimaConfigApplier that +// applies lima configuration changes by writing to the lima config file on the disk. +func NewLimaApplier( + cfg *Finch, + cmdCreator command.Creator, + fs afero.Fs, + limaDefaultConfigPath string, + limaOverrideConfigPath string, + systemDeps LimaConfigApplierSystemDeps, + finchConfigPath string, +) LimaConfigApplier { + return &limaConfigApplier{ + cfg: cfg, + cmdCreator: cmdCreator, + fs: fs, + limaDefaultConfigPath: limaDefaultConfigPath, + limaOverrideConfigPath: limaOverrideConfigPath, + systemDeps: systemDeps, + finchConfigPath: finchConfigPath, + } +} + +// ConfigureDefaultLimaYaml writes Lima-specific config values from Finch's config to default.yaml at lima config file path. +// ConfigureDefaultLimaYaml will create a default.yaml at the path if it does not exist. +func (lca *limaConfigApplier) ConfigureDefaultLimaYaml() error { + if err := afero.WriteFile(lca.fs, lca.limaDefaultConfigPath, []byte(""), 0o600); err != nil { + return fmt.Errorf("failed to create the an empty lima config file: %w", err) + } + + var limaCfg limayaml.LimaYAML + + if limaCfg.Rosetta.Enabled == nil { + limaCfg.Rosetta.Enabled = pointer.Bool(false) + limaCfg.Rosetta.BinFmt = pointer.Bool(false) + } + + cfgAfterInit, err := lca.configureVirtualizationFramework(&limaCfg) + if err != nil { + return fmt.Errorf("failed to apply init-only config values: %w", err) + } + limaCfg = *cfgAfterInit + + limaCfgBytes, err := yaml.Marshal(limaCfg) + if err != nil { + return fmt.Errorf("failed to marshal the lima config file: %w", err) + } + + if err := afero.WriteFile(lca.fs, lca.limaDefaultConfigPath, limaCfgBytes, 0o600); err != nil { + return fmt.Errorf("failed to write to the lima config file: %w", err) + } + + return nil +} + +// ConfigureOverrideLimaYaml writes Lima-specific config values from Finch's config to override.yaml at lima config file path. +// ConfigureOverrideLimaYaml will create a override.yaml at the path if it does not exist. +func (lca *limaConfigApplier) ConfigureOverrideLimaYaml() error { + if err := afero.WriteFile(lca.fs, lca.limaOverrideConfigPath, []byte(""), 0o600); err != nil { + return fmt.Errorf("failed to create the an empty lima config file: %w", err) + } + var limaCfg limayaml.LimaYAML + + lca.configureCPUs(&limaCfg) + lca.configureMemory(&limaCfg) + lca.configureMounts(&limaCfg) + if *lca.cfg.VMType != "wsl2" && len(limaCfg.AdditionalDisks) == 0 { + limaCfg.AdditionalDisks = append(limaCfg.AdditionalDisks, limayaml.Disk{ + Name: "finch", + }) + } + + err := lca.provisionSnapshotters(&limaCfg) + if err != nil { + return fmt.Errorf("failed to provision snapshotters: %w", err) + } + + err = lca.configureDefaultSnapshotter(&limaCfg) + if err != nil { + return fmt.Errorf("failed to configure default snapshotter: %w", err) + } + + if *lca.cfg.VMType == "wsl2" { + ensureWslDiskFormatScript(&limaCfg) + } + + limaCfgBytes, err := yaml.Marshal(limaCfg) + if err != nil { + return fmt.Errorf("failed to marshal the lima config file: %w", err) + } + + if err := afero.WriteFile(lca.fs, lca.limaOverrideConfigPath, limaCfgBytes, 0o600); err != nil { + return fmt.Errorf("failed to write to the lima config file: %w", err) + } + + return nil +} + +func validateSnapshotter(snapshotter string) error { + supportedSnapshotters := []string{"overlayfs", "soci"} + if !slices.Contains(supportedSnapshotters, snapshotter) { + return fmt.Errorf("snapshotter %s is not supported", snapshotter) + } + return nil +} + +func (lca *limaConfigApplier) configureDefaultSnapshotter(limaCfg *limayaml.LimaYAML) error { + if len(lca.cfg.Snapshotters) == 0 { + limaCfg.Env = map[string]string{} + return nil + } + + snapshotter := lca.cfg.Snapshotters[0] + err := validateSnapshotter(snapshotter) + if err != nil { + return err + } + + limaCfg.Env = map[string]string{"CONTAINERD_SNAPSHOTTER": snapshotter} + + return nil +} + +func (lca *limaConfigApplier) provisionSnapshotters(limaCfg *limayaml.LimaYAML) error { + for _, snapshotter := range lca.cfg.Snapshotters { + switch snapshotter { + case "soci": + lca.provisionSociSnapshotter(limaCfg) + case "overlayfs": + continue + default: + return fmt.Errorf("snapshotter %s is not supported", snapshotter) + } + } + + return nil +} + +func (lca *limaConfigApplier) provisionSociSnapshotter(limaCfg *limayaml.LimaYAML) { + arch := lca.systemDeps.Arch() + sociFileName := fmt.Sprintf(sociFileNameFormat, sociVersion, arch) + sociDownloadURL := fmt.Sprintf(sociDownloadURLFormat, sociVersion, sociFileName) + sociSha256Sum := sociAMD64Sha256Sum + if arch == "arm64" { + sociSha256Sum = sociARM64Sha256Sum + } + sociServiceDownloadURL := fmt.Sprintf(sociServiceDownloadURLFormat, sociVersion) + sociInstallationScript := fmt.Sprintf(sociInstallationScriptFormat, sociInstallationProvisioningScriptHeader, + sociFileName, sociDownloadURL, sociSha256Sum, sociServiceDownloadURL) + limaCfg.Provision = append(limaCfg.Provision, limayaml.Provision{ + Mode: "system", + Script: sociInstallationScript, + }) +} + +func ensureWslDiskFormatScript(limaCfg *limayaml.LimaYAML) { + if hasScript := findWslDiskFormatScript(limaCfg); !hasScript { + limaCfg.Provision = append(limaCfg.Provision, limayaml.Provision{ + Mode: "system", + Script: fmt.Sprintf(`%s +#!/bin/bash +mkdir -p /mnt/lima-finch +mount "$(blkid -s TYPE -t LABEL=FinchDataDisk -o device)" /mnt/lima-finch +`, wslDiskFormatScriptHeader), + }) + } +} + +func findWslDiskFormatScript(limaCfg *limayaml.LimaYAML) bool { + hasWslDiskFormatScript := false + for _, prov := range limaCfg.Provision { + trimmed := strings.Trim(prov.Script, " ") + if !hasWslDiskFormatScript && strings.HasPrefix(trimmed, wslDiskFormatScriptHeader) { + hasWslDiskFormatScript = true + break + } + } + + return hasWslDiskFormatScript +} + +func (lca *limaConfigApplier) GetFinchConfigPath() string { + return lca.finchConfigPath +} diff --git a/pkg/config/lima_config_applier_native.go b/pkg/config/lima_config_applier_native.go deleted file mode 100644 index c856032cb..000000000 --- a/pkg/config/lima_config_applier_native.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -//go:build linux || native - -package config - -import ( - "github.com/spf13/afero" - - "github.com/runfinch/finch/pkg/command" -) - -// NewLimaApplier creates a new LimaConfigApplier that -// applies lima configuration changes by writing to the lima config file on the disk. -func NewLimaApplier( - _ *Finch, - _ command.Creator, - _ afero.Fs, - _ string, - _ string, - _ LimaConfigApplierSystemDeps, - _ string, -) LimaConfigApplier { - return &limaConfigApplier{} -} - -func (lca *limaConfigApplier) ConfigureDefaultLimaYaml() error { - return nil -} - -// ConfigureOverrideLimaYaml writes Lima-specific config values from Finch's config to override.yaml at lima config file path. -// ConfigureOverrideLimaYaml will create a override.yaml at the path if it does not exist. -func (lca *limaConfigApplier) ConfigureOverrideLimaYaml() error { - return nil -} - -func (lca *limaConfigApplier) GetFinchConfigPath() string { - return lca.finchConfigPath -} diff --git a/pkg/config/lima_config_applier_remote.go b/pkg/config/lima_config_applier_remote.go deleted file mode 100644 index 0fc3dd138..000000000 --- a/pkg/config/lima_config_applier_remote.go +++ /dev/null @@ -1,267 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -//go:build (darwin || windows) && !native - -package config - -import ( - "fmt" - "strings" - - "github.com/lima-vm/lima/pkg/limayaml" - "github.com/spf13/afero" - "github.com/xorcare/pointer" - "golang.org/x/exp/slices" - "gopkg.in/yaml.v3" - - "github.com/runfinch/finch/pkg/command" -) - -const ( - sociVersion = "0.5.0" - sociAMD64Sha256Sum = "768f73dbd2c772386df1d12d0a371e9cbcefebea4856623335a2e8ea5170691c" - sociARM64Sha256Sum = "9238e00426ec67a725d511e232476248f2379d66a4ccab224a50ad4c56a0292e" - snapshotterProvisioningScriptHeader = "# snapshotter provisioning script" - sociInstallationProvisioningScriptHeader = snapshotterProvisioningScriptHeader + ": soci" - sociFileNameFormat = "soci-snapshotter-%s-linux-%s.tar.gz" - sociDownloadURLFormat = "https://github.com/awslabs/soci-snapshotter/releases/download/v%s/%s" - sociServiceDownloadURLFormat = "https://raw.githubusercontent.com/awslabs/soci-snapshotter/v%s/soci-snapshotter.service" - //nolint:lll // command string - sociInstallationScriptFormat = `%s -if [ ! -f /usr/local/bin/soci ]; then - # download soci - set -e - - # pull release tarball - release_tarball="%s" - curl --retry 2 --retry-max-time 120 -OL "%s" - - # validate shasum - (sha256sum "${release_tarball}" | cut -d ' ' -f 1 | grep -xq "^%s$") || \ - (echo "error: shasum verification failed for SOCI release tarball" && rm -f "${release_tarball}" && exit 1) - - # move to usr/local/bin - tar -C /usr/local/bin -xvf ${release_tarball} ./soci ./soci-snapshotter-grpc - - # install as a systemd service - curl --retry 2 --retry-max-time 120 -OL "%s" - mv soci-snapshotter.service /usr/local/lib/systemd/system/ - ln -s /usr/local/lib/systemd/system/soci-snapshotter.service /etc/systemd/system/multi-user.target.wants/ - restorecon -v /usr/local/lib/systemd/system/soci-snapshotter.service - systemctl daemon-reload - sudo mkdir -p /usr/local/lib/systemd/system/soci-snapshotter.service.d/ - printf '[Unit]\nPartOf=containerd.service\n\n[Service]\nKillSignal=SIGTERM\n' | sudo tee /usr/local/lib/systemd/system/soci-snapshotter.service.d/finch.conf - systemctl enable --now soci-snapshotter -fi - -# changing containerd config, this seems to get reset on every VM stop/start -if ! grep -q soci /etc/containerd/config.toml; then - printf ' [proxy_plugins.soci]\n type = "snapshot"\n address = "/run/soci-snapshotter-grpc/soci-snapshotter-grpc.sock"\n' >> /etc/containerd/config.toml -fi - -sudo systemctl restart containerd.service -` - - userModeEmulationProvisioningScriptHeader = "# cross-arch tools" - wslDiskFormatScriptHeader = "# wsl disk format script" - qemuPkgInstallationScript = `%s -#!/bin/bash -qemu_pkgs="" -if [ ! -f /usr/bin/qemu-aarch64-static ]; then - qemu_pkgs="$qemu_pkgs qemu-user-static-aarch64" -elif [ ! -f /usr/bin/qemu-aarch64-static ]; then - qemu_pkgs="$qemu_pkgs qemu-user-static-arm" -elif [ ! -f /usr/bin/qemu-aarch64-static ]; then - qemu_pkgs="$qemu_pkgs qemu-user-static-x86" -fi - -if [[ $qemu_pkgs ]]; then - dnf install -y --setopt=install_weak_deps=False ${qemu_pkgs} -fi -` -) - -// NewLimaApplier creates a new LimaConfigApplier that -// applies lima configuration changes by writing to the lima config file on the disk. -func NewLimaApplier( - cfg *Finch, - cmdCreator command.Creator, - fs afero.Fs, - limaDefaultConfigPath string, - limaOverrideConfigPath string, - systemDeps LimaConfigApplierSystemDeps, - finchConfigPath string, -) LimaConfigApplier { - return &limaConfigApplier{ - cfg: cfg, - cmdCreator: cmdCreator, - fs: fs, - limaDefaultConfigPath: limaDefaultConfigPath, - limaOverrideConfigPath: limaOverrideConfigPath, - systemDeps: systemDeps, - finchConfigPath: finchConfigPath, - } -} - -// ConfigureDefaultLimaYaml writes Lima-specific config values from Finch's config to default.yaml at lima config file path. -// ConfigureDefaultLimaYaml will create a default.yaml at the path if it does not exist. -func (lca *limaConfigApplier) ConfigureDefaultLimaYaml() error { - if err := afero.WriteFile(lca.fs, lca.limaDefaultConfigPath, []byte(""), 0o600); err != nil { - return fmt.Errorf("failed to create the an empty lima config file: %w", err) - } - - var limaCfg limayaml.LimaYAML - - if limaCfg.Rosetta.Enabled == nil { - limaCfg.Rosetta.Enabled = pointer.Bool(false) - limaCfg.Rosetta.BinFmt = pointer.Bool(false) - } - - cfgAfterInit, err := lca.configureVirtualizationFramework(&limaCfg) - if err != nil { - return fmt.Errorf("failed to apply init-only config values: %w", err) - } - limaCfg = *cfgAfterInit - - limaCfgBytes, err := yaml.Marshal(limaCfg) - if err != nil { - return fmt.Errorf("failed to marshal the lima config file: %w", err) - } - - if err := afero.WriteFile(lca.fs, lca.limaDefaultConfigPath, limaCfgBytes, 0o600); err != nil { - return fmt.Errorf("failed to write to the lima config file: %w", err) - } - - return nil -} - -// ConfigureOverrideLimaYaml writes Lima-specific config values from Finch's config to override.yaml at lima config file path. -// ConfigureOverrideLimaYaml will create a override.yaml at the path if it does not exist. -func (lca *limaConfigApplier) ConfigureOverrideLimaYaml() error { - if err := afero.WriteFile(lca.fs, lca.limaOverrideConfigPath, []byte(""), 0o600); err != nil { - return fmt.Errorf("failed to create the an empty lima config file: %w", err) - } - var limaCfg limayaml.LimaYAML - - lca.configureCPUs(&limaCfg) - lca.configureMemory(&limaCfg) - lca.configureMounts(&limaCfg) - if *lca.cfg.VMType != "wsl2" && len(limaCfg.AdditionalDisks) == 0 { - limaCfg.AdditionalDisks = append(limaCfg.AdditionalDisks, limayaml.Disk{ - Name: "finch", - }) - } - - err := lca.provisionSnapshotters(&limaCfg) - if err != nil { - return fmt.Errorf("failed to provision snapshotters: %w", err) - } - - err = lca.configureDefaultSnapshotter(&limaCfg) - if err != nil { - return fmt.Errorf("failed to configure default snapshotter: %w", err) - } - - if *lca.cfg.VMType == "wsl2" { - ensureWslDiskFormatScript(&limaCfg) - } - - limaCfgBytes, err := yaml.Marshal(limaCfg) - if err != nil { - return fmt.Errorf("failed to marshal the lima config file: %w", err) - } - - if err := afero.WriteFile(lca.fs, lca.limaOverrideConfigPath, limaCfgBytes, 0o600); err != nil { - return fmt.Errorf("failed to write to the lima config file: %w", err) - } - - return nil -} - -func validateSnapshotter(snapshotter string) error { - supportedSnapshotters := []string{"overlayfs", "soci"} - if !slices.Contains(supportedSnapshotters, snapshotter) { - return fmt.Errorf("snapshotter %s is not supported", snapshotter) - } - return nil -} - -func (lca *limaConfigApplier) configureDefaultSnapshotter(limaCfg *limayaml.LimaYAML) error { - if len(lca.cfg.Snapshotters) == 0 { - limaCfg.Env = map[string]string{} - return nil - } - - snapshotter := lca.cfg.Snapshotters[0] - err := validateSnapshotter(snapshotter) - if err != nil { - return err - } - - limaCfg.Env = map[string]string{"CONTAINERD_SNAPSHOTTER": snapshotter} - - return nil -} - -func (lca *limaConfigApplier) provisionSnapshotters(limaCfg *limayaml.LimaYAML) error { - for _, snapshotter := range lca.cfg.Snapshotters { - switch snapshotter { - case "soci": - lca.provisionSociSnapshotter(limaCfg) - case "overlayfs": - continue - default: - return fmt.Errorf("snapshotter %s is not supported", snapshotter) - } - } - - return nil -} - -func (lca *limaConfigApplier) provisionSociSnapshotter(limaCfg *limayaml.LimaYAML) { - arch := lca.systemDeps.Arch() - sociFileName := fmt.Sprintf(sociFileNameFormat, sociVersion, arch) - sociDownloadURL := fmt.Sprintf(sociDownloadURLFormat, sociVersion, sociFileName) - sociSha256Sum := sociAMD64Sha256Sum - if arch == "arm64" { - sociSha256Sum = sociARM64Sha256Sum - } - sociServiceDownloadURL := fmt.Sprintf(sociServiceDownloadURLFormat, sociVersion) - sociInstallationScript := fmt.Sprintf(sociInstallationScriptFormat, sociInstallationProvisioningScriptHeader, - sociFileName, sociDownloadURL, sociSha256Sum, sociServiceDownloadURL) - limaCfg.Provision = append(limaCfg.Provision, limayaml.Provision{ - Mode: "system", - Script: sociInstallationScript, - }) -} - -func ensureWslDiskFormatScript(limaCfg *limayaml.LimaYAML) { - if hasScript := findWslDiskFormatScript(limaCfg); !hasScript { - limaCfg.Provision = append(limaCfg.Provision, limayaml.Provision{ - Mode: "system", - Script: fmt.Sprintf(`%s -#!/bin/bash -mkdir -p /mnt/lima-finch -mount "$(blkid -s TYPE -t LABEL=FinchDataDisk -o device)" /mnt/lima-finch -`, wslDiskFormatScriptHeader), - }) - } -} - -func findWslDiskFormatScript(limaCfg *limayaml.LimaYAML) bool { - hasWslDiskFormatScript := false - for _, prov := range limaCfg.Provision { - trimmed := strings.Trim(prov.Script, " ") - if !hasWslDiskFormatScript && strings.HasPrefix(trimmed, wslDiskFormatScriptHeader) { - hasWslDiskFormatScript = true - break - } - } - - return hasWslDiskFormatScript -} - -func (lca *limaConfigApplier) GetFinchConfigPath() string { - return lca.finchConfigPath -} From d2e45f93c1649a4adec8bbcba6833b53e58eae54 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Mon, 29 Jul 2024 11:56:41 -0400 Subject: [PATCH 20/37] automatically set the NATIVE_BUILD parameter if using Linux since that's the only supported config Signed-off-by: Justin Alvarez --- Makefile | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 53fd61aea..b06c82436 100644 --- a/Makefile +++ b/Makefile @@ -22,8 +22,9 @@ LIMA_EXTENSION := .tar.gz LIMA_VDE_SUDOERS_FILE := /etc/sudoers.d/finch-lima # Final installation prefix for vde created by CLI after installation, only used in uninstall step VDE_INSTALL ?= /opt/finch -UNAME := $(shell uname -m) -ARCH ?= $(UNAME) +UNAME_M := $(shell uname -m) +UNAME_S := $(shell uname -s) +ARCH ?= $(UNAME_M) SUPPORTED_ARCH = false LICENSEDIR := $(OUTDIR)/license-files VERSION ?= $(shell git describe --match 'v[0-9]*' --dirty='.modified' --always --tags) @@ -56,11 +57,26 @@ BUILD_OS ?= $(OS) FINCH_CORE_DIR := $(CURDIR)/deps/finch-core ifeq ($(BUILD_OS), Windows_NT) include Makefile.windows -else +else ifeq ($(UNAME_S), Darwin) include Makefile.darwin endif +ifeq ($(UNAME_S),Linux) + # On Linux, which only supports native mode, set NATIVE_BUILD to true + # unless it was explicitly set to false + ifneq ($(NATIVE_BUILD),false) + NATIVE_BUILD = true + endif + ifndef $(NATIVE_BUILD) + NATIVE_BUILD = true + endif +endif + +ifeq ($(NATIVE_BUILD),true) +all: finch +else ifeq ($(NATIVE_BUILD),false) all: arch-test finch install.finch-core-dependencies finch.yaml networks.yaml config.yaml +endif .PHONY: install.finch-core-dependencies install.finch-core-dependencies: @@ -109,7 +125,7 @@ ifeq ($(GOOS),windows) finch: finch-windows finch-general else ifeq ($(GOOS),darwin) finch: finch-macos -else ifeq ($(GOOS),linux) +else ifeq ($(NATIVE_BUILD),true) finch: finch-native else finch: finch-general From 11fadda8e5759c714de879189f24b6b55681e688 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Mon, 29 Jul 2024 11:57:13 -0400 Subject: [PATCH 21/37] allow GITCOMMIT to be overwritten to make RPM builds easier Signed-off-by: Justin Alvarez --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index b06c82436..9633a0064 100644 --- a/Makefile +++ b/Makefile @@ -28,7 +28,7 @@ ARCH ?= $(UNAME_M) SUPPORTED_ARCH = false LICENSEDIR := $(OUTDIR)/license-files VERSION ?= $(shell git describe --match 'v[0-9]*' --dirty='.modified' --always --tags) -GITCOMMIT := $(shell git rev-parse HEAD)$(shell test -z "$(git status --porcelain)" || echo .m) +GITCOMMIT ?= $(shell git rev-parse HEAD)$(shell test -z "$(git status --porcelain)" || echo .m) LDFLAGS = "-w -X $(PACKAGE)/pkg/version.Version=$(VERSION) -X $(PACKAGE)/pkg/version.GitCommit=$(GITCOMMIT)" MIN_MACOS_VERSION ?= 11.0 From cba2d829e22c37475aa45b6e2842021678ee37d9 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Mon, 29 Jul 2024 11:57:29 -0400 Subject: [PATCH 22/37] finch-general => finch-all Signed-off-by: Justin Alvarez --- Makefile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index 9633a0064..439535351 100644 --- a/Makefile +++ b/Makefile @@ -122,13 +122,13 @@ uninstall: uninstall.finch .PHONY: finch ifeq ($(GOOS),windows) -finch: finch-windows finch-general +finch: finch-windows finch-all else ifeq ($(GOOS),darwin) finch: finch-macos else ifeq ($(NATIVE_BUILD),true) finch: finch-native else -finch: finch-general +finch: finch-all endif finch-windows: @@ -139,12 +139,12 @@ finch-macos: export CGO_CFLAGS := -mmacosx-version-min=$(MIN_MACOS_VERSION) finch-macos: export CGO_LDFLAGS := -mmacosx-version-min=$(MIN_MACOS_VERSION) finch-macos: finch-unix -finch-unix: finch-general +finch-unix: finch-all finch-native: GO_BUILD_TAGS += native -finch-native: finch-general +finch-native: finch-all -finch-general: +finch-all: $(GO) build -ldflags $(LDFLAGS) -tags "$(GO_BUILD_TAGS)" -o $(OUTDIR)/bin/$(BINARYNAME) $(PACKAGE)/cmd/finch .PHONY: release From 4dc79857727a1b59960e5790793e6945e9c3524c Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Mon, 29 Jul 2024 11:58:05 -0400 Subject: [PATCH 23/37] main_local.go => main_native.go Signed-off-by: Justin Alvarez --- cmd/finch/{main_local.go => main_native.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename cmd/finch/{main_local.go => main_native.go} (100%) diff --git a/cmd/finch/main_local.go b/cmd/finch/main_native.go similarity index 100% rename from cmd/finch/main_local.go rename to cmd/finch/main_native.go From dc6688bc44bdd67f418926e2dd6b5f840b11f792 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Mon, 29 Jul 2024 12:15:34 -0400 Subject: [PATCH 24/37] remove ensureCredentials check in native mode Signed-off-by: Justin Alvarez --- cmd/finch/nerdctl_native.go | 22 ++++------------------ 1 file changed, 4 insertions(+), 18 deletions(-) diff --git a/cmd/finch/nerdctl_native.go b/cmd/finch/nerdctl_native.go index cee9cf5e4..6c82950d0 100644 --- a/cmd/finch/nerdctl_native.go +++ b/cmd/finch/nerdctl_native.go @@ -13,24 +13,6 @@ import ( ) func (nc *nerdctlCommand) run(cmdName string, args []string) error { - var additionalEnv []string - switch cmdName { - case "image": - if slices.Contains(args, "build") || slices.Contains(args, "pull") || slices.Contains(args, "push") { - ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) - } - case "container": - if slices.Contains(args, "run") { - ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) - } - case "build", "pull", "push", "run": - ensureRemoteCredentials(nc.fc, nc.ecc, &additionalEnv, nc.logger) - } - - if nc.shouldReplaceForHelp(cmdName, args) { - return nc.ncc.RunWithReplacingStdout([]command.Replacement{{Source: "nerdctl", Target: "finch"}}, args...) - } - // eat the debug arg, and set the log level to avoid nerdctl parsing this flag dbgIdx := slices.Index(args, "--debug") if dbgIdx >= 0 { @@ -38,5 +20,9 @@ func (nc *nerdctlCommand) run(cmdName string, args []string) error { nc.logger.SetLevel(flog.Debug) } + if nc.shouldReplaceForHelp(cmdName, args) { + return nc.ncc.RunWithReplacingStdout([]command.Replacement{{Source: "nerdctl", Target: "finch"}}, args...) + } + return nc.ncc.Create(append([]string{cmdName}, args...)...).Run() } From 72f0ce9785a998174bfb4b7ce1c9144b4334369b Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Mon, 29 Jul 2024 12:15:53 -0400 Subject: [PATCH 25/37] virtual_machine_local.go => virtual_machine_native.go Signed-off-by: Justin Alvarez --- cmd/finch/{virtual_machine_local.go => virtual_machine_native.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename cmd/finch/{virtual_machine_local.go => virtual_machine_native.go} (100%) diff --git a/cmd/finch/virtual_machine_local.go b/cmd/finch/virtual_machine_native.go similarity index 100% rename from cmd/finch/virtual_machine_local.go rename to cmd/finch/virtual_machine_native.go From 2a3c9f544a08fed863522dc2cab3e599a9f52bf2 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Mon, 29 Jul 2024 12:22:59 -0400 Subject: [PATCH 26/37] ensure all remote only tests have _remote suffix Signed-off-by: Justin Alvarez --- cmd/finch/{nerdctl_shared_test.go => nerdctl_remote_test.go} | 0 cmd/finch/{version_test.go => version_remote_test.go} | 0 .../{additional_disk_test.go => additional_disk_remote_test.go} | 0 e2e/vm/{config_test.go => config_remote_test.go} | 0 e2e/vm/{cred_helper_test.go => cred_helper_remote_test.go} | 0 ...finch_config_file_test.go => finch_config_file_remote_test.go} | 0 e2e/vm/{lifecycle_test.go => lifecycle_remote_test.go} | 0 e2e/vm/{soci_test.go => soci_remote_test.go} | 0 e2e/vm/{support_bundle_test.go => support_bundle_remote_test.go} | 0 e2e/vm/{version_test.go => version_remote_test.go} | 0 e2e/vm/{vm_test.go => vm_remote_test.go} | 0 pkg/command/{nerdctl_test.go => nerdctl_remote_test.go} | 0 pkg/config/{defaults_test.go => defaults_remote_test.go} | 0 ...nfig_applier_test.go => nerdctl_config_applier_remote_test.go} | 0 pkg/path/{finch_test.go => finch_remote_test.go} | 0 15 files changed, 0 insertions(+), 0 deletions(-) rename cmd/finch/{nerdctl_shared_test.go => nerdctl_remote_test.go} (100%) rename cmd/finch/{version_test.go => version_remote_test.go} (100%) rename e2e/vm/{additional_disk_test.go => additional_disk_remote_test.go} (100%) rename e2e/vm/{config_test.go => config_remote_test.go} (100%) rename e2e/vm/{cred_helper_test.go => cred_helper_remote_test.go} (100%) rename e2e/vm/{finch_config_file_test.go => finch_config_file_remote_test.go} (100%) rename e2e/vm/{lifecycle_test.go => lifecycle_remote_test.go} (100%) rename e2e/vm/{soci_test.go => soci_remote_test.go} (100%) rename e2e/vm/{support_bundle_test.go => support_bundle_remote_test.go} (100%) rename e2e/vm/{version_test.go => version_remote_test.go} (100%) rename e2e/vm/{vm_test.go => vm_remote_test.go} (100%) rename pkg/command/{nerdctl_test.go => nerdctl_remote_test.go} (100%) rename pkg/config/{defaults_test.go => defaults_remote_test.go} (100%) rename pkg/config/{nerdctl_config_applier_test.go => nerdctl_config_applier_remote_test.go} (100%) rename pkg/path/{finch_test.go => finch_remote_test.go} (100%) diff --git a/cmd/finch/nerdctl_shared_test.go b/cmd/finch/nerdctl_remote_test.go similarity index 100% rename from cmd/finch/nerdctl_shared_test.go rename to cmd/finch/nerdctl_remote_test.go diff --git a/cmd/finch/version_test.go b/cmd/finch/version_remote_test.go similarity index 100% rename from cmd/finch/version_test.go rename to cmd/finch/version_remote_test.go diff --git a/e2e/vm/additional_disk_test.go b/e2e/vm/additional_disk_remote_test.go similarity index 100% rename from e2e/vm/additional_disk_test.go rename to e2e/vm/additional_disk_remote_test.go diff --git a/e2e/vm/config_test.go b/e2e/vm/config_remote_test.go similarity index 100% rename from e2e/vm/config_test.go rename to e2e/vm/config_remote_test.go diff --git a/e2e/vm/cred_helper_test.go b/e2e/vm/cred_helper_remote_test.go similarity index 100% rename from e2e/vm/cred_helper_test.go rename to e2e/vm/cred_helper_remote_test.go diff --git a/e2e/vm/finch_config_file_test.go b/e2e/vm/finch_config_file_remote_test.go similarity index 100% rename from e2e/vm/finch_config_file_test.go rename to e2e/vm/finch_config_file_remote_test.go diff --git a/e2e/vm/lifecycle_test.go b/e2e/vm/lifecycle_remote_test.go similarity index 100% rename from e2e/vm/lifecycle_test.go rename to e2e/vm/lifecycle_remote_test.go diff --git a/e2e/vm/soci_test.go b/e2e/vm/soci_remote_test.go similarity index 100% rename from e2e/vm/soci_test.go rename to e2e/vm/soci_remote_test.go diff --git a/e2e/vm/support_bundle_test.go b/e2e/vm/support_bundle_remote_test.go similarity index 100% rename from e2e/vm/support_bundle_test.go rename to e2e/vm/support_bundle_remote_test.go diff --git a/e2e/vm/version_test.go b/e2e/vm/version_remote_test.go similarity index 100% rename from e2e/vm/version_test.go rename to e2e/vm/version_remote_test.go diff --git a/e2e/vm/vm_test.go b/e2e/vm/vm_remote_test.go similarity index 100% rename from e2e/vm/vm_test.go rename to e2e/vm/vm_remote_test.go diff --git a/pkg/command/nerdctl_test.go b/pkg/command/nerdctl_remote_test.go similarity index 100% rename from pkg/command/nerdctl_test.go rename to pkg/command/nerdctl_remote_test.go diff --git a/pkg/config/defaults_test.go b/pkg/config/defaults_remote_test.go similarity index 100% rename from pkg/config/defaults_test.go rename to pkg/config/defaults_remote_test.go diff --git a/pkg/config/nerdctl_config_applier_test.go b/pkg/config/nerdctl_config_applier_remote_test.go similarity index 100% rename from pkg/config/nerdctl_config_applier_test.go rename to pkg/config/nerdctl_config_applier_remote_test.go diff --git a/pkg/path/finch_test.go b/pkg/path/finch_remote_test.go similarity index 100% rename from pkg/path/finch_test.go rename to pkg/path/finch_remote_test.go From 564aa7d9b46a68cc0e3b27a3367a0068ef751365 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Mon, 29 Jul 2024 12:42:09 -0400 Subject: [PATCH 27/37] prepend path to vended buildkit binaries for Fedora-based systems Signed-off-by: Justin Alvarez --- cmd/finch/main_native.go | 1 + pkg/command/nerdctl.go | 14 ++++++++ ...tl_unix_test.go => nerdctl_darwin_test.go} | 0 pkg/command/nerdctl_native.go | 11 ++++++- pkg/command/nerdctl_remote.go | 33 +++---------------- pkg/command/nerdctl_unix.go | 11 +++++++ pkg/command/nerdctl_windows.go | 11 +++++++ pkg/path/finch_native_linux.go | 8 ++++- 8 files changed, 58 insertions(+), 31 deletions(-) rename pkg/command/{nerdctl_unix_test.go => nerdctl_darwin_test.go} (100%) create mode 100644 pkg/command/nerdctl_unix.go create mode 100644 pkg/command/nerdctl_windows.go diff --git a/cmd/finch/main_native.go b/cmd/finch/main_native.go index 35d47f716..89c040c5d 100644 --- a/cmd/finch/main_native.go +++ b/cmd/finch/main_native.go @@ -20,6 +20,7 @@ func nerdctlCmdCreator(ecc command.Creator, logger flog.Logger, fp path.Finch, f logger, fp.NerdctlConfigFilePath(finchRootPath), fp.BuildkitSocketPath(finchRootPath), + fp.FinchDependencyBinDir(), system.NewStdLib(), ) } diff --git a/pkg/command/nerdctl.go b/pkg/command/nerdctl.go index e42ce7867..ab1309f7a 100644 --- a/pkg/command/nerdctl.go +++ b/pkg/command/nerdctl.go @@ -5,6 +5,9 @@ package command import ( "bytes" + "fmt" + "slices" + "strings" "github.com/runfinch/finch/pkg/system" ) @@ -83,3 +86,14 @@ func (ncc *nerdctlCmdCreator) replaceBytes(s []byte, rs []Replacement) []byte { } return s } + +func replaceOrAppend(orig []string, varName, newVar string) []string { + envIdx := slices.IndexFunc(orig, func(envVar string) bool { + return strings.HasPrefix(envVar, fmt.Sprintf("%s=", varName)) + }) + + if envIdx != -1 { + return slices.Replace(orig, envIdx, envIdx+1, newVar) + } + return append(orig, newVar) +} diff --git a/pkg/command/nerdctl_unix_test.go b/pkg/command/nerdctl_darwin_test.go similarity index 100% rename from pkg/command/nerdctl_unix_test.go rename to pkg/command/nerdctl_darwin_test.go diff --git a/pkg/command/nerdctl_native.go b/pkg/command/nerdctl_native.go index 229ef3b74..f2d8681e3 100644 --- a/pkg/command/nerdctl_native.go +++ b/pkg/command/nerdctl_native.go @@ -18,6 +18,7 @@ type nerdctlCmdCreator struct { systemDeps NerdctlCmdCreatorSystemDeps nerdctlConfigPath string buildkitSocketPath string + binPath string } // NewNerdctlCmdCreator returns a NerdctlCmdCreator that creates nerdctl commands. @@ -28,6 +29,7 @@ func NewNerdctlCmdCreator( logger flog.Logger, nerdctlConfigPath string, buildkitSocketPath string, + binPath string, systemDeps NerdctlCmdCreatorSystemDeps, ) NerdctlCmdCreator { return &nerdctlCmdCreator{ @@ -35,6 +37,7 @@ func NewNerdctlCmdCreator( logger: logger, nerdctlConfigPath: nerdctlConfigPath, buildkitSocketPath: buildkitSocketPath, + binPath: binPath, systemDeps: systemDeps, } } @@ -43,8 +46,14 @@ func (ncc *nerdctlCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, ncc.logger.Debugf("Creating nerdctl command: ARGUMENTS: %v", args) cmd := ncc.cmdCreator.Create("nerdctl", args...) + path := ncc.systemDeps.Env(envKeyPath) + path = fmt.Sprintf("%s:%s", ncc.binPath, path) + pathEnv := fmt.Sprintf("%s=%s", envKeyPath, path) + + newPathEnv := replaceOrAppend(ncc.systemDeps.Environ(), envKeyPath, pathEnv) + env := append( - ncc.systemDeps.Environ(), + newPathEnv, fmt.Sprintf("NERDCTL_TOML=%s", ncc.nerdctlConfigPath), fmt.Sprintf("BUILDKIT_HOST=%s", ncc.buildkitSocketPath), ) diff --git a/pkg/command/nerdctl_remote.go b/pkg/command/nerdctl_remote.go index d453e2fa0..3ed1a3c1f 100644 --- a/pkg/command/nerdctl_remote.go +++ b/pkg/command/nerdctl_remote.go @@ -8,16 +8,12 @@ package command import ( "fmt" "io" - "runtime" - "slices" - "strings" "github.com/runfinch/finch/pkg/flog" ) const ( envKeyLimaHome = "LIMA_HOME" - envKeyUnixPath = "PATH" envKeyWinPath = "Path" ) @@ -55,20 +51,10 @@ func (ncc *nerdctlCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, ncc.logger.Debugf("Creating limactl command: ARGUMENTS: %v, %s: %s", args, envKeyLimaHome, ncc.limaHomePath) cmd := ncc.cmdCreator.Create(ncc.limactlPath, args...) limaHomeEnv := fmt.Sprintf("%s=%s", envKeyLimaHome, ncc.limaHomePath) - var pathEnv string - var envKeyPath string - var path string - if runtime.GOOS == "windows" { - envKeyPath = envKeyWinPath - path = ncc.systemDeps.Env(envKeyPath) - path = fmt.Sprintf(`%s\;%s`, ncc.binPath, path) - pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) - } else { - envKeyPath = envKeyUnixPath - path = ncc.systemDeps.Env(envKeyPath) - path = fmt.Sprintf("%s:%s", ncc.binPath, path) - pathEnv = fmt.Sprintf("%s=%s", envKeyPath, path) - } + + path := ncc.systemDeps.Env(envKeyPath) + path = fmt.Sprintf(`%s%s%s`, ncc.binPath, envKeyPathJoiner, path) + pathEnv := fmt.Sprintf("%s=%s", envKeyPath, path) newPathEnv := replaceOrAppend(ncc.systemDeps.Environ(), envKeyLimaHome, limaHomeEnv) newPathEnv = replaceOrAppend(newPathEnv, envKeyPath, pathEnv) @@ -79,14 +65,3 @@ func (ncc *nerdctlCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, cmd.SetStderr(stderr) return cmd } - -func replaceOrAppend(orig []string, varName, newVar string) []string { - envIdx := slices.IndexFunc(orig, func(envVar string) bool { - return strings.HasPrefix(envVar, fmt.Sprintf("%s=", varName)) - }) - - if envIdx != -1 { - return slices.Replace(orig, envIdx, envIdx+1, newVar) - } - return append(orig, newVar) -} diff --git a/pkg/command/nerdctl_unix.go b/pkg/command/nerdctl_unix.go new file mode 100644 index 000000000..ae7062a5f --- /dev/null +++ b/pkg/command/nerdctl_unix.go @@ -0,0 +1,11 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build !windows + +package command + +const ( + envKeyPath = "PATH" + envKeyPathJoiner = ":" +) diff --git a/pkg/command/nerdctl_windows.go b/pkg/command/nerdctl_windows.go new file mode 100644 index 000000000..afc0ce3ab --- /dev/null +++ b/pkg/command/nerdctl_windows.go @@ -0,0 +1,11 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +//go:build windows + +package command + +const ( + envKeyPath = "Path" + envKeyPathJoiner = `\;` +) diff --git a/pkg/path/finch_native_linux.go b/pkg/path/finch_native_linux.go index dfa52c721..f29b843c4 100644 --- a/pkg/path/finch_native_linux.go +++ b/pkg/path/finch_native_linux.go @@ -30,11 +30,17 @@ func (Finch) NerdctlConfigFilePath(rootDir string) string { return filepath.Join(rootDir, "nerdctl", "nerdctl.toml") } -// BuildkitSocketPath returns the path to Finch config file. +// BuildkitSocketPath returns the path to the Buildkit socket file. func (Finch) BuildkitSocketPath(rootDir string) string { return filepath.Join(rootDir, "buildkit", "buildkitd.toml") } +// FinchDependencyBinDir returns the path to Finch's local helper or dependency binaries. +// Currently used for vended version of BuildKit. +func (Finch) FinchDependencyBinDir() string { + return filepath.Join("/", "usr", "libexec", "finch") +} + // FindFinch finds the installation path of Finch. func FindFinch(deps FinchFinderDeps) (Finch, error) { exe, err := deps.Executable() From d84a7f5312a5b923add18555b1326e1700493401 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Mon, 29 Jul 2024 18:55:57 -0400 Subject: [PATCH 28/37] fix Makefile not handling default case for NATIVE_BUILD not on Linux Signed-off-by: Justin Alvarez --- Makefile | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index 439535351..65d4cf5dd 100644 --- a/Makefile +++ b/Makefile @@ -55,11 +55,6 @@ arch-test: BUILD_OS ?= $(OS) FINCH_CORE_DIR := $(CURDIR)/deps/finch-core -ifeq ($(BUILD_OS), Windows_NT) -include Makefile.windows -else ifeq ($(UNAME_S), Darwin) -include Makefile.darwin -endif ifeq ($(UNAME_S),Linux) # On Linux, which only supports native mode, set NATIVE_BUILD to true @@ -72,12 +67,23 @@ ifeq ($(UNAME_S),Linux) endif endif +# if still not defined, then set to false +ifndef $(NATIVE_BUILD) + NATIVE_BUILD = false +endif + ifeq ($(NATIVE_BUILD),true) all: finch else ifeq ($(NATIVE_BUILD),false) all: arch-test finch install.finch-core-dependencies finch.yaml networks.yaml config.yaml endif +ifeq ($(BUILD_OS), Windows_NT) +include Makefile.windows +else ifeq ($(UNAME_S), Darwin) +include Makefile.darwin +endif + .PHONY: install.finch-core-dependencies install.finch-core-dependencies: OUTDIR=$(OUTDIR) ARCH=$(ARCH) "$(MAKE)" -C $(FINCH_CORE_DIR) install.dependencies From 5b15065cb766503f24a3bd7c97c60dfa1234067a Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 30 Jul 2024 15:39:15 -0400 Subject: [PATCH 29/37] simplify makefile Signed-off-by: Justin Alvarez --- Makefile | 39 ++++++++++++++++----------------------- 1 file changed, 16 insertions(+), 23 deletions(-) diff --git a/Makefile b/Makefile index 65d4cf5dd..0c6d7b278 100644 --- a/Makefile +++ b/Makefile @@ -22,9 +22,7 @@ LIMA_EXTENSION := .tar.gz LIMA_VDE_SUDOERS_FILE := /etc/sudoers.d/finch-lima # Final installation prefix for vde created by CLI after installation, only used in uninstall step VDE_INSTALL ?= /opt/finch -UNAME_M := $(shell uname -m) -UNAME_S := $(shell uname -s) -ARCH ?= $(UNAME_M) +ARCH ?= $(shell uname -m) SUPPORTED_ARCH = false LICENSEDIR := $(OUTDIR)/license-files VERSION ?= $(shell git describe --match 'v[0-9]*' --dirty='.modified' --always --tags) @@ -53,23 +51,24 @@ endif arch-test: @if [ $(SUPPORTED_ARCH) != "true" ]; then echo "Unsupported architecture: $(ARCH)"; exit "1"; fi +# OS will be set on Windows (to Windows_NT), and undefined otherwise unless +# it is explicity specified on the commandline. +# On Unix (or, not-Windows), query OS and set it using uname -s BUILD_OS ?= $(OS) -FINCH_CORE_DIR := $(CURDIR)/deps/finch-core - -ifeq ($(UNAME_S),Linux) - # On Linux, which only supports native mode, set NATIVE_BUILD to true - # unless it was explicitly set to false - ifneq ($(NATIVE_BUILD),false) - NATIVE_BUILD = true - endif - ifndef $(NATIVE_BUILD) - NATIVE_BUILD = true - endif +ifeq ($(BUILD_OS),) +BUILD_OS = $(shell uname -s) endif -# if still not defined, then set to false -ifndef $(NATIVE_BUILD) - NATIVE_BUILD = false +FINCH_CORE_DIR := $(CURDIR)/deps/finch-core + +ifeq ($(BUILD_OS), Windows_NT) +include Makefile.windows +else ifeq ($(BUILD_OS), Darwin) +include Makefile.darwin +else ifeq ($(BUILD_OS), Linux) +# on Linux, set NATIVE_BUILD unless it was otherwise +# set by the environment +NATIVE_BUILD ?= true endif ifeq ($(NATIVE_BUILD),true) @@ -78,12 +77,6 @@ else ifeq ($(NATIVE_BUILD),false) all: arch-test finch install.finch-core-dependencies finch.yaml networks.yaml config.yaml endif -ifeq ($(BUILD_OS), Windows_NT) -include Makefile.windows -else ifeq ($(UNAME_S), Darwin) -include Makefile.darwin -endif - .PHONY: install.finch-core-dependencies install.finch-core-dependencies: OUTDIR=$(OUTDIR) ARCH=$(ARCH) "$(MAKE)" -C $(FINCH_CORE_DIR) install.dependencies From e8743ab183171e28afeb50bb5b10cab3615852f5 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 30 Jul 2024 15:40:58 -0400 Subject: [PATCH 30/37] rename variable Signed-off-by: Justin Alvarez --- cmd/finch/version_native.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/finch/version_native.go b/cmd/finch/version_native.go index 94c2088d1..d38284a47 100644 --- a/cmd/finch/version_native.go +++ b/cmd/finch/version_native.go @@ -11,8 +11,8 @@ import ( ) func (va *versionAction) printVersion(format string) error { - limaArgs := []string{"version", "--format", "json"} - out, err := va.creator.CreateWithoutStdio(limaArgs...).Output() + nerdctlArgs := []string{"version", "--format", "json"} + out, err := va.creator.CreateWithoutStdio(nerdctlArgs...).Output() if err != nil { return fmt.Errorf("failed to create the nerdctl version command: %w", err) } From ad62d424c202b0f62ee5ca48d69c5ea77c54fecc Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 30 Jul 2024 15:41:08 -0400 Subject: [PATCH 31/37] add native build tag Signed-off-by: Justin Alvarez --- cmd/finch/main_native.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/finch/main_native.go b/cmd/finch/main_native.go index 89c040c5d..081a815c2 100644 --- a/cmd/finch/main_native.go +++ b/cmd/finch/main_native.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build linux +//go:build linux || native package main From a1d03ee653fb92c4dd501d5e306fb4680943e255 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 30 Jul 2024 15:41:57 -0400 Subject: [PATCH 32/37] update NerdctlCmdCreator comment Signed-off-by: Justin Alvarez --- pkg/command/nerdctl.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/command/nerdctl.go b/pkg/command/nerdctl.go index ab1309f7a..d16eff1ac 100644 --- a/pkg/command/nerdctl.go +++ b/pkg/command/nerdctl.go @@ -12,7 +12,7 @@ import ( "github.com/runfinch/finch/pkg/system" ) -// NerdctlCmdCreator creates a limactl command. +// NerdctlCmdCreator creates a nerdctl command. // //go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/command_nerdctl_cmd_creator.go -package=mocks -mock_names NerdctlCmdCreator=NerdctlCmdCreator . NerdctlCmdCreator type NerdctlCmdCreator interface { From b84b424926d5f4e2d2abf0c51507856a73221e9d Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 30 Jul 2024 16:35:46 -0400 Subject: [PATCH 33/37] fix Makefile for non-native builds Signed-off-by: Justin Alvarez --- Makefile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Makefile b/Makefile index 0c6d7b278..f08c17b1b 100644 --- a/Makefile +++ b/Makefile @@ -70,6 +70,8 @@ else ifeq ($(BUILD_OS), Linux) # set by the environment NATIVE_BUILD ?= true endif +# if not set at this point, default it to false +NATIVE_BUILD ?= false ifeq ($(NATIVE_BUILD),true) all: finch From e3555cd5e6b3e2264afb82ca19718acfe2edec8a Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Mon, 5 Aug 2024 11:58:19 -0400 Subject: [PATCH 34/37] remove native build tag and simplify platform separation Signed-off-by: Justin Alvarez --- Makefile | 15 +- cmd/finch/main.go | 64 --------- cmd/finch/main_darwin.go | 2 +- cmd/finch/main_native.go | 75 ++++++++-- cmd/finch/main_remote.go | 69 ++++++++- cmd/finch/nerdctl_darwin.go | 2 +- cmd/finch/nerdctl_native.go | 2 +- cmd/finch/nerdctl_remote.go | 2 +- cmd/finch/nerdctl_remote_test.go | 2 +- cmd/finch/support_bundle.go | 2 +- cmd/finch/support_bundle_native.go | 4 +- cmd/finch/support_bundle_remote.go | 4 +- cmd/finch/version_native.go | 2 +- cmd/finch/version_remote.go | 2 +- cmd/finch/version_remote_test.go | 2 +- ...l_machine_remote.go => virtual_machine.go} | 0 cmd/finch/virtual_machine_native.go | 29 ---- e2e/vm/additional_disk_remote_test.go | 2 +- e2e/vm/config_remote_test.go | 2 +- e2e/vm/cred_helper_remote_test.go | 2 +- e2e/vm/finch_config_file_remote_test.go | 2 +- e2e/vm/lifecycle_remote_test.go | 2 +- e2e/vm/soci_remote_test.go | 2 +- e2e/vm/support_bundle_remote_test.go | 2 +- e2e/vm/version_remote_test.go | 2 +- e2e/vm/vm_remote_test.go | 2 +- pkg/command/nerdctl_darwin_test.go | 2 +- pkg/command/nerdctl_native.go | 2 +- pkg/command/nerdctl_remote.go | 2 +- pkg/command/nerdctl_remote_test.go | 2 +- pkg/config/defaults_remote_test.go | 2 +- pkg/config/lima_config_applier.go | 2 +- pkg/config/lima_config_applier_darwin.go | 2 +- pkg/config/lima_config_applier_windows.go | 2 +- pkg/config/nerdctl_config_applier.go | 131 +++++++++++++++-- pkg/config/nerdctl_config_applier_native.go | 26 ---- pkg/config/nerdctl_config_applier_remote.go | 135 ------------------ ...test.go => nerdctl_config_applier_test.go} | 2 +- pkg/config/validate_darwin.go | 2 +- pkg/config/validate_natvie.go | 2 +- pkg/config/validate_windows.go | 2 +- pkg/dependency/vmnet/binaries_unix.go | 2 +- pkg/dependency/vmnet/binaries_unix_test.go | 2 +- pkg/dependency/vmnet/sudoers_file_unix.go | 2 +- .../vmnet/sudoers_file_unix_test.go | 2 +- .../vmnet/update_network_lima_config_unix.go | 2 +- .../update_network_lima_config_unix_test.go | 2 +- pkg/dependency/vmnet/vmnet_unix.go | 2 +- pkg/dependency/vmnet/vmnet_unix_test.go | 2 +- pkg/disk/disk.go | 2 + pkg/disk/disk_darwin.go | 3 +- pkg/disk/disk_native.go | 17 --- ...finch_remote_darwin.go => finch_darwin.go} | 0 .../{finch_native_linux.go => finch_linux.go} | 0 pkg/path/finch_remote.go | 2 +- pkg/path/finch_remote_test.go | 2 +- ...nch_remote_windows.go => finch_windows.go} | 0 pkg/support/config_remote.go | 2 +- 58 files changed, 300 insertions(+), 356 deletions(-) rename cmd/finch/{virtual_machine_remote.go => virtual_machine.go} (100%) delete mode 100644 cmd/finch/virtual_machine_native.go delete mode 100644 pkg/config/nerdctl_config_applier_native.go delete mode 100644 pkg/config/nerdctl_config_applier_remote.go rename pkg/config/{nerdctl_config_applier_remote_test.go => nerdctl_config_applier_test.go} (99%) delete mode 100644 pkg/disk/disk_native.go rename pkg/path/{finch_remote_darwin.go => finch_darwin.go} (100%) rename pkg/path/{finch_native_linux.go => finch_linux.go} (100%) rename pkg/path/{finch_remote_windows.go => finch_windows.go} (100%) diff --git a/Makefile b/Makefile index f08c17b1b..b1720b21e 100644 --- a/Makefile +++ b/Makefile @@ -61,22 +61,17 @@ endif FINCH_CORE_DIR := $(CURDIR)/deps/finch-core +remote-all: arch-test finch install.finch-core-dependencies finch.yaml networks.yaml config.yaml + ifeq ($(BUILD_OS), Windows_NT) include Makefile.windows +all: remote-all else ifeq ($(BUILD_OS), Darwin) include Makefile.darwin +all: remote-all else ifeq ($(BUILD_OS), Linux) -# on Linux, set NATIVE_BUILD unless it was otherwise -# set by the environment -NATIVE_BUILD ?= true -endif -# if not set at this point, default it to false -NATIVE_BUILD ?= false - -ifeq ($(NATIVE_BUILD),true) +# on Linux, we only need to build "finch" all: finch -else ifeq ($(NATIVE_BUILD),false) -all: arch-test finch install.finch-core-dependencies finch.yaml networks.yaml config.yaml endif .PHONY: install.finch-core-dependencies diff --git a/cmd/finch/main.go b/cmd/finch/main.go index 3d7ed3455..df89dd0bd 100644 --- a/cmd/finch/main.go +++ b/cmd/finch/main.go @@ -16,11 +16,8 @@ import ( "github.com/runfinch/finch/pkg/config" "github.com/runfinch/finch/pkg/flog" "github.com/runfinch/finch/pkg/fmemory" - "github.com/runfinch/finch/pkg/lima/wrapper" "github.com/runfinch/finch/pkg/path" - "github.com/runfinch/finch/pkg/support" "github.com/runfinch/finch/pkg/system" - "github.com/runfinch/finch/pkg/version" ) const finchRootCmd = "finch" @@ -81,67 +78,6 @@ func xmain(logger flog.Logger, ).Execute() } -var newApp = func( - logger flog.Logger, - fp path.Finch, - fs afero.Fs, - fc *config.Finch, - stdOut io.Writer, - home, - finchRootPath string, - ecc command.Creator, -) *cobra.Command { - usage := fmt.Sprintf("%v ", finchRootCmd) - rootCmd := &cobra.Command{ - Use: usage, - Short: "Finch: open-source container development tool", - SilenceUsage: true, - SilenceErrors: true, - Version: version.Version, - } - // TODO: Decide when to forward --debug to the dependencies - // (e.g. nerdctl for container commands and limactl for VM commands). - rootCmd.PersistentFlags().Bool("debug", false, "running under debug mode") - rootCmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error { - // running commands under debug mode will print out debug logs - debugMode, _ := cmd.Flags().GetBool("debug") - if debugMode { - logger.SetLevel(flog.Debug) - } - return nil - } - - ncc := nerdctlCmdCreator(ecc, logger, fp, finchRootPath) - lima := wrapper.NewLimaWrapper() - supportBundleBuilder := support.NewBundleBuilder( - logger, - fs, - support.NewBundleConfig(fp, finchRootPath), - fp, - ecc, - ncc, - lima, - ) - - // append nerdctl commands - allCommands := initializeNerdctlCommands(ncc, ecc, logger, fs, fc) - // append finch specific commands - allCommands = append(allCommands, - newVersionCommand(ncc, logger, stdOut), - virtualMachineCommands(logger, fp, ncc, ecc, fs, fc, home, finchRootPath), - newSupportBundleCommand(logger, supportBundleBuilder, ncc), - newGenDocsCommand(rootCmd, logger, fs, system.NewStdLib()), - ) - - rootCmd.AddCommand(allCommands...) - - if err := configureNerdctl(fs); err != nil { - logger.Fatal(err) - } - - return rootCmd -} - func initializeNerdctlCommands( ncc command.NerdctlCmdCreator, ecc command.Creator, diff --git a/cmd/finch/main_darwin.go b/cmd/finch/main_darwin.go index 852390a0b..3f3b9c620 100644 --- a/cmd/finch/main_darwin.go +++ b/cmd/finch/main_darwin.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin package main diff --git a/cmd/finch/main_native.go b/cmd/finch/main_native.go index 081a815c2..d83052abb 100644 --- a/cmd/finch/main_native.go +++ b/cmd/finch/main_native.go @@ -1,38 +1,85 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build linux || native +//go:build linux package main import ( + "fmt" + "io" + "github.com/spf13/afero" + "github.com/spf13/cobra" "github.com/runfinch/finch/pkg/command" "github.com/runfinch/finch/pkg/config" "github.com/runfinch/finch/pkg/flog" + "github.com/runfinch/finch/pkg/lima/wrapper" "github.com/runfinch/finch/pkg/path" + "github.com/runfinch/finch/pkg/support" "github.com/runfinch/finch/pkg/system" + "github.com/runfinch/finch/pkg/version" ) -func nerdctlCmdCreator(ecc command.Creator, logger flog.Logger, fp path.Finch, finchRootPath string) command.NerdctlCmdCreator { - return command.NewNerdctlCmdCreator(ecc, +var newApp = func( + logger flog.Logger, + fp path.Finch, + fs afero.Fs, + fc *config.Finch, + stdOut io.Writer, + _, + finchRootPath string, + ecc command.Creator, +) *cobra.Command { + usage := fmt.Sprintf("%v ", finchRootCmd) + rootCmd := &cobra.Command{ + Use: usage, + Short: "Finch: open-source container development tool", + SilenceUsage: true, + SilenceErrors: true, + Version: version.Version, + } + // TODO: Decide when to forward --debug to the dependencies + // (e.g. nerdctl for container commands and limactl for VM commands). + rootCmd.PersistentFlags().Bool("debug", false, "running under debug mode") + rootCmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error { + // running commands under debug mode will print out debug logs + debugMode, _ := cmd.Flags().GetBool("debug") + if debugMode { + logger.SetLevel(flog.Debug) + } + return nil + } + + ncc := command.NewNerdctlCmdCreator(ecc, logger, fp.NerdctlConfigFilePath(finchRootPath), fp.BuildkitSocketPath(finchRootPath), fp.FinchDependencyBinDir(), system.NewStdLib(), ) -} - -func configureNerdctl(fs afero.Fs) error { - return config.NewNerdctlApplier( - nil, + lima := wrapper.NewLimaWrapper() + supportBundleBuilder := support.NewBundleBuilder( + logger, fs, - "", - "", - "", - "", - nil, - ).Apply("") + support.NewBundleConfig(fp, finchRootPath), + fp, + ecc, + ncc, + lima, + ) + + // append nerdctl commands + allCommands := initializeNerdctlCommands(ncc, ecc, logger, fs, fc) + // append finch specific commands + allCommands = append(allCommands, + newVersionCommand(ncc, logger, stdOut), + newSupportBundleCommand(logger, supportBundleBuilder, ncc), + newGenDocsCommand(rootCmd, logger, fs, system.NewStdLib()), + ) + + rootCmd.AddCommand(allCommands...) + + return rootCmd } diff --git a/cmd/finch/main_remote.go b/cmd/finch/main_remote.go index 5b88e9955..259806a92 100644 --- a/cmd/finch/main_remote.go +++ b/cmd/finch/main_remote.go @@ -1,29 +1,86 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package main import ( + "fmt" + "io" + "github.com/spf13/afero" + "github.com/spf13/cobra" "github.com/runfinch/finch/pkg/command" + "github.com/runfinch/finch/pkg/config" "github.com/runfinch/finch/pkg/flog" + "github.com/runfinch/finch/pkg/lima/wrapper" "github.com/runfinch/finch/pkg/path" + "github.com/runfinch/finch/pkg/support" "github.com/runfinch/finch/pkg/system" + "github.com/runfinch/finch/pkg/version" ) -func nerdctlCmdCreator(ecc command.Creator, logger flog.Logger, fp path.Finch, _ string) command.NerdctlCmdCreator { - return command.NewNerdctlCmdCreator(ecc, +var newApp = func( + logger flog.Logger, + fp path.Finch, + fs afero.Fs, + fc *config.Finch, + stdOut io.Writer, + home, + finchRootPath string, + ecc command.Creator, +) *cobra.Command { + usage := fmt.Sprintf("%v ", finchRootCmd) + rootCmd := &cobra.Command{ + Use: usage, + Short: "Finch: open-source container development tool", + SilenceUsage: true, + SilenceErrors: true, + Version: version.Version, + } + // TODO: Decide when to forward --debug to the dependencies + // (e.g. nerdctl for container commands and limactl for VM commands). + rootCmd.PersistentFlags().Bool("debug", false, "running under debug mode") + rootCmd.PersistentPreRunE = func(cmd *cobra.Command, _ []string) error { + // running commands under debug mode will print out debug logs + debugMode, _ := cmd.Flags().GetBool("debug") + if debugMode { + logger.SetLevel(flog.Debug) + } + return nil + } + + ncc := command.NewNerdctlCmdCreator(ecc, logger, fp.LimaHomePath(), fp.LimactlPath(), fp.QEMUBinDir(), system.NewStdLib(), ) -} + lima := wrapper.NewLimaWrapper() + supportBundleBuilder := support.NewBundleBuilder( + logger, + fs, + support.NewBundleConfig(fp, finchRootPath), + fp, + ecc, + ncc, + lima, + ) + + // append nerdctl commands + allCommands := initializeNerdctlCommands(ncc, ecc, logger, fs, fc) + // append finch specific commands + allCommands = append(allCommands, + newVersionCommand(ncc, logger, stdOut), + virtualMachineCommands(logger, fp, ncc, ecc, fs, fc, home, finchRootPath), + newSupportBundleCommand(logger, supportBundleBuilder, ncc), + newGenDocsCommand(rootCmd, logger, fs, system.NewStdLib()), + ) + + rootCmd.AddCommand(allCommands...) -func configureNerdctl(_ afero.Fs) error { - return nil + return rootCmd } diff --git a/cmd/finch/nerdctl_darwin.go b/cmd/finch/nerdctl_darwin.go index 6b35f540d..cfbf3ad8a 100644 --- a/cmd/finch/nerdctl_darwin.go +++ b/cmd/finch/nerdctl_darwin.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin package main diff --git a/cmd/finch/nerdctl_native.go b/cmd/finch/nerdctl_native.go index 6c82950d0..e41736d79 100644 --- a/cmd/finch/nerdctl_native.go +++ b/cmd/finch/nerdctl_native.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build linux || native +//go:build linux package main diff --git a/cmd/finch/nerdctl_remote.go b/cmd/finch/nerdctl_remote.go index 5f7305708..fcabec60d 100644 --- a/cmd/finch/nerdctl_remote.go +++ b/cmd/finch/nerdctl_remote.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package main diff --git a/cmd/finch/nerdctl_remote_test.go b/cmd/finch/nerdctl_remote_test.go index c688dc64a..3ac35830b 100644 --- a/cmd/finch/nerdctl_remote_test.go +++ b/cmd/finch/nerdctl_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package main diff --git a/cmd/finch/support_bundle.go b/cmd/finch/support_bundle.go index 9118eec74..376e7b227 100644 --- a/cmd/finch/support_bundle.go +++ b/cmd/finch/support_bundle.go @@ -71,7 +71,7 @@ func (gsa *generateSupportBundleAction) runAdapter(cmd *cobra.Command, _ []strin } func (gsa *generateSupportBundleAction) run(additionalFiles []string, excludeFiles []string) error { - err := gsa.assertVMExists() + err := gsa.canCreateBundle() if err != nil { return err } diff --git a/cmd/finch/support_bundle_native.go b/cmd/finch/support_bundle_native.go index 0dc35e875..f8e444056 100644 --- a/cmd/finch/support_bundle_native.go +++ b/cmd/finch/support_bundle_native.go @@ -1,10 +1,10 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build linux || native +//go:build linux package main -func (gsa *generateSupportBundleAction) assertVMExists() error { +func (gsa *generateSupportBundleAction) canCreateBundle() error { return nil } diff --git a/cmd/finch/support_bundle_remote.go b/cmd/finch/support_bundle_remote.go index a368d0d4f..9c954dff9 100644 --- a/cmd/finch/support_bundle_remote.go +++ b/cmd/finch/support_bundle_remote.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package main @@ -11,7 +11,7 @@ import ( "github.com/runfinch/finch/pkg/lima" ) -func (gsa *generateSupportBundleAction) assertVMExists() error { +func (gsa *generateSupportBundleAction) canCreateBundle() error { status, err := lima.GetVMStatus(gsa.ncc, gsa.logger, limaInstanceName) if err != nil { return err diff --git a/cmd/finch/version_native.go b/cmd/finch/version_native.go index d38284a47..f2cda51eb 100644 --- a/cmd/finch/version_native.go +++ b/cmd/finch/version_native.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build linux || native +//go:build linux package main diff --git a/cmd/finch/version_remote.go b/cmd/finch/version_remote.go index 062228e98..954f56666 100644 --- a/cmd/finch/version_remote.go +++ b/cmd/finch/version_remote.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package main diff --git a/cmd/finch/version_remote_test.go b/cmd/finch/version_remote_test.go index 6176aa2aa..076f189c1 100644 --- a/cmd/finch/version_remote_test.go +++ b/cmd/finch/version_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package main diff --git a/cmd/finch/virtual_machine_remote.go b/cmd/finch/virtual_machine.go similarity index 100% rename from cmd/finch/virtual_machine_remote.go rename to cmd/finch/virtual_machine.go diff --git a/cmd/finch/virtual_machine_native.go b/cmd/finch/virtual_machine_native.go deleted file mode 100644 index 32f30650d..000000000 --- a/cmd/finch/virtual_machine_native.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -//go:build linux - -package main - -import ( - "github.com/runfinch/finch/pkg/command" - "github.com/runfinch/finch/pkg/config" - "github.com/runfinch/finch/pkg/flog" - "github.com/runfinch/finch/pkg/path" - - "github.com/spf13/afero" - "github.com/spf13/cobra" -) - -func virtualMachineCommands( - _ flog.Logger, - _ path.Finch, - _ command.NerdctlCmdCreator, - _ command.Creator, - _ afero.Fs, - _ *config.Finch, - _ string, - _ string, -) *cobra.Command { - return &cobra.Command{} -} diff --git a/e2e/vm/additional_disk_remote_test.go b/e2e/vm/additional_disk_remote_test.go index 5735fcfd0..ba294dc95 100644 --- a/e2e/vm/additional_disk_remote_test.go +++ b/e2e/vm/additional_disk_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package vm diff --git a/e2e/vm/config_remote_test.go b/e2e/vm/config_remote_test.go index 5233644fd..dfd043a26 100644 --- a/e2e/vm/config_remote_test.go +++ b/e2e/vm/config_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package vm diff --git a/e2e/vm/cred_helper_remote_test.go b/e2e/vm/cred_helper_remote_test.go index 398f35390..c819a447c 100644 --- a/e2e/vm/cred_helper_remote_test.go +++ b/e2e/vm/cred_helper_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package vm diff --git a/e2e/vm/finch_config_file_remote_test.go b/e2e/vm/finch_config_file_remote_test.go index 85c88c06e..7fe3a1a25 100644 --- a/e2e/vm/finch_config_file_remote_test.go +++ b/e2e/vm/finch_config_file_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package vm diff --git a/e2e/vm/lifecycle_remote_test.go b/e2e/vm/lifecycle_remote_test.go index ad39d080b..940821b2b 100644 --- a/e2e/vm/lifecycle_remote_test.go +++ b/e2e/vm/lifecycle_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package vm diff --git a/e2e/vm/soci_remote_test.go b/e2e/vm/soci_remote_test.go index 323ea2137..2c3cab3ae 100644 --- a/e2e/vm/soci_remote_test.go +++ b/e2e/vm/soci_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package vm diff --git a/e2e/vm/support_bundle_remote_test.go b/e2e/vm/support_bundle_remote_test.go index baed0eef4..6cf30d198 100644 --- a/e2e/vm/support_bundle_remote_test.go +++ b/e2e/vm/support_bundle_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package vm diff --git a/e2e/vm/version_remote_test.go b/e2e/vm/version_remote_test.go index 9befa5234..6c9ccf833 100644 --- a/e2e/vm/version_remote_test.go +++ b/e2e/vm/version_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package vm diff --git a/e2e/vm/vm_remote_test.go b/e2e/vm/vm_remote_test.go index dcb38f894..c6abbe938 100644 --- a/e2e/vm/vm_remote_test.go +++ b/e2e/vm/vm_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package vm diff --git a/pkg/command/nerdctl_darwin_test.go b/pkg/command/nerdctl_darwin_test.go index cf0254f5a..f6f6a3171 100644 --- a/pkg/command/nerdctl_darwin_test.go +++ b/pkg/command/nerdctl_darwin_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin package command_test diff --git a/pkg/command/nerdctl_native.go b/pkg/command/nerdctl_native.go index f2d8681e3..054ca937d 100644 --- a/pkg/command/nerdctl_native.go +++ b/pkg/command/nerdctl_native.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build linux || native +//go:build linux package command diff --git a/pkg/command/nerdctl_remote.go b/pkg/command/nerdctl_remote.go index 3ed1a3c1f..a23b2927d 100644 --- a/pkg/command/nerdctl_remote.go +++ b/pkg/command/nerdctl_remote.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package command diff --git a/pkg/command/nerdctl_remote_test.go b/pkg/command/nerdctl_remote_test.go index b41bf7172..d5a30211b 100644 --- a/pkg/command/nerdctl_remote_test.go +++ b/pkg/command/nerdctl_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows // Package command_test is not named as command to avoid circular dependency (command <-> mocks). package command_test diff --git a/pkg/config/defaults_remote_test.go b/pkg/config/defaults_remote_test.go index e6497517a..804a89f62 100644 --- a/pkg/config/defaults_remote_test.go +++ b/pkg/config/defaults_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package config diff --git a/pkg/config/lima_config_applier.go b/pkg/config/lima_config_applier.go index 426f7458e..40dc15da5 100644 --- a/pkg/config/lima_config_applier.go +++ b/pkg/config/lima_config_applier.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package config diff --git a/pkg/config/lima_config_applier_darwin.go b/pkg/config/lima_config_applier_darwin.go index 77f6d849c..df6814498 100644 --- a/pkg/config/lima_config_applier_darwin.go +++ b/pkg/config/lima_config_applier_darwin.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin package config diff --git a/pkg/config/lima_config_applier_windows.go b/pkg/config/lima_config_applier_windows.go index 63bf286a5..eddea3d04 100644 --- a/pkg/config/lima_config_applier_windows.go +++ b/pkg/config/lima_config_applier_windows.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build windows && !native +//go:build windows package config diff --git a/pkg/config/nerdctl_config_applier.go b/pkg/config/nerdctl_config_applier.go index 254a1453c..b03d1e5f0 100644 --- a/pkg/config/nerdctl_config_applier.go +++ b/pkg/config/nerdctl_config_applier.go @@ -1,21 +1,28 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + package config import ( "errors" "fmt" "path" + "path/filepath" + "strings" toml "github.com/pelletier/go-toml" + "github.com/pkg/sftp" "github.com/spf13/afero" + "github.com/spf13/afero/sftpfs" "github.com/runfinch/finch/pkg/fssh" ) const ( - nerdctlNamespace = "finch" + nerdctlNamespace = "finch" + nerdctlRootfulCfgPath = "/etc/nerdctl/nerdctl.toml" ) type nerdctlConfigApplier struct { @@ -52,6 +59,70 @@ func NewNerdctlApplier( } } +func addLineToBashrc(fs afero.Fs, profileFilePath string, profStr string, cmd string) (string, error) { + if !strings.Contains(profStr, cmd) { + profBufWithCmd := fmt.Sprintf("%s\n%s", profStr, cmd) + if err := afero.WriteFile(fs, profileFilePath, []byte(profBufWithCmd), 0o600); err != nil { + return "", fmt.Errorf("failed to write to profile file: %w", err) + } + return profBufWithCmd, nil + } + return profStr, nil +} + +// updateEnvironment adds variables to the user's shell's environment. Currently it uses ~/.bashrc because +// Bash is the default shell and Bash will not load ~/.profile if ~/.bash_profile exists (which it does). +// ~/.bash_profile sources ~/.bashrc, so ~/.bashrc is currently the best place to define additional variables. +// The [GNU docs for Bash] explain how these files work together in more details. +// The default location of DOCKER_CONFIG is ~/.docker/config.json. This config change sets the location to +// ~/.finch/config.json, but from the perspective of macOS (/Users//.finch/config.json). +// The reason that we don't set environment variables inside /root/.bashrc is that the vars inside it are +// not able to be picked up even if we specify `sudo -E`. We have to switch to root user in order to access them, while +// normally we would access the VM as the regular user. +// For more information on the variable, see the registry nerdctl docs. +// +// [GNU docs for Bash]: https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html +// +// [registry nerdctl docs]: https://github.com/containerd/nerdctl/blob/master/docs/registry.md + +func updateEnvironment(fs afero.Fs, fc *Finch, finchDir, homeDir, limaVMHomeDir string) error { + cmdArr := []string{ + `export DOCKER_CONFIG="$FINCH_DIR"`, + "[ -L /usr/local/bin/docker-credential-ecr-login ] " + + `|| sudo ln -s "$FINCH_DIR"/cred-helpers/docker-credential-ecr-login /usr/local/bin/`, + `[ -L /root/.aws ] || sudo ln -fs "$AWS_DIR" /root/.aws`, + } + + awsDir := fmt.Sprintf("%s/.aws", homeDir) + + if *fc.VMType == "wsl2" { + cmdArr = append([]string{ + fmt.Sprintf(`FINCH_DIR="$(/usr/bin/wslpath '%s')"`, finchDir), + fmt.Sprintf(`AWS_DIR="$(/usr/bin/wslpath '%s')"`, awsDir), + }, cmdArr...) + } else { + cmdArr = append([]string{ + fmt.Sprintf(`FINCH_DIR=%s`, finchDir), + fmt.Sprintf(`AWS_DIR=%s`, awsDir), + }, cmdArr...) + } + + profileFilePath := fmt.Sprintf("%s/.bashrc", limaVMHomeDir) + profBuf, err := afero.ReadFile(fs, profileFilePath) + if err != nil { + return fmt.Errorf("failed to read config file %q: %w", profileFilePath, err) + } + profStr := string(profBuf) + for _, element := range cmdArr { + profStr, err = addLineToBashrc(fs, profileFilePath, profStr, element) + if err != nil { + return err + } + } + + return nil +} + // updateNerdctlConfig reads from the nerdctl config and updates values. func updateNerdctlConfig(fs afero.Fs, homeDir string, rootless bool) error { nerdctlRootlessCfgPath := fmt.Sprintf("%s/.config/nerdctl/nerdctl.toml", homeDir) @@ -76,7 +147,7 @@ func updateNerdctlConfig(fs afero.Fs, homeDir string, rootless bool) error { var cfg Nerdctl cfgBuf, err := afero.ReadFile(fs, cfgPath) if err != nil { - return fmt.Errorf("updateEnvironment %q: %w", cfgPath, err) + return fmt.Errorf("failed to read config file %q: %w", cfgPath, err) } if err := toml.Unmarshal(cfgBuf, &cfg); err != nil { @@ -97,24 +168,68 @@ func updateNerdctlConfig(fs afero.Fs, homeDir string, rootless bool) error { return nil } -// Apply updates the nerdctl config. +func getLimaHomeDir(localFs afero.Fs, remoteFs afero.Fs, limaInstanceDir string, cfg *Finch) (string, error) { + var envB []byte + var envErr error + + if *cfg.VMType == "wsl2" { + envB, envErr = afero.ReadFile(localFs, filepath.Join(limaInstanceDir, "cidata", "lima.env")) + } else { + envB, envErr = afero.ReadFile(remoteFs, "/mnt/lima-cidata/lima.env") + } + + if envErr != nil { + return "", envErr + } + + var user, home string + lines := strings.Split(string(envB), "\n") + for _, l := range lines { + if strings.Contains(l, "LIMA_CIDATA_USER") { + user = strings.Split(l, "=")[1] + } else if strings.Contains(l, "LIMA_CIDATA_HOME") { + home = strings.Split(l, "=")[1] + } + } + + if home != "" { + return home, nil + } + + return "/home/" + user + ".linux", nil +} + +// Apply gets SSH and SFTP clients and uses them to update the nerdctl config. func (nca *nerdctlConfigApplier) Apply(remoteAddr string) error { - nFs, err := nca.nerdctlFs(nca.fs, nca.privateKeyPath, remoteAddr) + user := "root" + sshCfg, err := fssh.NewClientConfig(nca.fs, user, nca.privateKeyPath) + if err != nil { + return fmt.Errorf("failed to create ssh client config: %w", err) + } + + sshClient, err := nca.dialer.Dial("tcp", remoteAddr, sshCfg) if err != nil { - return fmt.Errorf("failed to get nerdctlFs: %w", err) + return fmt.Errorf("failed to setup ssh client: %w", err) } - homeDir, err := getHomeDir(nca.fs, nFs, nca.limaInstancePath, nca.fc, nca.homeDir) + sftpClient, err := sftp.NewClient(sshClient) + if err != nil { + return fmt.Errorf("failed to setup sftp client: %w", err) + } + + sftpFs := sftpfs.New(sftpClient) + + limaHomeDir, err := getLimaHomeDir(nca.fs, sftpFs, nca.limaInstancePath, nca.fc) if err != nil { return fmt.Errorf("failed to get lima home dir: %w", err) } // rootless hardcoded to false for now to match our finch.yaml file - if err := updateNerdctlConfig(nFs, homeDir, false); err != nil { + if err := updateNerdctlConfig(sftpFs, limaHomeDir, false); err != nil { return fmt.Errorf("failed to update the nerdctl config file: %w", err) } - if err := updateEnvironment(nFs, nca.fc, nca.finchDir, homeDir, homeDir); err != nil { + if err := updateEnvironment(sftpFs, nca.fc, nca.finchDir, nca.homeDir, limaHomeDir); err != nil { return fmt.Errorf("failed to update the user's .profile file: %w", err) } return nil diff --git a/pkg/config/nerdctl_config_applier_native.go b/pkg/config/nerdctl_config_applier_native.go deleted file mode 100644 index 6d4dc0664..000000000 --- a/pkg/config/nerdctl_config_applier_native.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -//go:build linux || native - -package config - -import ( - "github.com/spf13/afero" -) - -const nerdctlRootfulCfgPath = "/etc/finch/nerdctl/nerdctl.toml" - -func (nca *nerdctlConfigApplier) nerdctlFs(hostFs afero.Fs, _ string, _ string) (afero.Fs, error) { - return hostFs, nil -} - -// updateEnvironment is a noop on Linux since Finch does not fully control the user's environment -// on native Linux, unlike on macOS/Windows, via a VM. -func updateEnvironment(_ afero.Fs, _ *Finch, _, _, _ string) error { - return nil -} - -func getHomeDir(_ afero.Fs, _ afero.Fs, _ string, _ *Finch, systemHomeDir string) (string, error) { - return systemHomeDir, nil -} diff --git a/pkg/config/nerdctl_config_applier_remote.go b/pkg/config/nerdctl_config_applier_remote.go deleted file mode 100644 index 8813f88e5..000000000 --- a/pkg/config/nerdctl_config_applier_remote.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -//go:build (darwin || windows) && !native - -package config - -import ( - "fmt" - "path/filepath" - "strings" - - "github.com/pkg/sftp" - "github.com/spf13/afero" - "github.com/spf13/afero/sftpfs" - - "github.com/runfinch/finch/pkg/fssh" -) - -const nerdctlRootfulCfgPath = "/etc/nerdctl/nerdctl.toml" - -func (nca *nerdctlConfigApplier) nerdctlFs(hostFs afero.Fs, privateKeyPath string, remoteAddr string) (afero.Fs, error) { - user := "root" - sshCfg, err := fssh.NewClientConfig(hostFs, user, privateKeyPath) - if err != nil { - return nil, fmt.Errorf("failed to create ssh client config: %w", err) - } - - sshClient, err := nca.dialer.Dial("tcp", remoteAddr, sshCfg) - if err != nil { - return nil, fmt.Errorf("failed to setup ssh client: %w", err) - } - - sftpClient, err := sftp.NewClient(sshClient) - if err != nil { - return nil, fmt.Errorf("failed to setup sftp client: %w", err) - } - - return sftpfs.New(sftpClient), nil -} - -// updateEnvironment adds variables to the user's shell's environment. Currently it uses ~/.bashrc because -// Bash is the default shell and Bash will not load ~/.profile if ~/.bash_profile exists (which it does). -// ~/.bash_profile sources ~/.bashrc, so ~/.bashrc is currently the best place to define additional variables. -// The [GNU docs for Bash] explain how these files work together in more details. -// The default location of DOCKER_CONFIG is ~/.docker/config.json. This config change sets the location to -// ~/.finch/config.json, but from the perspective of macOS (/Users//.finch/config.json). -// The reason that we don't set environment variables inside /root/.bashrc is that the vars inside it are -// not able to be picked up even if we specify `sudo -E`. We have to switch to root user in order to access them, while -// normally we would access the VM as the regular user. -// For more information on the variable, see the registry nerdctl docs. -// -// [GNU docs for Bash]: https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html -// -// [registry nerdctl docs]: https://github.com/containerd/nerdctl/blob/master/docs/registry.md - -func updateEnvironment(fs afero.Fs, fc *Finch, finchDir, homeDir, limaVMHomeDir string) error { - cmdArr := []string{ - `export DOCKER_CONFIG="$FINCH_DIR"`, - "[ -L /usr/local/bin/docker-credential-ecr-login ] " + - `|| sudo ln -s "$FINCH_DIR"/cred-helpers/docker-credential-ecr-login /usr/local/bin/`, - `[ -L /root/.aws ] || sudo ln -fs "$AWS_DIR" /root/.aws`, - } - - awsDir := fmt.Sprintf("%s/.aws", homeDir) - - if *fc.VMType == "wsl2" { - cmdArr = append([]string{ - fmt.Sprintf(`FINCH_DIR="$(/usr/bin/wslpath '%s')"`, finchDir), - fmt.Sprintf(`AWS_DIR="$(/usr/bin/wslpath '%s')"`, awsDir), - }, cmdArr...) - } else { - cmdArr = append([]string{ - fmt.Sprintf(`FINCH_DIR=%s`, finchDir), - fmt.Sprintf(`AWS_DIR=%s`, awsDir), - }, cmdArr...) - } - - profileFilePath := fmt.Sprintf("%s/.bashrc", limaVMHomeDir) - profBuf, err := afero.ReadFile(fs, profileFilePath) - if err != nil { - return fmt.Errorf("failed to read config file %q: %w", profileFilePath, err) - } - profStr := string(profBuf) - for _, element := range cmdArr { - profStr, err = addLineToBashrc(fs, profileFilePath, profStr, element) - if err != nil { - return err - } - } - - return nil -} - -func getHomeDir(localFs afero.Fs, remoteFs afero.Fs, limaInstanceDir string, cfg *Finch, _ string) (string, error) { - var envB []byte - var envErr error - - if *cfg.VMType == "wsl2" { - envB, envErr = afero.ReadFile(localFs, filepath.Join(limaInstanceDir, "cidata", "lima.env")) - } else { - envB, envErr = afero.ReadFile(remoteFs, "/mnt/lima-cidata/lima.env") - } - - if envErr != nil { - return "", envErr - } - - var user, home string - lines := strings.Split(string(envB), "\n") - for _, l := range lines { - if strings.Contains(l, "LIMA_CIDATA_USER") { - user = strings.Split(l, "=")[1] - } else if strings.Contains(l, "LIMA_CIDATA_HOME") { - home = strings.Split(l, "=")[1] - } - } - - if home != "" { - return home, nil - } - - return "/home/" + user + ".linux", nil -} - -func addLineToBashrc(fs afero.Fs, profileFilePath string, profStr string, cmd string) (string, error) { - if !strings.Contains(profStr, cmd) { - profBufWithCmd := fmt.Sprintf("%s\n%s", profStr, cmd) - if err := afero.WriteFile(fs, profileFilePath, []byte(profBufWithCmd), 0o600); err != nil { - return "", fmt.Errorf("failed to write to profile file: %w", err) - } - return profBufWithCmd, nil - } - return profStr, nil -} diff --git a/pkg/config/nerdctl_config_applier_remote_test.go b/pkg/config/nerdctl_config_applier_test.go similarity index 99% rename from pkg/config/nerdctl_config_applier_remote_test.go rename to pkg/config/nerdctl_config_applier_test.go index 401ed859e..449bc0086 100644 --- a/pkg/config/nerdctl_config_applier_remote_test.go +++ b/pkg/config/nerdctl_config_applier_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package config diff --git a/pkg/config/validate_darwin.go b/pkg/config/validate_darwin.go index 10fdc8a2c..141fedffe 100644 --- a/pkg/config/validate_darwin.go +++ b/pkg/config/validate_darwin.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin package config diff --git a/pkg/config/validate_natvie.go b/pkg/config/validate_natvie.go index 1d64d271b..972a77bd7 100644 --- a/pkg/config/validate_natvie.go +++ b/pkg/config/validate_natvie.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build linux || native +//go:build linux package config diff --git a/pkg/config/validate_windows.go b/pkg/config/validate_windows.go index 4518a6cff..0eb78c841 100644 --- a/pkg/config/validate_windows.go +++ b/pkg/config/validate_windows.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build windows && !native +//go:build windows package config diff --git a/pkg/dependency/vmnet/binaries_unix.go b/pkg/dependency/vmnet/binaries_unix.go index 10c1659d3..3bfce9d74 100644 --- a/pkg/dependency/vmnet/binaries_unix.go +++ b/pkg/dependency/vmnet/binaries_unix.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin package vmnet diff --git a/pkg/dependency/vmnet/binaries_unix_test.go b/pkg/dependency/vmnet/binaries_unix_test.go index d68872cff..a1612c96f 100644 --- a/pkg/dependency/vmnet/binaries_unix_test.go +++ b/pkg/dependency/vmnet/binaries_unix_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin // Ensures that the binaries required for networking are installed in a privileged location. // More information here: https://github.com/lima-vm/socket_vmnet diff --git a/pkg/dependency/vmnet/sudoers_file_unix.go b/pkg/dependency/vmnet/sudoers_file_unix.go index 9c81048dc..8d5611f42 100644 --- a/pkg/dependency/vmnet/sudoers_file_unix.go +++ b/pkg/dependency/vmnet/sudoers_file_unix.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin package vmnet diff --git a/pkg/dependency/vmnet/sudoers_file_unix_test.go b/pkg/dependency/vmnet/sudoers_file_unix_test.go index 0a19ea537..ba382b8fd 100644 --- a/pkg/dependency/vmnet/sudoers_file_unix_test.go +++ b/pkg/dependency/vmnet/sudoers_file_unix_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin // Ensures that output of `lima sudoers` is output to the correct directory. // This is necessary for networking to work without prompting the user diff --git a/pkg/dependency/vmnet/update_network_lima_config_unix.go b/pkg/dependency/vmnet/update_network_lima_config_unix.go index 9235ef72d..bd89f6d8a 100644 --- a/pkg/dependency/vmnet/update_network_lima_config_unix.go +++ b/pkg/dependency/vmnet/update_network_lima_config_unix.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin package vmnet diff --git a/pkg/dependency/vmnet/update_network_lima_config_unix_test.go b/pkg/dependency/vmnet/update_network_lima_config_unix_test.go index 0ec5941f8..8c47be1ac 100644 --- a/pkg/dependency/vmnet/update_network_lima_config_unix_test.go +++ b/pkg/dependency/vmnet/update_network_lima_config_unix_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin package vmnet diff --git a/pkg/dependency/vmnet/vmnet_unix.go b/pkg/dependency/vmnet/vmnet_unix.go index 21f299d07..33b137975 100644 --- a/pkg/dependency/vmnet/vmnet_unix.go +++ b/pkg/dependency/vmnet/vmnet_unix.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin // Package vmnet handles installation and configuration of dependencies needed for Lima's managed networking // and port-forwarding to work, with minimal user interaction. diff --git a/pkg/dependency/vmnet/vmnet_unix_test.go b/pkg/dependency/vmnet/vmnet_unix_test.go index d20dbcfee..1f904044f 100644 --- a/pkg/dependency/vmnet/vmnet_unix_test.go +++ b/pkg/dependency/vmnet/vmnet_unix_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native +//go:build darwin package vmnet diff --git a/pkg/disk/disk.go b/pkg/disk/disk.go index e6ff4ca05..1526d53e8 100644 --- a/pkg/disk/disk.go +++ b/pkg/disk/disk.go @@ -1,6 +1,8 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +//go:build darwin || windows + // Package disk manages the persistent disk used to save containerd user data // //go:generate mockgen -copyright_file=../../copyright_header -destination=../mocks/pkg_disk_disk.go -package=mocks -mock_names UserDataDiskManager=UserDataDiskManager,diskFS=MockdiskFS -source=disk.go . diff --git a/pkg/disk/disk_darwin.go b/pkg/disk/disk_darwin.go index c7ddbc511..d4eb1cbc3 100644 --- a/pkg/disk/disk_darwin.go +++ b/pkg/disk/disk_darwin.go @@ -1,8 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build darwin && !native -// +build darwin,!native +//go:build darwin package disk diff --git a/pkg/disk/disk_native.go b/pkg/disk/disk_native.go deleted file mode 100644 index 9fcf009c9..000000000 --- a/pkg/disk/disk_native.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 - -//go:build linux || native -// +build linux native - -package disk - -// EnsureUserDataDisk checks the current disk configuration and fixes it if needed. -func (m *userDataDiskManager) EnsureUserDataDisk() error { - return nil -} - -// DetachUserDataDisk unmounts the disk in wsl. -func (m *userDataDiskManager) DetachUserDataDisk() error { - return nil -} diff --git a/pkg/path/finch_remote_darwin.go b/pkg/path/finch_darwin.go similarity index 100% rename from pkg/path/finch_remote_darwin.go rename to pkg/path/finch_darwin.go diff --git a/pkg/path/finch_native_linux.go b/pkg/path/finch_linux.go similarity index 100% rename from pkg/path/finch_native_linux.go rename to pkg/path/finch_linux.go diff --git a/pkg/path/finch_remote.go b/pkg/path/finch_remote.go index edaab0218..104f603e5 100644 --- a/pkg/path/finch_remote.go +++ b/pkg/path/finch_remote.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows // Package path contains functions to find/calculate path used in the project. package path diff --git a/pkg/path/finch_remote_test.go b/pkg/path/finch_remote_test.go index 2b2230da5..c955489d5 100644 --- a/pkg/path/finch_remote_test.go +++ b/pkg/path/finch_remote_test.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package path diff --git a/pkg/path/finch_remote_windows.go b/pkg/path/finch_windows.go similarity index 100% rename from pkg/path/finch_remote_windows.go rename to pkg/path/finch_windows.go diff --git a/pkg/support/config_remote.go b/pkg/support/config_remote.go index eeaa28fd5..16d984dab 100644 --- a/pkg/support/config_remote.go +++ b/pkg/support/config_remote.go @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -//go:build (darwin || windows) && !native +//go:build darwin || windows package support From c83c38b2761c7b4646a70b9d72b3191247338926 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Mon, 5 Aug 2024 12:05:37 -0400 Subject: [PATCH 35/37] remove unnecessary remote in names Signed-off-by: Justin Alvarez --- .../{additional_disk_remote_test.go => additional_disk_test.go} | 0 e2e/vm/{lifecycle_remote_test.go => lifecycle_test.go} | 0 e2e/vm/{vm_remote_test.go => vm_test.go} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename e2e/vm/{additional_disk_remote_test.go => additional_disk_test.go} (100%) rename e2e/vm/{lifecycle_remote_test.go => lifecycle_test.go} (100%) rename e2e/vm/{vm_remote_test.go => vm_test.go} (100%) diff --git a/e2e/vm/additional_disk_remote_test.go b/e2e/vm/additional_disk_test.go similarity index 100% rename from e2e/vm/additional_disk_remote_test.go rename to e2e/vm/additional_disk_test.go diff --git a/e2e/vm/lifecycle_remote_test.go b/e2e/vm/lifecycle_test.go similarity index 100% rename from e2e/vm/lifecycle_remote_test.go rename to e2e/vm/lifecycle_test.go diff --git a/e2e/vm/vm_remote_test.go b/e2e/vm/vm_test.go similarity index 100% rename from e2e/vm/vm_remote_test.go rename to e2e/vm/vm_test.go From 3e3f4c3fc6c760b4eb9e8752075e8409ba42b787 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Tue, 6 Aug 2024 14:46:31 -0400 Subject: [PATCH 36/37] fix unit tests Signed-off-by: Justin Alvarez --- pkg/config/nerdctl_config_applier_test.go | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/pkg/config/nerdctl_config_applier_test.go b/pkg/config/nerdctl_config_applier_test.go index 449bc0086..b8076d8b9 100644 --- a/pkg/config/nerdctl_config_applier_test.go +++ b/pkg/config/nerdctl_config_applier_test.go @@ -258,12 +258,10 @@ func TestNerdctlConfigApplier_Apply(t *testing.T) { remoteAddr: "", mockSvc: func(_ *testing.T, _ afero.Fs, _ *mocks.Dialer) { }, - want: fmt.Errorf( - "failed to get nerdctlFs: %w", - fmt.Errorf("failed to create ssh client config: %w", fmt.Errorf( - "failed to open private key file: %w", - &fs.PathError{Op: "open", Path: privateKeyPath, Err: errors.New("file does not exist")}, - )), + want: fmt.Errorf("failed to create ssh client config: %w", fmt.Errorf( + "failed to open private key file: %w", + &fs.PathError{Op: "open", Path: privateKeyPath, Err: errors.New("file does not exist")}, + ), ), }, { @@ -276,8 +274,7 @@ func TestNerdctlConfigApplier_Apply(t *testing.T) { d.EXPECT().Dial("tcp", "deadbeef", gomock.Any()).Return(nil, fmt.Errorf("some error")) }, - want: fmt.Errorf("failed to get nerdctlFs: %w", - fmt.Errorf("failed to setup ssh client: %w", fmt.Errorf("some error"))), + want: fmt.Errorf("failed to setup ssh client: %w", fmt.Errorf("some error")), }, } From 601e040d2576a8e86aed1e336f433d76441316a1 Mon Sep 17 00:00:00 2001 From: Justin Alvarez Date: Wed, 21 Aug 2024 12:00:22 -0400 Subject: [PATCH 37/37] fix BuildkitSocketPath Signed-off-by: Justin Alvarez --- cmd/finch/main_native.go | 2 +- pkg/command/nerdctl_native.go | 2 +- pkg/path/finch_linux.go | 10 +++++++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/cmd/finch/main_native.go b/cmd/finch/main_native.go index d83052abb..44c3f3896 100644 --- a/cmd/finch/main_native.go +++ b/cmd/finch/main_native.go @@ -55,7 +55,7 @@ var newApp = func( ncc := command.NewNerdctlCmdCreator(ecc, logger, fp.NerdctlConfigFilePath(finchRootPath), - fp.BuildkitSocketPath(finchRootPath), + fp.BuildkitSocketPath(), fp.FinchDependencyBinDir(), system.NewStdLib(), ) diff --git a/pkg/command/nerdctl_native.go b/pkg/command/nerdctl_native.go index 054ca937d..7fc9997d3 100644 --- a/pkg/command/nerdctl_native.go +++ b/pkg/command/nerdctl_native.go @@ -55,7 +55,7 @@ func (ncc *nerdctlCmdCreator) create(stdin io.Reader, stdout, stderr io.Writer, env := append( newPathEnv, fmt.Sprintf("NERDCTL_TOML=%s", ncc.nerdctlConfigPath), - fmt.Sprintf("BUILDKIT_HOST=%s", ncc.buildkitSocketPath), + fmt.Sprintf("BUILDKIT_HOST=unix://%s", ncc.buildkitSocketPath), ) cmd.SetEnv(env) diff --git a/pkg/path/finch_linux.go b/pkg/path/finch_linux.go index f29b843c4..1aa0988d8 100644 --- a/pkg/path/finch_linux.go +++ b/pkg/path/finch_linux.go @@ -31,16 +31,20 @@ func (Finch) NerdctlConfigFilePath(rootDir string) string { } // BuildkitSocketPath returns the path to the Buildkit socket file. -func (Finch) BuildkitSocketPath(rootDir string) string { - return filepath.Join(rootDir, "buildkit", "buildkitd.toml") +func (fp Finch) BuildkitSocketPath() string { + return filepath.Join(fp.FinchRuntimeDataDir(), "buildkit", "buildkitd.sock") } // FinchDependencyBinDir returns the path to Finch's local helper or dependency binaries. -// Currently used for vended version of BuildKit. func (Finch) FinchDependencyBinDir() string { return filepath.Join("/", "usr", "libexec", "finch") } +// FinchRuntimeDataDir returns the path to Finch's runtime data directory, used for state of running programs. +func (Finch) FinchRuntimeDataDir() string { + return filepath.Join("/", "var", "lib", "finch") +} + // FindFinch finds the installation path of Finch. func FindFinch(deps FinchFinderDeps) (Finch, error) { exe, err := deps.Executable()