From 3b60b81a3b539b0eb2a9fc64408a674d3cf5b850 Mon Sep 17 00:00:00 2001 From: Doug Hellmann Date: Sat, 8 Apr 2023 09:40:38 -0400 Subject: [PATCH] USHIFT-1053: remove user data dir Remove the user data directory and always use the global path. --- etcd/cmd/microshift-etcd/run.go | 5 +- .../github.com/mitchellh/go-homedir/LICENSE | 21 --- .../github.com/mitchellh/go-homedir/README.md | 14 -- .../mitchellh/go-homedir/homedir.go | 167 ------------------ .../openshift/microshift/pkg/config/files.go | 27 +-- .../microshift/pkg/config/kubeconfig.go | 4 +- .../openshift/microshift/pkg/config/node.go | 12 +- etcd/vendor/modules.txt | 1 - pkg/cmd/init.go | 10 +- pkg/cmd/run.go | 2 +- pkg/components/components.go | 2 - pkg/components/controllers.go | 4 +- pkg/components/networking.go | 2 +- pkg/config/config_test.go | 28 ++- pkg/config/files.go | 27 +-- pkg/config/kubeconfig.go | 4 +- pkg/config/node.go | 12 +- pkg/controllers/etcd.go | 2 +- pkg/controllers/kube-apiserver.go | 12 +- pkg/controllers/kube-controller-manager.go | 7 +- pkg/controllers/kube-scheduler.go | 4 +- .../openshift-route-controller-manager.go | 4 +- pkg/node/kubelet.go | 12 +- .../github.com/mitchellh/go-homedir/LICENSE | 21 --- .../github.com/mitchellh/go-homedir/README.md | 14 -- .../mitchellh/go-homedir/homedir.go | 167 ------------------ vendor/modules.txt | 1 - 27 files changed, 61 insertions(+), 525 deletions(-) delete mode 100644 etcd/vendor/github.com/mitchellh/go-homedir/LICENSE delete mode 100644 etcd/vendor/github.com/mitchellh/go-homedir/README.md delete mode 100644 etcd/vendor/github.com/mitchellh/go-homedir/homedir.go delete mode 100644 vendor/github.com/mitchellh/go-homedir/LICENSE delete mode 100644 vendor/github.com/mitchellh/go-homedir/README.md delete mode 100644 vendor/github.com/mitchellh/go-homedir/homedir.go diff --git a/etcd/cmd/microshift-etcd/run.go b/etcd/cmd/microshift-etcd/run.go index a9a56de9c9..5e78d02dca 100644 --- a/etcd/cmd/microshift-etcd/run.go +++ b/etcd/cmd/microshift-etcd/run.go @@ -67,13 +67,12 @@ func (s *EtcdService) configure(cfg *config.Config) { s.maxFragmentedPercentage = cfg.Etcd.MaxFragmentedPercentage s.defragCheckFreq = cfg.Etcd.DefragCheckFreq - microshiftDataDir := config.GetDataDir() - certsDir := cryptomaterial.CertsDirectory(microshiftDataDir) + certsDir := cryptomaterial.CertsDirectory(config.DataDir) etcdServingCertDir := cryptomaterial.EtcdServingCertDir(certsDir) etcdPeerCertDir := cryptomaterial.EtcdPeerCertDir(certsDir) etcdSignerCertPath := cryptomaterial.CACertPath(cryptomaterial.EtcdSignerDir(certsDir)) - dataDir := filepath.Join(microshiftDataDir, s.Name()) + dataDir := filepath.Join(config.DataDir, s.Name()) // based on https://github.com/openshift/cluster-etcd-operator/blob/master/bindata/bootkube/bootstrap-manifests/etcd-member-pod.yaml#L19 s.etcdCfg = etcd.NewConfig() diff --git a/etcd/vendor/github.com/mitchellh/go-homedir/LICENSE b/etcd/vendor/github.com/mitchellh/go-homedir/LICENSE deleted file mode 100644 index f9c841a51e..0000000000 --- a/etcd/vendor/github.com/mitchellh/go-homedir/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Mitchell Hashimoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/etcd/vendor/github.com/mitchellh/go-homedir/README.md b/etcd/vendor/github.com/mitchellh/go-homedir/README.md deleted file mode 100644 index d70706d5b3..0000000000 --- a/etcd/vendor/github.com/mitchellh/go-homedir/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# go-homedir - -This is a Go library for detecting the user's home directory without -the use of cgo, so the library can be used in cross-compilation environments. - -Usage is incredibly simple, just call `homedir.Dir()` to get the home directory -for a user, and `homedir.Expand()` to expand the `~` in a path to the home -directory. - -**Why not just use `os/user`?** The built-in `os/user` package requires -cgo on Darwin systems. This means that any Go code that uses that package -cannot cross compile. But 99% of the time the use for `os/user` is just to -retrieve the home directory, which we can do for the current user without -cgo. This library does that, enabling cross-compilation. diff --git a/etcd/vendor/github.com/mitchellh/go-homedir/homedir.go b/etcd/vendor/github.com/mitchellh/go-homedir/homedir.go deleted file mode 100644 index 25378537ea..0000000000 --- a/etcd/vendor/github.com/mitchellh/go-homedir/homedir.go +++ /dev/null @@ -1,167 +0,0 @@ -package homedir - -import ( - "bytes" - "errors" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" -) - -// DisableCache will disable caching of the home directory. Caching is enabled -// by default. -var DisableCache bool - -var homedirCache string -var cacheLock sync.RWMutex - -// Dir returns the home directory for the executing user. -// -// This uses an OS-specific method for discovering the home directory. -// An error is returned if a home directory cannot be detected. -func Dir() (string, error) { - if !DisableCache { - cacheLock.RLock() - cached := homedirCache - cacheLock.RUnlock() - if cached != "" { - return cached, nil - } - } - - cacheLock.Lock() - defer cacheLock.Unlock() - - var result string - var err error - if runtime.GOOS == "windows" { - result, err = dirWindows() - } else { - // Unix-like system, so just assume Unix - result, err = dirUnix() - } - - if err != nil { - return "", err - } - homedirCache = result - return result, nil -} - -// Expand expands the path to include the home directory if the path -// is prefixed with `~`. If it isn't prefixed with `~`, the path is -// returned as-is. -func Expand(path string) (string, error) { - if len(path) == 0 { - return path, nil - } - - if path[0] != '~' { - return path, nil - } - - if len(path) > 1 && path[1] != '/' && path[1] != '\\' { - return "", errors.New("cannot expand user-specific home dir") - } - - dir, err := Dir() - if err != nil { - return "", err - } - - return filepath.Join(dir, path[1:]), nil -} - -// Reset clears the cache, forcing the next call to Dir to re-detect -// the home directory. This generally never has to be called, but can be -// useful in tests if you're modifying the home directory via the HOME -// env var or something. -func Reset() { - cacheLock.Lock() - defer cacheLock.Unlock() - homedirCache = "" -} - -func dirUnix() (string, error) { - homeEnv := "HOME" - if runtime.GOOS == "plan9" { - // On plan9, env vars are lowercase. - homeEnv = "home" - } - - // First prefer the HOME environmental variable - if home := os.Getenv(homeEnv); home != "" { - return home, nil - } - - var stdout bytes.Buffer - - // If that fails, try OS specific commands - if runtime.GOOS == "darwin" { - cmd := exec.Command("sh", "-c", `dscl -q . -read /Users/"$(whoami)" NFSHomeDirectory | sed 's/^[^ ]*: //'`) - cmd.Stdout = &stdout - if err := cmd.Run(); err == nil { - result := strings.TrimSpace(stdout.String()) - if result != "" { - return result, nil - } - } - } else { - cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - // If the error is ErrNotFound, we ignore it. Otherwise, return it. - if err != exec.ErrNotFound { - return "", err - } - } else { - if passwd := strings.TrimSpace(stdout.String()); passwd != "" { - // username:password:uid:gid:gecos:home:shell - passwdParts := strings.SplitN(passwd, ":", 7) - if len(passwdParts) > 5 { - return passwdParts[5], nil - } - } - } - } - - // If all else fails, try the shell - stdout.Reset() - cmd := exec.Command("sh", "-c", "cd && pwd") - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - return "", err - } - - result := strings.TrimSpace(stdout.String()) - if result == "" { - return "", errors.New("blank output when reading home directory") - } - - return result, nil -} - -func dirWindows() (string, error) { - // First prefer the HOME environmental variable - if home := os.Getenv("HOME"); home != "" { - return home, nil - } - - // Prefer standard environment variable USERPROFILE - if home := os.Getenv("USERPROFILE"); home != "" { - return home, nil - } - - drive := os.Getenv("HOMEDRIVE") - path := os.Getenv("HOMEPATH") - home := drive + path - if drive == "" || path == "" { - return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank") - } - - return home, nil -} diff --git a/etcd/vendor/github.com/openshift/microshift/pkg/config/files.go b/etcd/vendor/github.com/openshift/microshift/pkg/config/files.go index 4b972cfa48..87614c59ab 100644 --- a/etcd/vendor/github.com/openshift/microshift/pkg/config/files.go +++ b/etcd/vendor/github.com/openshift/microshift/pkg/config/files.go @@ -1,18 +1,15 @@ package config import ( - "errors" "fmt" "os" - "github.com/mitchellh/go-homedir" "sigs.k8s.io/yaml" ) const ( - defaultUserDataDir = "~/.microshift/data" - ConfigFile = "/etc/microshift/config.yaml" - defaultGlobalDataDir = "/var/lib/microshift" + ConfigFile = "/etc/microshift/config.yaml" + DataDir = "/var/lib/microshift" // for files managed via management system in /etc, i.e. user applications defaultManifestDirEtc = "/etc/microshift/manifests" // for files embedded in ostree. i.e. cni/other component customizations @@ -20,33 +17,13 @@ const ( ) var ( - dataDir = findDataDir() manifestsDir = findManifestsDir() ) -func GetDataDir() string { - return dataDir -} - func GetManifestsDir() []string { return manifestsDir } -// Returns the default user data dir if it exists or the user is non-root. -// Returns the default global data dir otherwise. -func findDataDir() string { - userDataDir, _ := homedir.Expand(defaultUserDataDir) - if _, err := os.Stat(userDataDir); errors.Is(err, os.ErrNotExist) { - if os.Geteuid() > 0 { - return userDataDir - } else { - return defaultGlobalDataDir - } - } else { - return userDataDir - } -} - // Returns the default manifests directories func findManifestsDir() []string { var manifestsDir = []string{defaultManifestDirLib, defaultManifestDirEtc} diff --git a/etcd/vendor/github.com/openshift/microshift/pkg/config/kubeconfig.go b/etcd/vendor/github.com/openshift/microshift/pkg/config/kubeconfig.go index 1e33b07b96..72a85466f5 100644 --- a/etcd/vendor/github.com/openshift/microshift/pkg/config/kubeconfig.go +++ b/etcd/vendor/github.com/openshift/microshift/pkg/config/kubeconfig.go @@ -16,9 +16,9 @@ const ( // KubeConfigPath returns the path to the specified kubeconfig file. func (cfg *Config) KubeConfigPath(id KubeConfigID) string { - return filepath.Join(dataDir, "resources", string(id), "kubeconfig") + return filepath.Join(DataDir, "resources", string(id), "kubeconfig") } func (cfg *Config) KubeConfigAdminPath(id string) string { - return filepath.Join(dataDir, "resources", string(KubeAdmin), id, "kubeconfig") + return filepath.Join(DataDir, "resources", string(KubeAdmin), id, "kubeconfig") } diff --git a/etcd/vendor/github.com/openshift/microshift/pkg/config/node.go b/etcd/vendor/github.com/openshift/microshift/pkg/config/node.go index 13eb6e6a90..84ba694bce 100644 --- a/etcd/vendor/github.com/openshift/microshift/pkg/config/node.go +++ b/etcd/vendor/github.com/openshift/microshift/pkg/config/node.go @@ -36,13 +36,13 @@ func (c *Config) CanonicalNodeName() string { } // Read or set the NodeName that will be used for this MicroShift instance -func (c *Config) establishNodeName() (string, error) { +func (c *Config) establishNodeName(dataDir string) (string, error) { name := c.CanonicalNodeName() - filePath := filepath.Join(GetDataDir(), ".nodename") + filePath := filepath.Join(dataDir, ".nodename") contents, err := os.ReadFile(filePath) if os.IsNotExist(err) { // ensure that dataDir exists - os.MkdirAll(GetDataDir(), 0700) + os.MkdirAll(dataDir, 0700) if err := os.WriteFile(filePath, []byte(name), 0444); err != nil { return "", fmt.Errorf("failed to write nodename file %q: %v", filePath, err) } @@ -54,13 +54,13 @@ func (c *Config) establishNodeName() (string, error) { } // Validate the NodeName to be used for this MicroShift instances -func (c *Config) validateNodeName(isDefaultNodeName bool) error { +func (c *Config) validateNodeName(isDefaultNodeName bool, dataDir string) error { currentNodeName := c.CanonicalNodeName() if addr := net.ParseIP(currentNodeName); addr != nil { return fmt.Errorf("NodeName can not be an IP address: %q", currentNodeName) } - establishedNodeName, err := c.establishNodeName() + establishedNodeName, err := c.establishNodeName(dataDir) if err != nil { return fmt.Errorf("failed to establish NodeName: %v", err) } @@ -83,5 +83,5 @@ func (c *Config) EnsureNodeNameHasNotChanged() error { // Validate NodeName in config file, node-name should not be changed for an already // initialized MicroShift instance. This can lead to Pods being re-scheduled, storage // being orphaned or lost, and other side effects. - return c.validateNodeName(c.isDefaultNodeName()) + return c.validateNodeName(c.isDefaultNodeName(), DataDir) } diff --git a/etcd/vendor/modules.txt b/etcd/vendor/modules.txt index 52bedc559a..0d24790c76 100644 --- a/etcd/vendor/modules.txt +++ b/etcd/vendor/modules.txt @@ -165,7 +165,6 @@ github.com/mailru/easyjson/jwriter github.com/matttproud/golang_protobuf_extensions/pbutil # github.com/mitchellh/go-homedir v1.1.0 ## explicit -github.com/mitchellh/go-homedir # github.com/mitchellh/go-wordwrap v1.0.0 ## explicit github.com/mitchellh/go-wordwrap diff --git a/pkg/cmd/init.go b/pkg/cmd/init.go index 864e785b0f..abd3ccb890 100644 --- a/pkg/cmd/init.go +++ b/pkg/cmd/init.go @@ -35,8 +35,6 @@ import ( "github.com/openshift/microshift/pkg/util/cryptomaterial/certchains" ) -var microshiftDataDir = config.GetDataDir() - func initCerts(cfg *config.Config) (*certchains.CertificateChains, error) { certChains, err := certSetup(cfg) if err != nil { @@ -86,7 +84,7 @@ func certSetup(cfg *config.Config) (*certchains.CertificateChains, error) { externalCertNames = append(externalCertNames, cfg.Node.NodeIP) } - certsDir := cryptomaterial.CertsDirectory(microshiftDataDir) + certsDir := cryptomaterial.CertsDirectory(config.DataDir) certChains, err := certchains.NewCertificateChains( // ------------------------------ @@ -350,7 +348,7 @@ func certSetup(cfg *config.Config) (*certchains.CertificateChains, error) { return nil, err } - saKeyDir := filepath.Join(microshiftDataDir, "/resources/kube-apiserver/secrets/service-account-key") + saKeyDir := filepath.Join(config.DataDir, "/resources/kube-apiserver/secrets/service-account-key") if err := util.EnsureKeyPair( filepath.Join(saKeyDir, "service-account.pub"), filepath.Join(saKeyDir, "service-account.key"), @@ -370,11 +368,11 @@ func initKubeconfigs( cfg *config.Config, certChains *certchains.CertificateChains, ) error { - externalTrustPEM, err := os.ReadFile(cryptomaterial.CACertPath(cryptomaterial.KubeAPIServerExternalSigner(cryptomaterial.CertsDirectory(microshiftDataDir)))) + externalTrustPEM, err := os.ReadFile(cryptomaterial.CACertPath(cryptomaterial.KubeAPIServerExternalSigner(cryptomaterial.CertsDirectory(config.DataDir)))) if err != nil { return fmt.Errorf("failed to load the external trust signer: %v", err) } - internalTrustPEM, err := os.ReadFile(cryptomaterial.CACertPath(cryptomaterial.KubeAPIServerLocalhostSigner(cryptomaterial.CertsDirectory(microshiftDataDir)))) + internalTrustPEM, err := os.ReadFile(cryptomaterial.CACertPath(cryptomaterial.KubeAPIServerLocalhostSigner(cryptomaterial.CertsDirectory(config.DataDir)))) if err != nil { return fmt.Errorf("failed to load the internal trust signer: %v", err) } diff --git a/pkg/cmd/run.go b/pkg/cmd/run.go index b5fe89b9fa..6e0a436d3a 100644 --- a/pkg/cmd/run.go +++ b/pkg/cmd/run.go @@ -85,7 +85,7 @@ func RunMicroshift(cfg *config.Config) error { klog.Fatal(err) } - os.MkdirAll(microshiftDataDir, 0700) + os.MkdirAll(config.DataDir, 0700) // TODO: change to only initialize what is strictly necessary for the selected role(s) certChains, err := initCerts(cfg) diff --git a/pkg/components/components.go b/pkg/components/components.go index aaadbca36f..3eb32f9c84 100755 --- a/pkg/components/components.go +++ b/pkg/components/components.go @@ -5,8 +5,6 @@ import ( "k8s.io/klog/v2" ) -var microshiftDataDir = config.GetDataDir() - func StartComponents(cfg *config.Config) error { kubeAdminConfig := cfg.KubeConfigPath(config.KubeAdmin) diff --git a/pkg/components/controllers.go b/pkg/components/controllers.go index 13c4038980..457ae1f770 100644 --- a/pkg/components/controllers.go +++ b/pkg/components/controllers.go @@ -39,7 +39,7 @@ func startServiceCAController(cfg *config.Config, kubeconfigPath string) error { cmName = "signing-cabundle" ) - serviceCADir := cryptomaterial.ServiceCADir(cryptomaterial.CertsDirectory(microshiftDataDir)) + serviceCADir := cryptomaterial.ServiceCADir(cryptomaterial.CertsDirectory(config.DataDir)) caCertPath := cryptomaterial.CACertPath(serviceCADir) caKeyPath := cryptomaterial.CAKeyPath(serviceCADir) @@ -141,7 +141,7 @@ func startIngressController(cfg *config.Config, kubeconfigPath string) error { return err } - serviceCADir := cryptomaterial.ServiceCADir(cryptomaterial.CertsDirectory(microshiftDataDir)) + serviceCADir := cryptomaterial.ServiceCADir(cryptomaterial.CertsDirectory(config.DataDir)) caCertPath := cryptomaterial.CACertPath(serviceCADir) cmData := map[string]string{} diff --git a/pkg/components/networking.go b/pkg/components/networking.go index 96e5929bc1..ce9ab6134e 100644 --- a/pkg/components/networking.go +++ b/pkg/components/networking.go @@ -76,7 +76,7 @@ func startCNIPlugin(cfg *config.Config, kubeconfigPath string) error { extraParams := assets.RenderParams{ "OVNConfig": ovnConfig, "KubeconfigPath": kubeconfigPath, - "KubeconfigDir": filepath.Join(microshiftDataDir, "/resources/kubeadmin"), + "KubeconfigDir": filepath.Join(config.DataDir, "/resources/kubeadmin"), } if err := assets.ApplyConfigMaps(cm, renderTemplate, renderParamsFromConfig(cfg, extraParams), kubeconfigPath); err != nil { klog.Warningf("Failed to apply configMap %v %v", cm, err) diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index fc57668286..8ede4b9bbb 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -15,13 +15,12 @@ const ( IS_NOT_DEFAULT_NODENAME = false ) -func setupSuiteDataDir(t *testing.T) func() { +func setupSuiteDataDir(t *testing.T) (string, func()) { tmpdir, err := os.MkdirTemp("", "microshift") if err != nil { t.Errorf("failed to create temp dir: %v", err) } - dataDir = tmpdir - return func() { + return tmpdir, func() { os.RemoveAll(tmpdir) } } @@ -199,9 +198,6 @@ func TestGetActiveConfigFromYAML(t *testing.T) { // Test the validation logic func TestValidate(t *testing.T) { - cleanup := setupSuiteDataDir(t) - defer cleanup() - mkDefaultConfig := func() *Config { c := NewDefault() c.ApiServer.SkipInterface = true @@ -321,13 +317,13 @@ func TestCanonicalNodeName(t *testing.T) { } func TestMicroshiftConfigNodeNameValidation(t *testing.T) { - cleanup := setupSuiteDataDir(t) + dataDir, cleanup := setupSuiteDataDir(t) defer cleanup() c := NewDefault() c.Node.HostnameOverride = "node1" - if err := c.validateNodeName(IS_NOT_DEFAULT_NODENAME); err != nil { + if err := c.validateNodeName(IS_NOT_DEFAULT_NODENAME, dataDir); err != nil { t.Errorf("failed to validate node name on first call: %v", err) } @@ -338,23 +334,23 @@ func TestMicroshiftConfigNodeNameValidation(t *testing.T) { t.Errorf("node name file doesn't match the node name in the saved file: %v", err) } - if err := c.validateNodeName(IS_NOT_DEFAULT_NODENAME); err != nil { + if err := c.validateNodeName(IS_NOT_DEFAULT_NODENAME, dataDir); err != nil { t.Errorf("failed to validate node name on second call without changes: %v", err) } c.Node.HostnameOverride = "node2" - if err := c.validateNodeName(IS_NOT_DEFAULT_NODENAME); err == nil { + if err := c.validateNodeName(IS_NOT_DEFAULT_NODENAME, dataDir); err == nil { t.Errorf("validation should have failed for nodename change: %v", err) } } func TestMicroshiftConfigNodeNameValidationFromDefault(t *testing.T) { - cleanup := setupSuiteDataDir(t) + dataDir, cleanup := setupSuiteDataDir(t) defer cleanup() c := NewDefault() - if err := c.validateNodeName(IS_DEFAULT_NODENAME); err != nil { + if err := c.validateNodeName(IS_DEFAULT_NODENAME, dataDir); err != nil { t.Errorf("failed to validate node name on first call: %v", err) } @@ -366,24 +362,24 @@ func TestMicroshiftConfigNodeNameValidationFromDefault(t *testing.T) { t.Errorf("node name file doesn't match the node name in the saved file: %v", err) } - if err := c.validateNodeName(IS_DEFAULT_NODENAME); err != nil { + if err := c.validateNodeName(IS_DEFAULT_NODENAME, dataDir); err != nil { t.Errorf("failed to validate node name on second call without changes: %v", err) } c.Node.HostnameOverride = "node2" - if err := c.validateNodeName(IS_DEFAULT_NODENAME); err != nil { + if err := c.validateNodeName(IS_DEFAULT_NODENAME, dataDir); err != nil { t.Errorf("validation should have failed in this case, it must be a warning in logs: %v", err) } } func TestMicroshiftConfigNodeNameValidationBadName(t *testing.T) { - cleanup := setupSuiteDataDir(t) + dataDir, cleanup := setupSuiteDataDir(t) defer cleanup() c := NewDefault() c.Node.HostnameOverride = "1.2.3.4" - if err := c.validateNodeName(IS_DEFAULT_NODENAME); err == nil { + if err := c.validateNodeName(IS_DEFAULT_NODENAME, dataDir); err == nil { t.Errorf("failed to validate node name.") } } diff --git a/pkg/config/files.go b/pkg/config/files.go index 4b972cfa48..87614c59ab 100644 --- a/pkg/config/files.go +++ b/pkg/config/files.go @@ -1,18 +1,15 @@ package config import ( - "errors" "fmt" "os" - "github.com/mitchellh/go-homedir" "sigs.k8s.io/yaml" ) const ( - defaultUserDataDir = "~/.microshift/data" - ConfigFile = "/etc/microshift/config.yaml" - defaultGlobalDataDir = "/var/lib/microshift" + ConfigFile = "/etc/microshift/config.yaml" + DataDir = "/var/lib/microshift" // for files managed via management system in /etc, i.e. user applications defaultManifestDirEtc = "/etc/microshift/manifests" // for files embedded in ostree. i.e. cni/other component customizations @@ -20,33 +17,13 @@ const ( ) var ( - dataDir = findDataDir() manifestsDir = findManifestsDir() ) -func GetDataDir() string { - return dataDir -} - func GetManifestsDir() []string { return manifestsDir } -// Returns the default user data dir if it exists or the user is non-root. -// Returns the default global data dir otherwise. -func findDataDir() string { - userDataDir, _ := homedir.Expand(defaultUserDataDir) - if _, err := os.Stat(userDataDir); errors.Is(err, os.ErrNotExist) { - if os.Geteuid() > 0 { - return userDataDir - } else { - return defaultGlobalDataDir - } - } else { - return userDataDir - } -} - // Returns the default manifests directories func findManifestsDir() []string { var manifestsDir = []string{defaultManifestDirLib, defaultManifestDirEtc} diff --git a/pkg/config/kubeconfig.go b/pkg/config/kubeconfig.go index 1e33b07b96..72a85466f5 100644 --- a/pkg/config/kubeconfig.go +++ b/pkg/config/kubeconfig.go @@ -16,9 +16,9 @@ const ( // KubeConfigPath returns the path to the specified kubeconfig file. func (cfg *Config) KubeConfigPath(id KubeConfigID) string { - return filepath.Join(dataDir, "resources", string(id), "kubeconfig") + return filepath.Join(DataDir, "resources", string(id), "kubeconfig") } func (cfg *Config) KubeConfigAdminPath(id string) string { - return filepath.Join(dataDir, "resources", string(KubeAdmin), id, "kubeconfig") + return filepath.Join(DataDir, "resources", string(KubeAdmin), id, "kubeconfig") } diff --git a/pkg/config/node.go b/pkg/config/node.go index 13eb6e6a90..84ba694bce 100644 --- a/pkg/config/node.go +++ b/pkg/config/node.go @@ -36,13 +36,13 @@ func (c *Config) CanonicalNodeName() string { } // Read or set the NodeName that will be used for this MicroShift instance -func (c *Config) establishNodeName() (string, error) { +func (c *Config) establishNodeName(dataDir string) (string, error) { name := c.CanonicalNodeName() - filePath := filepath.Join(GetDataDir(), ".nodename") + filePath := filepath.Join(dataDir, ".nodename") contents, err := os.ReadFile(filePath) if os.IsNotExist(err) { // ensure that dataDir exists - os.MkdirAll(GetDataDir(), 0700) + os.MkdirAll(dataDir, 0700) if err := os.WriteFile(filePath, []byte(name), 0444); err != nil { return "", fmt.Errorf("failed to write nodename file %q: %v", filePath, err) } @@ -54,13 +54,13 @@ func (c *Config) establishNodeName() (string, error) { } // Validate the NodeName to be used for this MicroShift instances -func (c *Config) validateNodeName(isDefaultNodeName bool) error { +func (c *Config) validateNodeName(isDefaultNodeName bool, dataDir string) error { currentNodeName := c.CanonicalNodeName() if addr := net.ParseIP(currentNodeName); addr != nil { return fmt.Errorf("NodeName can not be an IP address: %q", currentNodeName) } - establishedNodeName, err := c.establishNodeName() + establishedNodeName, err := c.establishNodeName(dataDir) if err != nil { return fmt.Errorf("failed to establish NodeName: %v", err) } @@ -83,5 +83,5 @@ func (c *Config) EnsureNodeNameHasNotChanged() error { // Validate NodeName in config file, node-name should not be changed for an already // initialized MicroShift instance. This can lead to Pods being re-scheduled, storage // being orphaned or lost, and other side effects. - return c.validateNodeName(c.isDefaultNodeName()) + return c.validateNodeName(c.isDefaultNodeName(), DataDir) } diff --git a/pkg/controllers/etcd.go b/pkg/controllers/etcd.go index d875652207..9eb612e51d 100644 --- a/pkg/controllers/etcd.go +++ b/pkg/controllers/etcd.go @@ -147,7 +147,7 @@ func checkIfEtcdIsReady(ctx context.Context) error { } func getEtcdClient(ctx context.Context) (*clientv3.Client, error) { - certsDir := cryptomaterial.CertsDirectory(config.GetDataDir()) + certsDir := cryptomaterial.CertsDirectory(config.DataDir) etcdAPIServerClientCertDir := cryptomaterial.EtcdAPIServerClientCertDir(certsDir) tlsInfo := transport.TLSInfo{ diff --git a/pkg/controllers/kube-apiserver.go b/pkg/controllers/kube-apiserver.go index 96fbcead51..6afb60fbf6 100644 --- a/pkg/controllers/kube-apiserver.go +++ b/pkg/controllers/kube-apiserver.go @@ -56,8 +56,6 @@ var ( embedded.MustAsset("controllers/kube-apiserver/defaultconfig.yaml"), embedded.MustAsset("controllers/kube-apiserver/config-overrides.yaml"), } - - microshiftDataDir = config.GetDataDir() ) var fixedTLSProfile *configv1.TLSProfileSpec @@ -94,7 +92,7 @@ func (s *KubeAPIServer) Dependencies() []string { return []string{"etcd", "netwo func (s *KubeAPIServer) configure(cfg *config.Config) error { s.verbosity = cfg.GetVerbosity() - certsDir := cryptomaterial.CertsDirectory(microshiftDataDir) + certsDir := cryptomaterial.CertsDirectory(config.DataDir) kubeCSRSignerDir := cryptomaterial.CSRSignerCertDir(certsDir) kubeletClientDir := cryptomaterial.KubeAPIServerToKubeletClientCertDir(certsDir) clientCABundlePath := cryptomaterial.TotalClientCABundlePath(certsDir) @@ -116,7 +114,7 @@ func (s *KubeAPIServer) configure(cfg *config.Config) error { overrides := &kubecontrolplanev1.KubeAPIServerConfig{ APIServerArguments: map[string]kubecontrolplanev1.Arguments{ "advertise-address": {s.advertiseAddress}, - "audit-policy-file": {microshiftDataDir + "/resources/kube-apiserver-audit-policies/default.yaml"}, + "audit-policy-file": {filepath.Join(config.DataDir, "/resources/kube-apiserver-audit-policies/default.yaml")}, "client-ca-file": {clientCABundlePath}, "etcd-cafile": {cryptomaterial.CACertPath(cryptomaterial.EtcdSignerDir(certsDir))}, "etcd-certfile": {cryptomaterial.ClientCertPath(etcdClientCertDir)}, @@ -132,7 +130,7 @@ func (s *KubeAPIServer) configure(cfg *config.Config) error { "proxy-client-cert-file": {cryptomaterial.ClientCertPath(aggregatorClientCertDir)}, "proxy-client-key-file": {cryptomaterial.ClientKeyPath(aggregatorClientCertDir)}, "requestheader-client-ca-file": {aggregatorCAPath}, - "service-account-signing-key-file": {microshiftDataDir + "/resources/kube-apiserver/secrets/service-account-key/service-account.key"}, + "service-account-signing-key-file": {filepath.Join(config.DataDir, "/resources/kube-apiserver/secrets/service-account-key/service-account.key")}, "service-node-port-range": {cfg.Network.ServiceNodePortRange}, "tls-cert-file": {servingCert}, "tls-private-key-file": {servingKey}, @@ -206,7 +204,7 @@ func (s *KubeAPIServer) configure(cfg *config.Config) error { }, }, ServiceAccountPublicKeyFiles: []string{ - microshiftDataDir + "/resources/kube-apiserver/secrets/service-account-key/service-account.pub", + filepath.Join(config.DataDir, "/resources/kube-apiserver/secrets/service-account-key/service-account.pub"), }, ServicesSubnet: cfg.Network.ServiceNetwork[0], ServicesNodePortRange: cfg.Network.ServiceNodePortRange, @@ -284,7 +282,7 @@ rules: omitStages: - "RequestReceived"`) - path := filepath.Join(microshiftDataDir, "resources", "kube-apiserver-audit-policies", "default.yaml") + path := filepath.Join(config.DataDir, "resources", "kube-apiserver-audit-policies", "default.yaml") os.MkdirAll(filepath.Dir(path), os.FileMode(0700)) return os.WriteFile(path, data, 0400) } diff --git a/pkg/controllers/kube-controller-manager.go b/pkg/controllers/kube-controller-manager.go index 3a2126cb58..bdd73a55fb 100644 --- a/pkg/controllers/kube-controller-manager.go +++ b/pkg/controllers/kube-controller-manager.go @@ -20,6 +20,7 @@ import ( "encoding/json" "errors" "fmt" + "path/filepath" "sort" "strconv" @@ -60,18 +61,18 @@ func (s *KubeControllerManager) Name() string { return "kube-controlle func (s *KubeControllerManager) Dependencies() []string { return []string{"kube-apiserver"} } func kcmRootCAFile() string { - certsDir := cryptomaterial.CertsDirectory(microshiftDataDir) + certsDir := cryptomaterial.CertsDirectory(config.DataDir) return cryptomaterial.ServiceAccountTokenCABundlePath(certsDir) } func kcmClusterSigningCertKeyAndFile() (string, string) { - certsDir := cryptomaterial.CertsDirectory(microshiftDataDir) + certsDir := cryptomaterial.CertsDirectory(config.DataDir) csrSignerDir := cryptomaterial.CSRSignerCertDir(certsDir) return cryptomaterial.CAKeyPath(csrSignerDir), cryptomaterial.CACertPath(csrSignerDir) } func kcmServiceAccountPrivateKeyFile() string { - return microshiftDataDir + "/resources/kube-apiserver/secrets/service-account-key/service-account.key" + return filepath.Join(config.DataDir, "/resources/kube-apiserver/secrets/service-account-key/service-account.key") } func configure(cfg *config.Config) (args []string, applyFn func() error, err error) { diff --git a/pkg/controllers/kube-scheduler.go b/pkg/controllers/kube-scheduler.go index d1cd500799..6c1391a6ce 100644 --- a/pkg/controllers/kube-scheduler.go +++ b/pkg/controllers/kube-scheduler.go @@ -54,7 +54,7 @@ func (s *KubeScheduler) configure(cfg *config.Config) { } s.options = schedulerOptions.NewOptions() - s.options.ConfigFile = microshiftDataDir + "/resources/kube-scheduler/config/config.yaml" + s.options.ConfigFile = filepath.Join(config.DataDir, "/resources/kube-scheduler/config/config.yaml") s.options.Authentication.RemoteKubeConfigFile = cfg.KubeConfigPath(config.KubeScheduler) s.options.Authorization.RemoteKubeConfigFile = cfg.KubeConfigPath(config.KubeScheduler) s.kubeconfig = cfg.KubeConfigPath(config.KubeScheduler) @@ -68,7 +68,7 @@ clientConnection: leaderElection: leaderElect: false`) - path := filepath.Join(microshiftDataDir, "resources", "kube-scheduler", "config", "config.yaml") + path := filepath.Join(config.DataDir, "resources", "kube-scheduler", "config", "config.yaml") os.MkdirAll(filepath.Dir(path), os.FileMode(0700)) return os.WriteFile(path, data, 0400) } diff --git a/pkg/controllers/openshift-route-controller-manager.go b/pkg/controllers/openshift-route-controller-manager.go index 3bfa301fab..aaa679ce62 100644 --- a/pkg/controllers/openshift-route-controller-manager.go +++ b/pkg/controllers/openshift-route-controller-manager.go @@ -62,7 +62,7 @@ func (s *OCPRouteControllerManager) configure(cfg *config.Config) { } func (s *OCPRouteControllerManager) writeConfig(cfg *config.Config) *openshiftcontrolplanev1.OpenShiftControllerManagerConfig { - servingCertDir := cryptomaterial.RouteControllerManagerServingCertDir(cryptomaterial.CertsDirectory(microshiftDataDir)) + servingCertDir := cryptomaterial.RouteControllerManagerServingCertDir(cryptomaterial.CertsDirectory(config.DataDir)) c := &openshiftcontrolplanev1.OpenShiftControllerManagerConfig{ KubeClientConfig: configv1.KubeClientConfig{ @@ -79,7 +79,7 @@ func (s *OCPRouteControllerManager) writeConfig(cfg *config.Config) *openshiftco CertFile: cryptomaterial.ServingCertPath(servingCertDir), KeyFile: cryptomaterial.ServingKeyPath(servingCertDir), }, - ClientCA: cryptomaterial.TotalClientCABundlePath(cryptomaterial.CertsDirectory(microshiftDataDir)), + ClientCA: cryptomaterial.TotalClientCABundlePath(cryptomaterial.CertsDirectory(config.DataDir)), }, }, Controllers: []string{ diff --git a/pkg/node/kubelet.go b/pkg/node/kubelet.go index 55ea2b1695..cc906572fc 100644 --- a/pkg/node/kubelet.go +++ b/pkg/node/kubelet.go @@ -44,8 +44,6 @@ const ( componentKubelet = "kubelet" ) -var microshiftDataDir = config.GetDataDir() - type KubeletServer struct { kubeletflags *kubeletoptions.KubeletFlags kubeconfig *kubeletconfig.KubeletConfiguration @@ -83,7 +81,7 @@ func (s *KubeletServer) configure(cfg *config.Config) { kubeletFlags.NodeLabels["node-role.kubernetes.io/worker"] = "" kubeletFlags.NodeLabels["node.openshift.io/os_id"] = osID - kubeletConfig, err := loadConfigFile(microshiftDataDir + "/resources/kubelet/config/config.yaml") + kubeletConfig, err := loadConfigFile(filepath.Join(config.DataDir, "/resources/kubelet/config/config.yaml")) if err != nil { klog.Fatalf("Failed to load Kubelet Configuration", err) @@ -94,7 +92,7 @@ func (s *KubeletServer) configure(cfg *config.Config) { } func (s *KubeletServer) writeConfig(cfg *config.Config) error { - certsDir := cryptomaterial.CertsDirectory(microshiftDataDir) + certsDir := cryptomaterial.CertsDirectory(config.DataDir) servingCertDir := cryptomaterial.KubeletServingCertDir(certsDir) data := []byte(` @@ -102,14 +100,14 @@ kind: KubeletConfiguration apiVersion: kubelet.config.k8s.io/v1beta1 authentication: x509: - clientCAFile: ` + cryptomaterial.KubeletClientCAPath(cryptomaterial.CertsDirectory(microshiftDataDir)) + ` + clientCAFile: ` + cryptomaterial.KubeletClientCAPath(cryptomaterial.CertsDirectory(config.DataDir)) + ` anonymous: enabled: false tlsCertFile: ` + cryptomaterial.ServingCertPath(servingCertDir) + ` tlsPrivateKeyFile: ` + cryptomaterial.ServingKeyPath(servingCertDir) + ` cgroupDriver: "systemd" failSwapOn: false -volumePluginDir: ` + microshiftDataDir + `/kubelet-plugins/volume/exec +volumePluginDir: ` + config.DataDir + `/kubelet-plugins/volume/exec clusterDNS: - ` + cfg.Network.DNS + ` clusterDomain: cluster.local @@ -135,7 +133,7 @@ serverTLSBootstrap: false #TODO`) data = append(data, fmt.Sprintf("\nresolvConf: %s\n", config.DefaultSystemdResolvedFile)...) } - path := filepath.Join(microshiftDataDir, "resources", "kubelet", "config", "config.yaml") + path := filepath.Join(config.DataDir, "resources", "kubelet", "config", "config.yaml") os.MkdirAll(filepath.Dir(path), os.FileMode(0700)) return os.WriteFile(path, data, 0400) } diff --git a/vendor/github.com/mitchellh/go-homedir/LICENSE b/vendor/github.com/mitchellh/go-homedir/LICENSE deleted file mode 100644 index f9c841a51e..0000000000 --- a/vendor/github.com/mitchellh/go-homedir/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Mitchell Hashimoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/mitchellh/go-homedir/README.md b/vendor/github.com/mitchellh/go-homedir/README.md deleted file mode 100644 index d70706d5b3..0000000000 --- a/vendor/github.com/mitchellh/go-homedir/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# go-homedir - -This is a Go library for detecting the user's home directory without -the use of cgo, so the library can be used in cross-compilation environments. - -Usage is incredibly simple, just call `homedir.Dir()` to get the home directory -for a user, and `homedir.Expand()` to expand the `~` in a path to the home -directory. - -**Why not just use `os/user`?** The built-in `os/user` package requires -cgo on Darwin systems. This means that any Go code that uses that package -cannot cross compile. But 99% of the time the use for `os/user` is just to -retrieve the home directory, which we can do for the current user without -cgo. This library does that, enabling cross-compilation. diff --git a/vendor/github.com/mitchellh/go-homedir/homedir.go b/vendor/github.com/mitchellh/go-homedir/homedir.go deleted file mode 100644 index 25378537ea..0000000000 --- a/vendor/github.com/mitchellh/go-homedir/homedir.go +++ /dev/null @@ -1,167 +0,0 @@ -package homedir - -import ( - "bytes" - "errors" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "sync" -) - -// DisableCache will disable caching of the home directory. Caching is enabled -// by default. -var DisableCache bool - -var homedirCache string -var cacheLock sync.RWMutex - -// Dir returns the home directory for the executing user. -// -// This uses an OS-specific method for discovering the home directory. -// An error is returned if a home directory cannot be detected. -func Dir() (string, error) { - if !DisableCache { - cacheLock.RLock() - cached := homedirCache - cacheLock.RUnlock() - if cached != "" { - return cached, nil - } - } - - cacheLock.Lock() - defer cacheLock.Unlock() - - var result string - var err error - if runtime.GOOS == "windows" { - result, err = dirWindows() - } else { - // Unix-like system, so just assume Unix - result, err = dirUnix() - } - - if err != nil { - return "", err - } - homedirCache = result - return result, nil -} - -// Expand expands the path to include the home directory if the path -// is prefixed with `~`. If it isn't prefixed with `~`, the path is -// returned as-is. -func Expand(path string) (string, error) { - if len(path) == 0 { - return path, nil - } - - if path[0] != '~' { - return path, nil - } - - if len(path) > 1 && path[1] != '/' && path[1] != '\\' { - return "", errors.New("cannot expand user-specific home dir") - } - - dir, err := Dir() - if err != nil { - return "", err - } - - return filepath.Join(dir, path[1:]), nil -} - -// Reset clears the cache, forcing the next call to Dir to re-detect -// the home directory. This generally never has to be called, but can be -// useful in tests if you're modifying the home directory via the HOME -// env var or something. -func Reset() { - cacheLock.Lock() - defer cacheLock.Unlock() - homedirCache = "" -} - -func dirUnix() (string, error) { - homeEnv := "HOME" - if runtime.GOOS == "plan9" { - // On plan9, env vars are lowercase. - homeEnv = "home" - } - - // First prefer the HOME environmental variable - if home := os.Getenv(homeEnv); home != "" { - return home, nil - } - - var stdout bytes.Buffer - - // If that fails, try OS specific commands - if runtime.GOOS == "darwin" { - cmd := exec.Command("sh", "-c", `dscl -q . -read /Users/"$(whoami)" NFSHomeDirectory | sed 's/^[^ ]*: //'`) - cmd.Stdout = &stdout - if err := cmd.Run(); err == nil { - result := strings.TrimSpace(stdout.String()) - if result != "" { - return result, nil - } - } - } else { - cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - // If the error is ErrNotFound, we ignore it. Otherwise, return it. - if err != exec.ErrNotFound { - return "", err - } - } else { - if passwd := strings.TrimSpace(stdout.String()); passwd != "" { - // username:password:uid:gid:gecos:home:shell - passwdParts := strings.SplitN(passwd, ":", 7) - if len(passwdParts) > 5 { - return passwdParts[5], nil - } - } - } - } - - // If all else fails, try the shell - stdout.Reset() - cmd := exec.Command("sh", "-c", "cd && pwd") - cmd.Stdout = &stdout - if err := cmd.Run(); err != nil { - return "", err - } - - result := strings.TrimSpace(stdout.String()) - if result == "" { - return "", errors.New("blank output when reading home directory") - } - - return result, nil -} - -func dirWindows() (string, error) { - // First prefer the HOME environmental variable - if home := os.Getenv("HOME"); home != "" { - return home, nil - } - - // Prefer standard environment variable USERPROFILE - if home := os.Getenv("USERPROFILE"); home != "" { - return home, nil - } - - drive := os.Getenv("HOMEDRIVE") - path := os.Getenv("HOMEPATH") - home := drive + path - if drive == "" || path == "" { - return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank") - } - - return home, nil -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 2a1468fb9c..3c7046f9f4 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -479,7 +479,6 @@ github.com/mindprince/gonvml github.com/mistifyio/go-zfs # github.com/mitchellh/go-homedir v1.1.0 ## explicit -github.com/mitchellh/go-homedir # github.com/mitchellh/go-wordwrap v1.0.0 ## explicit github.com/mitchellh/go-wordwrap