Skip to content

Commit

Permalink
config refactoring: use runtime config
Browse files Browse the repository at this point in the history
Signed-off-by: Karen Almog <[email protected]>
  • Loading branch information
Karen Almog committed Jan 11, 2022
1 parent ec97796 commit 5bf44c5
Show file tree
Hide file tree
Showing 38 changed files with 939 additions and 314 deletions.
6 changes: 1 addition & 5 deletions cmd/airgap/listimages.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,7 @@ func NewAirgapListImagesCmd() *cobra.Command {
Example: `k0s airgap list-images`,
RunE: func(cmd *cobra.Command, args []string) error {
c := CmdOpts(config.GetCmdOpts())
cfg, err := config.GetYamlFromFile(c.CfgFile, c.K0sVars)
if err != nil {
return err
}
uris := airgap.GetImageURIs(cfg.Spec.Images)
uris := airgap.GetImageURIs(c.ClusterConfig.Spec.Images)
for _, uri := range uris {
fmt.Println(uri)
}
Expand Down
6 changes: 0 additions & 6 deletions cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,10 @@ func NewAPICmd() *cobra.Command {
logrus.SetOutput(os.Stdout)

c := CmdOpts(config.GetCmdOpts())
cfg, err := config.GetNodeConfig(c.CfgFile, c.K0sVars)
if err != nil {
return err
}
c.NodeConfig = cfg
return c.startAPI()
},
}
cmd.SilenceUsage = true
cmd.Flags().AddFlagSet(config.FileInputFlag())
cmd.PersistentFlags().AddFlagSet(config.GetPersistentFlagSet())
return cmd
}
Expand Down
16 changes: 6 additions & 10 deletions cmd/backup/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,7 @@ func NewBackupCmd() *cobra.Command {
Short: "Back-Up k0s configuration. Must be run as root (or with sudo)",
RunE: func(cmd *cobra.Command, args []string) error {
c := CmdOpts(config.GetCmdOpts())
cfg, err := config.GetYamlFromFile(c.CfgFile, c.K0sVars)
if err != nil {
return err
}
c.ClusterConfig = cfg
if c.ClusterConfig.Spec.Storage.Etcd.IsExternalClusterUsed() {
if c.NodeConfig.Spec.Storage.Etcd.IsExternalClusterUsed() {
return fmt.Errorf("command 'k0s backup' does not support external etcd cluster")
}
return c.backup()
Expand All @@ -57,7 +52,6 @@ func NewBackupCmd() *cobra.Command {
}
cmd.Flags().StringVar(&savePath, "save-path", "", "destination directory path for backup assets")
cmd.SilenceUsage = true
cmd.Flags().AddFlagSet(config.FileInputFlag())
cmd.PersistentFlags().AddFlagSet(config.GetPersistentFlagSet())
return cmd
}
Expand Down Expand Up @@ -86,16 +80,18 @@ func (c *CmdOpts) backup() error {
if err != nil {
return err
}
return mgr.RunBackup(c.CfgFile, c.ClusterConfig.Spec, c.K0sVars, savePath)
return mgr.RunBackup(c.CfgFile, c.NodeConfig.Spec, c.K0sVars, savePath)
}
return fmt.Errorf("backup command must be run on the controller node, have `%s`", status.Role)
}

func preRunValidateConfig(cmd *cobra.Command, args []string) error {
c := CmdOpts(config.GetCmdOpts())
_, err := config.GetConfigFromYAML(c.CfgFile, c.K0sVars)

loadingRules := config.ClientConfigLoadingRules{K0sVars: c.K0sVars}
_, err := loadingRules.ParseRuntimeConfig()
if err != nil {
return err
return fmt.Errorf("failed to get config: %v", err)
}
return nil
}
4 changes: 3 additions & 1 deletion cmd/config/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ func NewValidateCmd() *cobra.Command {
k0s config validate --config path_to_config.yaml`,
RunE: func(cmd *cobra.Command, args []string) error {
c := CmdOpts(config.GetCmdOpts())
_, err := config.GetNodeConfig(c.CfgFile, c.K0sVars)

loadingRules := config.ClientConfigLoadingRules{K0sVars: c.K0sVars}
_, err := loadingRules.ParseRuntimeConfig()
return err
},
SilenceUsage: true,
Expand Down
37 changes: 20 additions & 17 deletions cmd/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,6 @@ func NewControllerCmd() *cobra.Command {
}
c.TokenArg = string(bytes)
}
if c.SingleNode {
c.EnableWorker = true
c.K0sVars.DefaultStorageType = "kine"
}
c.Logging = stringmap.Merge(c.CmdLogLevels, c.DefaultLogLevels)
cmd.SilenceUsage = true

Expand Down Expand Up @@ -124,15 +120,25 @@ func (c *CmdOpts) startController(ctx context.Context) error {
if err := dir.Init(c.K0sVars.CertRootDir, constant.CertRootDirMode); err != nil {
return err
}
// let's make sure run-dir exists
if err := dir.Init(c.K0sVars.RunDir, constant.RunDirMode); err != nil {
logrus.Fatalf("failed to initialize dir: %v", err)
}

nodeConfig, err := config.GetNodeConfig(c.CfgFile, c.K0sVars)
if err != nil {
return err
// initialize runtime config
loadingRules := config.ClientConfigLoadingRules{Nodeconfig: true}
if err := loadingRules.InitRuntimeConfig(); err != nil {
logrus.Fatalf("failed to initialize k0s runtime config: %s", err.Error())
}
c.NodeConfig = nodeConfig

// from now on, we only refer to the runtime config
c.CfgFile = loadingRules.RuntimeConfigPath

certificateManager := certificate.Manager{K0sVars: c.K0sVars}

var joinClient *token.JoinClient
var err error

if c.TokenArg != "" && c.needToJoin() {
joinClient, err = joinController(ctx, c.TokenArg, c.K0sVars.CertRootDir)
if err != nil {
Expand Down Expand Up @@ -282,8 +288,9 @@ func (c *CmdOpts) startController(ctx context.Context) error {
// Stop components
if stopErr := c.NodeComponents.Stop(); stopErr != nil {
logrus.Errorf("error while stopping node component %s", stopErr)
} else {
logrus.Info("all node components stopped")
}
logrus.Info("all node components stopped")
}()

// in-cluster component reconcilers
Expand Down Expand Up @@ -335,11 +342,7 @@ func (c *CmdOpts) startController(ctx context.Context) error {
return err
}
} else {
fullCfg, err := config.GetYamlFromFile(c.CfgFile, c.K0sVars)
if err != nil {
return err
}
cfgSource, err = clusterconfig.NewStaticSource(fullCfg)
cfgSource, err = clusterconfig.NewStaticSource(c.ClusterConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -402,7 +405,7 @@ func (c *CmdOpts) startController(ctx context.Context) error {
logrus.Info("Shutting down k0s controller")

perfTimer.Output()
return err
return os.Remove(c.CfgFile)
}

func (c *CmdOpts) startClusterComponents(ctx context.Context) error {
Expand All @@ -420,7 +423,7 @@ func (c *CmdOpts) startBootstrapReconcilers(ctx context.Context, cf kubernetes.C
return err
}

cfgReconciler, err := controller.NewClusterConfigReconciler(c.CfgFile, leaderElector, c.K0sVars, c.ClusterComponents, manifestSaver, cf, configSource)
cfgReconciler, err := controller.NewClusterConfigReconciler(leaderElector, c.K0sVars, c.ClusterComponents, manifestSaver, cf, configSource)
if err != nil {
logrus.Warnf("failed to initialize cluster-config reconciler: %s", err.Error())
return err
Expand Down Expand Up @@ -472,7 +475,7 @@ func (c *CmdOpts) createClusterReconcilers(ctx context.Context, cf kubernetes.Cl
}

if !stringslice.Contains(c.DisableComponents, constant.KubeProxyComponentName) {
proxy, err := controller.NewKubeProxy(c.CfgFile, c.K0sVars)
proxy, err := controller.NewKubeProxy(c.CfgFile, c.K0sVars, c.NodeConfig)
if err != nil {
return fmt.Errorf("failed to initialize kube-proxy reconciler: %s", err.Error())

Expand Down
6 changes: 0 additions & 6 deletions cmd/etcd/etcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,6 @@ func NewEtcdCmd() *cobra.Command {
Short: "Manage etcd cluster",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
c := CmdOpts(config.GetCmdOpts())
cfg, err := config.GetNodeConfig(c.CfgFile, c.K0sVars)
if err != nil {
return err
}
c.ClusterConfig = cfg
if c.ClusterConfig.Spec.Storage.Type != v1beta1.EtcdStorageType {
return fmt.Errorf("wrong storage type: %s", c.ClusterConfig.Spec.Storage.Type)
}
Expand All @@ -49,7 +44,6 @@ func NewEtcdCmd() *cobra.Command {
cmd.SilenceUsage = true
cmd.AddCommand(etcdLeaveCmd())
cmd.AddCommand(etcdListCmd())
cmd.Flags().AddFlagSet(config.FileInputFlag())
cmd.PersistentFlags().AddFlagSet(config.GetPersistentFlagSet())
return cmd
}
11 changes: 2 additions & 9 deletions cmd/etcd/leave.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,22 +33,16 @@ func etcdLeaveCmd() *cobra.Command {
Short: "Sign off a given etc node from etcd cluster",
RunE: func(cmd *cobra.Command, args []string) error {
c := CmdOpts(config.GetCmdOpts())
cfg, err := config.GetNodeConfig(c.CfgFile, c.K0sVars)
if err != nil {
return err
}
c.ClusterConfig = cfg

ctx := context.Background()
if etcdPeerAddress == "" {
etcdPeerAddress = c.ClusterConfig.Spec.Storage.Etcd.PeerAddress
etcdPeerAddress = c.NodeConfig.Spec.Storage.Etcd.PeerAddress
}
if etcdPeerAddress == "" {
return fmt.Errorf("can't leave etcd cluster: peer address is empty, check the config file or use cli argument")
}

peerURL := fmt.Sprintf("https://%s:2380", etcdPeerAddress)
etcdClient, err := etcd.NewClient(c.K0sVars.CertRootDir, c.K0sVars.EtcdCertDir, c.ClusterConfig.Spec.Storage.Etcd)
etcdClient, err := etcd.NewClient(c.K0sVars.CertRootDir, c.K0sVars.EtcdCertDir, c.NodeConfig.Spec.Storage.Etcd)
if err != nil {
return fmt.Errorf("can't connect to the etcd: %v", err)
}
Expand Down Expand Up @@ -76,6 +70,5 @@ func etcdLeaveCmd() *cobra.Command {

cmd.Flags().StringVar(&etcdPeerAddress, "peer-address", "", "etcd peer address")
cmd.PersistentFlags().AddFlagSet(config.GetPersistentFlagSet())
cmd.Flags().AddFlagSet(config.FileInputFlag())
return cmd
}
9 changes: 1 addition & 8 deletions cmd/etcd/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,8 @@ func etcdListCmd() *cobra.Command {
Short: "Returns etcd cluster members list",
RunE: func(cmd *cobra.Command, args []string) error {
c := CmdOpts(config.GetCmdOpts())
cfg, err := config.GetNodeConfig(c.CfgFile, c.K0sVars)
if err != nil {
return err
}
c.ClusterConfig = cfg

ctx := context.Background()
etcdClient, err := etcd.NewClient(c.K0sVars.CertRootDir, c.K0sVars.EtcdCertDir, c.ClusterConfig.Spec.Storage.Etcd)
etcdClient, err := etcd.NewClient(c.K0sVars.CertRootDir, c.K0sVars.EtcdCertDir, c.NodeConfig.Spec.Storage.Etcd)
if err != nil {
return fmt.Errorf("can't list etcd cluster members: %v", err)
}
Expand All @@ -51,7 +45,6 @@ func etcdListCmd() *cobra.Command {
return json.NewEncoder(os.Stdout).Encode(map[string]interface{}{"members": members})
},
}
cmd.Flags().AddFlagSet(config.FileInputFlag())
cmd.PersistentFlags().AddFlagSet(config.GetPersistentFlagSet())
return cmd
}
13 changes: 5 additions & 8 deletions cmd/install/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,7 @@ func (c *CmdOpts) setup(role string, args []string) error {
}

if role == "controller" {
cfg, err := config.GetNodeConfig(c.CfgFile, c.K0sVars)
if err != nil {
return err
}
c.ClusterConfig = cfg
if err := install.CreateControllerUsers(c.ClusterConfig, c.K0sVars); err != nil {
if err := install.CreateControllerUsers(c.NodeConfig, c.K0sVars); err != nil {
return fmt.Errorf("failed to create controller users: %v", err)
}
}
Expand Down Expand Up @@ -97,9 +92,11 @@ func (c *CmdOpts) convertFileParamsToAbsolute() (err error) {

func preRunValidateConfig(_ *cobra.Command, _ []string) error {
c := CmdOpts(config.GetCmdOpts())
_, err := config.GetConfigFromYAML(c.CfgFile, c.K0sVars)

loadingRules := config.ClientConfigLoadingRules{K0sVars: c.K0sVars}
_, err := loadingRules.ParseRuntimeConfig()
if err != nil {
return err
return fmt.Errorf("failed to get config: %v", err)
}
return nil
}
5 changes: 1 addition & 4 deletions cmd/kubeconfig/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,7 @@ func kubeConfigAdminCmd() *cobra.Command {
log.Fatal(err)
}

clusterAPIURL, err := c.getAPIURL()
if err != nil {
return fmt.Errorf("failed to fetch cluster's API Address: %w", err)
}
clusterAPIURL := c.NodeConfig.Spec.API.APIAddressURL()
newContent := strings.Replace(string(content), "https://localhost:6443", clusterAPIURL, -1)
os.Stdout.Write([]byte(newContent))
} else {
Expand Down
18 changes: 2 additions & 16 deletions cmd/kubeconfig/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
"path"

"github.com/cloudflare/cfssl/log"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"

"github.com/k0sproject/k0s/pkg/certificate"
Expand Down Expand Up @@ -78,10 +77,8 @@ Note: A certificate once signed cannot be revoked for a particular user`,
}
username := args[0]
c := CmdOpts(config.GetCmdOpts())
clusterAPIURL, err := c.getAPIURL()
if err != nil {
return fmt.Errorf("failed to fetch cluster's API Address: %w", err)
}
clusterAPIURL := c.NodeConfig.Spec.API.APIAddressURL()

caCert, err := os.ReadFile(path.Join(c.K0sVars.CertRootDir, "ca.crt"))
if err != nil {
return fmt.Errorf("failed to read cluster ca certificate: %w, check if the control plane is initialized on this node", err)
Expand Down Expand Up @@ -130,17 +127,6 @@ Note: A certificate once signed cannot be revoked for a particular user`,
},
}
cmd.Flags().StringVar(&groups, "groups", "", "Specify groups")
cmd.Flags().AddFlagSet(config.FileInputFlag())
cmd.PersistentFlags().AddFlagSet(config.GetPersistentFlagSet())
return cmd
}

func (c *CmdOpts) getAPIURL() (string, error) {
// Disable logrus
logrus.SetLevel(logrus.WarnLevel)
cfg, err := config.GetNodeConfig(c.CfgFile, c.K0sVars)
if err != nil {
return "", err
}
return cfg.Spec.API.APIAddressURL(), nil
}
21 changes: 10 additions & 11 deletions cmd/kubeconfig/kubeconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,8 @@ import (
"k8s.io/client-go/tools/clientcmd"

"github.com/k0sproject/k0s/internal/pkg/file"
"github.com/k0sproject/k0s/pkg/apis/k0s.k0sproject.io/v1beta1"
"github.com/k0sproject/k0s/internal/testutil"
"github.com/k0sproject/k0s/pkg/certificate"
"github.com/k0sproject/k0s/pkg/config"
"github.com/k0sproject/k0s/pkg/constant"
)

Expand All @@ -47,12 +46,11 @@ spec:
api:
externalAddress: 10.0.0.86
`
cfgFilePath, err := file.WriteTmpFile(yamlData, "k0s-config")
configGetter := testutil.NewConfigGetter(yamlData, false, constant.GetConfig(""))
cfg, err := configGetter.FakeConfigFromFile()
s.NoError(err)

c := CmdOpts(config.GetCmdOpts())
c.CfgFile = cfgFilePath

defer os.Remove(testutil.RuntimeFakePath)
caCert := `
-----BEGIN CERTIFICATE-----
MIIDADCCAeigAwIBAgIUW+2hawM8HgHrfxmDRV51wOq95icwDQYJKoZIhvcNAQEL
Expand Down Expand Up @@ -121,12 +119,15 @@ yJm2KSue0toWmkBFK8WMTjAvmAw3Z/qUhJRKoqCu3k6Mf8DNl6t+Uw==
certManager := certificate.Manager{
K0sVars: k0sVars,
}
err = os.Mkdir(path.Join(k0sVars.CertRootDir), 0755)

userCert, err := certManager.EnsureCertificate(userReq, "root")
pkiPath := path.Join(k0sVars.CertRootDir)
err = os.Mkdir(pkiPath, 0o755)
s.NoError(err)
clusterAPIURL, err := c.getAPIURL()

defer os.RemoveAll(pkiPath)
userCert, err := certManager.EnsureCertificate(userReq, "root")
s.NoError(err)
clusterAPIURL := cfg.Spec.API.APIAddressURL()

data := struct {
CACert string
Expand All @@ -151,8 +152,6 @@ yJm2KSue0toWmkBFK8WMTjAvmAw3Z/qUhJRKoqCu3k6Mf8DNl6t+Uw==
config, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath)
s.NoError(err)
s.Equal("https://10.0.0.86:6443", config.Host)
_, err = v1beta1.ConfigFromString(yamlData)
s.NoError(err)
}

func TestCLITestSuite(t *testing.T) {
Expand Down
Loading

0 comments on commit 5bf44c5

Please sign in to comment.