Skip to content

Commit

Permalink
Make the location for .crc directory configurable
Browse files Browse the repository at this point in the history
- Add a new config key called crc-dir
- Initialise Crc base directory variables based on the saved config
- New config will take effect after rerunning `crc setup`
  • Loading branch information
vyasgun committed Apr 25, 2024
1 parent ec6cbfb commit ae9585f
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 8 deletions.
2 changes: 1 addition & 1 deletion cmd/crc-embedder/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ when building the crc executable for release`,
}

func init() {
err := constants.EnsureBaseDirectoriesExist()
err := constants.EnsureBaseDirectoriesExist("")
if err != nil {
fmt.Println("CRC base directories are missing: ", err)
os.Exit(1)
Expand Down
7 changes: 4 additions & 3 deletions cmd/crc/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,16 @@ var (
)

func init() {
if err := constants.EnsureBaseDirectoriesExist(); err != nil {
logging.Fatal(err.Error())
}
var err error
config, viper, err = newConfig()
if err != nil {
logging.Fatal(err.Error())
}

if err := constants.EnsureBaseDirectoriesExist(crcConfig.GetConfigDir(config)); err != nil {
logging.Fatal(err.Error())
}

if err := setProxyDefaults(); err != nil {
logging.Warn(err.Error())
}
Expand Down
14 changes: 12 additions & 2 deletions pkg/crc/config/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const (
EmergencyLogin = "enable-emergency-login"
PersistentVolumeSize = "persistent-volume-size"
EnableBundleQuayFallback = "enable-bundle-quay-fallback"
CrcDir = "crc-dir"
)

func RegisterSettings(cfg *Config) {
Expand Down Expand Up @@ -141,13 +142,18 @@ func RegisterSettings(cfg *Config) {

cfg.AddSetting(EnableBundleQuayFallback, false, ValidateBool, SuccessfullyApplied,
"If bundle download from the default location fails, fallback to quay.io (true/false, default: false)")
cfg.AddSetting(CrcDir, constants.GetHomeDir(), validateDirectory, RequiresCRCSetup,
"Location for .crc")

if err := cfg.RegisterNotifier(Preset, presetChanged); err != nil {
if err := cfg.RegisterNotifier(Preset, settingChanged); err != nil {
logging.Debugf("Failed to register notifier for Preset: %v", err)
}
if err := cfg.RegisterNotifier(CrcDir, settingChanged); err != nil {
logging.Debugf("Failed to register notifier for .crc directory: %v", err)
}
}

func presetChanged(cfg *Config, _ string, _ interface{}) {
func settingChanged(cfg *Config, _ string, _ interface{}) {
UpdateDefaults(cfg)
}

Expand All @@ -167,6 +173,10 @@ func GetPreset(config Storage) preset.Preset {
return preset.ParsePreset(config.Get(Preset).AsString())
}

func GetConfigDir(config Storage) string {
return config.Get(CrcDir).AsString()
}

func defaultNetworkMode() network.Mode {
if runtime.GOOS != "linux" {
return network.UserNetworkingMode
Expand Down
26 changes: 26 additions & 0 deletions pkg/crc/config/settings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config

import (
"fmt"
"os"
"path/filepath"
"testing"

Expand Down Expand Up @@ -182,3 +183,28 @@ func TestPath(t *testing.T) {
IsSecret: false,
}, cfg.Get(ProxyCAFile))
}

func TestDirectory(t *testing.T) {
cfg, err := newInMemoryConfig()
require.NoError(t, err)

assert.Equal(t, SettingValue{
Value: constants.GetHomeDir(),
Invalid: false,
IsDefault: true,
IsSecret: false,
}, cfg.Get(CrcDir))

tmpDir, err := os.MkdirTemp("", "tempdir")
require.NoError(t, err)
defer os.Remove(tmpDir)
_, err = cfg.Set(CrcDir, tmpDir)
require.NoError(t, err)

assert.Equal(t, SettingValue{
Value: tmpDir,
Invalid: false,
IsDefault: false,
IsSecret: false,
}, cfg.Get(CrcDir))
}
7 changes: 7 additions & 0 deletions pkg/crc/config/validations.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,13 @@ func validatePath(value interface{}) (bool, string) {
return true, ""
}

func validateDirectory(value interface{}) (bool, string) {
if err := validation.ValidateDirectory(cast.ToString(value)); err != nil {
return false, err.Error()
}
return true, ""
}

// validateHTTPProxy checks if given URI is valid for a HTTP proxy
func validateHTTPProxy(value interface{}) (bool, string) {
if err := httpproxy.ValidateProxyURL(cast.ToString(value), false); err != nil {
Expand Down
23 changes: 22 additions & 1 deletion pkg/crc/constants/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,8 @@ func GetHomeDir() string {
}

// EnsureBaseDirectoriesExist creates ~/.crc, ~/.crc/bin and ~/.crc/cache directories if it is not present
func EnsureBaseDirectoriesExist() error {
func EnsureBaseDirectoriesExist(configDir string) error {
initialiseAllDirectories(configDir)
baseDirectories := []string{CrcBaseDir, MachineCacheDir, CrcBinDir}
for _, baseDir := range baseDirectories {
err := os.MkdirAll(baseDir, 0750)
Expand All @@ -175,6 +176,26 @@ func EnsureBaseDirectoriesExist() error {
return nil
}

func initialiseAllDirectories(crcDir string) {
if crcDir == "" {
return
}
CrcBaseDir = filepath.Join(crcDir, ".crc")
CrcBinDir = filepath.Join(CrcBaseDir, "bin")
CrcOcBinDir = filepath.Join(CrcBinDir, "oc")
CrcPodmanBinDir = filepath.Join(CrcBinDir, "podman")
CrcSymlinkPath = filepath.Join(CrcBinDir, "crc")
ConfigPath = filepath.Join(CrcBaseDir, ConfigFile)
LogFilePath = filepath.Join(CrcBaseDir, LogFile)
DaemonLogFilePath = filepath.Join(CrcBaseDir, DaemonLogFile)
MachineBaseDir = CrcBaseDir
MachineCacheDir = filepath.Join(MachineBaseDir, "cache")
MachineInstanceDir = filepath.Join(MachineBaseDir, "machines")
DaemonSocketPath = filepath.Join(CrcBaseDir, "crc.sock")
KubeconfigFilePath = filepath.Join(MachineInstanceDir, DefaultName, "kubeconfig")
PasswdFilePath = filepath.Join(MachineInstanceDir, DefaultName, "passwd")
}

func GetPublicKeyPath() string {
return filepath.Join(MachineInstanceDir, DefaultName, "id_ecdsa.pub")
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/crc/preflight/preflight_checks_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
func bundleCheck(bundlePath string, preset crcpreset.Preset, enableBundleQuayFallback bool) Check {
return Check{
configKeySuffix: "check-bundle-extracted",
checkDescription: "Checking if CRC bundle is extracted in '$HOME/.crc'",
checkDescription: fmt.Sprintf("Checking if CRC bundle is extracted in %q", bundlePath),
check: checkBundleExtracted(bundlePath),
fixDescription: "Getting bundle for the CRC executable",
fix: fixBundleExtracted(bundlePath, preset, enableBundleQuayFallback),
Expand Down
10 changes: 10 additions & 0 deletions pkg/crc/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,16 @@ func ValidatePath(path string) error {
return nil
}

// ValidateDirectory checks if provided path exists and has sufficient permissions
func ValidateDirectory(path string) error {
file, err := os.CreateTemp(path, "tempfile")
if err != nil {
return &invalidPath{path: path}
}
defer os.Remove(file.Name())
return nil
}

type imagePullSecret struct {
Auths map[string]map[string]interface{} `json:"auths"`
}
Expand Down

0 comments on commit ae9585f

Please sign in to comment.