Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support yurtadm config command #1709

Merged
merged 1 commit into from
Oct 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ require (
github.com/gorilla/mux v1.8.0
github.com/hashicorp/go-version v1.6.0
github.com/jarcoal/httpmock v1.3.0
github.com/lithammer/dedent v1.1.0
github.com/onsi/ginkgo/v2 v2.1.4
github.com/onsi/gomega v1.19.0
github.com/opencontainers/selinux v1.11.0
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,7 @@ github.com/leodido/go-urn v1.2.3/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNa
github.com/libopenstorage/openstorage v1.0.0/go.mod h1:Sp1sIObHjat1BeXhfMqLZ14wnOzEhNx2YQedreMcUyc=
github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0=
github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE=
github.com/lithammer/dedent v1.1.0 h1:VNzHMVCBNG1j0fh3OrsFRkVUwStdDArbgBWoPAffktY=
github.com/lithammer/dedent v1.1.0/go.mod h1:jrXYCQtgg0nJiN+StA2KgR7w6CiQNv9Fd/Z9BP0jIOc=
github.com/lpabon/godbc v0.1.1/go.mod h1:Jo9QV0cf3U6jZABgiJ2skINAXb9j8m51r07g4KI92ZA=
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
Expand Down
3 changes: 2 additions & 1 deletion pkg/yurtadm/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"k8s.io/klog/v2"

"github.com/openyurtio/openyurt/pkg/projectinfo"
"github.com/openyurtio/openyurt/pkg/yurtadm/cmd/config"
"github.com/openyurtio/openyurt/pkg/yurtadm/cmd/docs"
"github.com/openyurtio/openyurt/pkg/yurtadm/cmd/join"
"github.com/openyurtio/openyurt/pkg/yurtadm/cmd/renew"
Expand All @@ -52,7 +53,7 @@ func NewYurtadmCommand() *cobra.Command {
cmds.AddCommand(docs.NewDocsCmd(cmds))
cmds.AddCommand(renew.NewCmdRenew(os.Stdin, os.Stdout, os.Stderr))
cmds.AddCommand(staticpods.NewCmdStaticPods(os.Stdin, os.Stdout, os.Stderr))

cmds.AddCommand(config.NewCmdConfig(os.Stdin, os.Stdout, os.Stderr))
klog.InitFlags(nil)
// goflag.Parse()
flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
Expand Down
116 changes: 116 additions & 0 deletions pkg/yurtadm/cmd/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
Copyright 2023 The OpenYurt Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package config

import (
"fmt"
"io"
"path/filepath"

"github.com/lithammer/dedent"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/util/sets"

"github.com/openyurtio/openyurt/pkg/projectinfo"
"github.com/openyurtio/openyurt/pkg/util/templates"
"github.com/openyurtio/openyurt/pkg/yurtadm/constants"
"github.com/openyurtio/openyurt/pkg/yurtadm/util"
"github.com/openyurtio/openyurt/pkg/yurtadm/util/edgenode"
)

// NewCmdConfig returns cobra.Command for "yurtadm config" command
func NewCmdConfig(in io.Reader, out io.Writer, outErr io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "config",
Short: "Manage configuration for a openyurt cluster",
Run: util.SubCmdRun(),
}

cmd.AddCommand(newCmdConfigPrint(out))
return cmd
}

// newCmdConfigPrint returns cobra.Command for "yurtadm config print" command
func newCmdConfigPrint(out io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "print",
Short: "Print configuration",
Run: util.SubCmdRun(),
}
cmd.AddCommand(newCmdConfigPrintJoinDefaults(out))
return cmd
}

// newCmdConfigPrintJoinDefaults returns cobra.Command for "yurtadm config print join-defaults" command
func newCmdConfigPrintJoinDefaults(out io.Writer) *cobra.Command {
return newCmdConfigPrintActionDefaults(out, "join", getDefaultNodeConfigBytes)
}

func newCmdConfigPrintActionDefaults(out io.Writer, action string, configBytesProc func() (string, error)) *cobra.Command {
cmd := &cobra.Command{
Use: fmt.Sprintf("%s-defaults", action),
Short: fmt.Sprintf("Print default %s configuration, that can be used for 'yurtadm %s'", action, action),
Long: fmt.Sprintf(dedent.Dedent(`
This command prints objects such as the default %s configuration that is used for 'yurtadm %s'.

Note that sensitive values like the Bootstrap Token fields are replaced with placeholder values like %q in order to pass validation but
not perform the real computation for creating a token.
`), action, action, constants.PlaceholderToken),
RunE: func(cmd *cobra.Command, args []string) error {
return runConfigPrintActionDefaults(out, configBytesProc)
},
Args: cobra.NoArgs,
}
return cmd
}

func runConfigPrintActionDefaults(out io.Writer, configBytesProc func() (string, error)) error {
initialConfig, err := configBytesProc()
if err != nil {
return err
}

fmt.Fprint(out, initialConfig)
return nil
}

func getDefaultNodeConfigBytes() (string, error) {
KubeadmJoinDiscoveryFilePath := filepath.Join(constants.KubeletWorkdir, constants.KubeadmJoinDiscoveryFileName)
ignoreErrors := sets.String{}
name, err := edgenode.GetHostname("")
if err != nil {
return "", err
}
ctx := map[string]interface{}{
"kubeConfigPath": KubeadmJoinDiscoveryFilePath,
"tlsBootstrapToken": constants.PlaceholderToken,
"ignorePreflightErrors": ignoreErrors.List(),
"podInfraContainerImage": constants.PauseImagePath,
"nodeLabels": fmt.Sprintf("%s=true", projectinfo.GetEdgeWorkerLabelKey()),
"criSocket": constants.DefaultDockerCRISocket,
"name": name,
"networkPlugin": "cni",
"apiVersion": "kubeadm.k8s.io/v1beta3",
}

kubeadmJoinTemplate, err := templates.SubsituteTemplate(constants.KubeadmJoinConf, ctx)
if err != nil {
return "", err
}

return kubeadmJoinTemplate, nil
}
1 change: 1 addition & 0 deletions pkg/yurtadm/constants/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ const (
KubeletEnvironmentFile = "EnvironmentFile=.*"

BootstrapTokenPattern = `\A([a-z0-9]{6})\.([a-z0-9]{16})\z`
PlaceholderToken = "abcdef.0123456789abcdef"

DaemonReload = "systemctl daemon-reload"
RestartKubeletSvc = "systemctl restart kubelet"
Expand Down
45 changes: 45 additions & 0 deletions pkg/yurtadm/util/cmdutil.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
Copyright 2023 The OpenYurt Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package util

import (
"fmt"
"strings"

"github.com/pkg/errors"
"github.com/spf13/cobra"

util "github.com/openyurtio/openyurt/pkg/yurtadm/util/error"
)

// SubCmdRun returns a function that handles a case where a subcommand must be specified
// Without this callback, if a user runs just the command without a subcommand,
// or with an invalid subcommand, cobra will print usage information, but still exit cleanly.
func SubCmdRun() func(c *cobra.Command, args []string) {
return func(c *cobra.Command, args []string) {
if len(args) > 0 {
util.CheckErr(usageErrorf(c, "invalid subcommand %q", strings.Join(args, " ")))
}
c.Help()
util.CheckErr(util.ErrExit)
}
}

func usageErrorf(c *cobra.Command, format string, args ...interface{}) error {
msg := fmt.Sprintf(format, args...)
return errors.Errorf("%s\nSee '%s -h' for help and examples", msg, c.CommandPath())
}