Skip to content

Commit

Permalink
feat(autok3s): implements get command
Browse files Browse the repository at this point in the history
Signed-off-by: Jason-ZW <zhenyang@rancher.com>
  • Loading branch information
rancher-sy-bot committed Aug 17, 2020
1 parent 6f1e56c commit 2416ea0
Show file tree
Hide file tree
Showing 6 changed files with 140 additions and 33 deletions.
6 changes: 3 additions & 3 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ var (

func init() {
cobra.OnInitialize(initCfg)
cmd.PersistentFlags().StringVarP(&common.CfgFile, "cfg", "c", common.CfgFile, "Path to the cfg file to use for CLI requests")
cmd.Flags().StringVarP(&common.CfgPath, "cfg", "c", common.CfgPath, "Path to the cfg file to use for CLI requests")
}

func Command() *cobra.Command {
Expand All @@ -57,10 +57,10 @@ func Command() *cobra.Command {

func initCfg() {
viper.SetConfigType("yaml")
viper.SetConfigFile(common.CfgFile)
viper.SetConfigFile(fmt.Sprintf("%s/%s", common.CfgPath, common.ConfigFile))
viper.AutomaticEnv()

if err := utils.EnsureFileExist(common.CfgFile); err != nil {
if err := utils.EnsureFileExist(common.CfgPath, common.ConfigFile); err != nil {
logrus.Fatalln(err)
}
}
Expand Down
59 changes: 58 additions & 1 deletion cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,21 @@ package cmd
import (
"os"

"github.com/Jason-ZW/autok3s/pkg/cluster"
"github.com/Jason-ZW/autok3s/pkg/common"
"github.com/Jason-ZW/autok3s/pkg/providers"
"github.com/Jason-ZW/autok3s/pkg/utils"

"github.com/olekukonko/tablewriter"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

func GetCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "get",
Short: "Display one or many resources",
ValidArgs: []string{"provider"},
ValidArgs: []string{"provider", "cluster"},
Args: cobra.RangeArgs(1, 2),
Example: ` autok3s get provider`,
}
Expand All @@ -22,6 +26,8 @@ func GetCommand() *cobra.Command {
switch args[0] {
case "provider":
getProvider(args)
case "cluster":
getCluster(args)
}
}
return cmd
Expand All @@ -45,3 +51,54 @@ func getProvider(args []string) {
}
table.Render()
}

func getCluster(args []string) {
table := tablewriter.NewWriter(os.Stdout)
table.SetBorder(false)
table.SetHeaderLine(false)
table.SetColumnSeparator("")
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetHeader([]string{"Name", "Provider", "Masters", "Workers"})

input := ""
if len(args) > 1 {
input = args[1]
}

v := common.CfgPath
if v == "" {
logrus.Fatalln("state path is empty\n")
}

clusters, err := utils.ReadYaml(v, common.StateFile)
if err != nil {
logrus.Fatalf("read state file error, msg: %s\n", err.Error())
}

result, err := cluster.ConvertToClusters(clusters)
if err != nil {
logrus.Fatalf("failed to unmarshal state file, msg: %s\n", err.Error())
}

for _, r := range result {
if input != "" {
if input == r.Name {
table.Append([]string{
r.Name,
r.Provider,
r.Master,
r.Worker,
})
}
} else {
table.Append([]string{
r.Name,
r.Provider,
r.Master,
r.Worker,
})
}
}

table.Render()
}
3 changes: 3 additions & 0 deletions pkg/cli/kubectl/kubectl.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"os"
"time"

"github.com/Jason-ZW/autok3s/pkg/common"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
cliflag "k8s.io/component-base/cli/flag"
Expand All @@ -33,5 +35,6 @@ func Main() {
func EmbedCommand() *cobra.Command {
c := cmd.NewDefaultKubectlCommand()
c.Short = "Kubectl controls the Kubernetes cluster manager"
c.PersistentFlags().Set("kubeconfig", fmt.Sprintf("%s/%s", common.CfgPath, common.KubeCfgFile))
return c
}
66 changes: 48 additions & 18 deletions pkg/cluster/cluster.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
package cluster

import (
"encoding/json"
"errors"
"fmt"
"github.com/sirupsen/logrus"
"strings"

"github.com/Jason-ZW/autok3s/pkg/common"
"github.com/Jason-ZW/autok3s/pkg/hosts"
"github.com/Jason-ZW/autok3s/pkg/types"
"github.com/Jason-ZW/autok3s/pkg/utils"

"github.com/ghodss/yaml"
"github.com/sirupsen/logrus"
)

var (
masterCommand = "curl -sLS https://docs.rancher.cn/k3s/k3s-install.sh | INSTALL_K3S_MIRROR=cn K3S_TOKEN='%s' sh -\n"
masterCommand = "curl -sLS https://docs.rancher.cn/k3s/k3s-install.sh | INSTALL_K3S_MIRROR=cn K3S_TOKEN='%s' INSTALL_K3S_EXEC='--tls-san %s' sh -\n"
workerCommand = "curl -sLS https://docs.rancher.cn/k3s/k3s-install.sh | INSTALL_K3S_MIRROR=cn K3S_URL='https://%s:6443' K3S_TOKEN='%s' sh -\n"
catCfgCommand = "cat /etc/rancher/k3s/k3s.yaml"
)

func InitK3sCluster(cluster *types.Cluster) error {
Expand All @@ -29,72 +31,83 @@ func InitK3sCluster(cluster *types.Cluster) error {
}

url := cluster.MasterNodes[0].InternalIPAddress[0]
publicIP := cluster.MasterNodes[0].PublicIPAddress[0]

for _, master := range cluster.MasterNodes {
if err := initK3s(&hosts.Host{Node: master}, fmt.Sprintf(masterCommand, token)); err != nil {
if _, err := execute(&hosts.Host{Node: master}, fmt.Sprintf(masterCommand, token, publicIP), true); err != nil {
return err
}
}

for _, worker := range cluster.WorkerNodes {
if err := initK3s(&hosts.Host{Node: worker}, fmt.Sprintf(workerCommand, url, token)); err != nil {
if _, err := execute(&hosts.Host{Node: worker}, fmt.Sprintf(workerCommand, url, token), true); err != nil {
return err
}
}

// get k3s cluster config.
cfg, err := execute(&hosts.Host{Node: cluster.MasterNodes[0]}, catCfgCommand, false)
if err != nil {
return err
}

if err := writeCfg(cfg, publicIP, cluster.Name); err != nil {
return err
}

// write current cluster to state file.
return writeState(cluster)
}

func ConvertToClusters(origin []interface{}) ([]types.Cluster, error) {
result := make([]types.Cluster, 0)

b, err := json.Marshal(origin)
b, err := yaml.Marshal(origin)
if err != nil {
return nil, err
}

err = json.Unmarshal(b, &result)
err = yaml.Unmarshal(b, &result)
if err != nil {
return nil, err
}

return result, nil
}

func initK3s(host *hosts.Host, cmd string) error {
func execute(host *hosts.Host, cmd string, print bool) (string, error) {
dialer, err := hosts.SSHDialer(host)
if err != nil {
return err
return "", err
}

tunnel, err := dialer.OpenTunnel()
if err != nil {
return err
return "", err
}
defer func() {
_ = tunnel.Close()
}()

result, err := tunnel.ExecuteCommand(cmd)
if err != nil {
return err
return "", err
}

fmt.Printf("[dialer] execute command result: %s\n", result)
if print {
fmt.Printf("[dialer] execute command result: %s\n", result)
}

return nil
return result, nil
}

func writeState(cluster *types.Cluster) error {
v := common.CfgFile
v := common.CfgPath
if v == "" {
return errors.New("cfg path is empty\n")
}

p := v[0:strings.LastIndex(v, "/")]

clusters, err := utils.ReadYaml(p, common.StateFile)
clusters, err := utils.ReadYaml(v, common.StateFile)
if err != nil {
return err
}
Expand All @@ -116,5 +129,22 @@ func writeState(cluster *types.Cluster) error {
result = append(result, *cluster)
}

return utils.WriteYaml(result, p, common.StateFile)
return utils.WriteYaml(result, v, common.StateFile)
}

func writeCfg(cfg, ip, context string) error {
replacer := strings.NewReplacer(
"127.0.0.1", ip,
"localhost", ip,
"default", context,
)

result := replacer.Replace(cfg)

err := utils.EnsureFileExist(common.CfgPath, common.KubeCfgFile)
if err != nil {
return err
}

return utils.WriteBytesToYaml([]byte(result), common.CfgPath, common.KubeCfgFile)
}
4 changes: 3 additions & 1 deletion pkg/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ const (
WorkerInstanceName = WorkerInstancePrefix + "[%d,%d]" // autok3s.<cluster>.w<index>
WildcardInstanceName = "autok3s.%s.*" // autok3s.<cluster>.*
BindPrefix = "autok3s.providers.%s.%s"
ConfigFile = "config.yaml"
StateFile = ".state"
KubeCfgFile = ".kube/config"
)

var (
CfgFile = "/var/lib/rancher/autok3s/config.yaml"
CfgPath = "/var/lib/rancher/autok3s"
)
35 changes: 25 additions & 10 deletions pkg/utils/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"fmt"
"io/ioutil"
"os"
"strings"

"github.com/ghodss/yaml"
)
Expand All @@ -17,21 +16,20 @@ const (
UserProfileEnv = "USERPROFILE"
)

func EnsureFileExist(path string) error {
func EnsureFileExist(path, file string) error {
if path == "" {
return errors.New(fmt.Sprintf("path %s cannot be empty\n", path))
}

dir := path[0:strings.LastIndex(path, "/")]
if _, err := os.Stat(dir); os.IsNotExist(err) {
dirE := os.MkdirAll(dir, os.ModePerm)
if dirE != nil {
return dirE
}
n := fmt.Sprintf("%s/%s", path, file)

err := os.MkdirAll(path, os.ModePerm)
if err != nil && !os.IsExist(err) {
return err
}

if _, err := os.Stat(path); os.IsNotExist(err) {
_, fileE := os.Create(path)
if _, err := os.Stat(n); os.IsNotExist(err) {
_, fileE := os.Create(n)
if fileE != nil {
return fileE
}
Expand Down Expand Up @@ -74,6 +72,23 @@ func WriteYaml(source interface{}, path, name string) error {
return ioutil.WriteFile(n, b, 0644)
}

func WriteBytesToYaml(b []byte, path, name string) error {
n := fmt.Sprintf("%s/%s", path, name)

if _, err := os.Stat(n); os.IsNotExist(err) {
f, err := os.Create(n)
if err != nil {
return err
}

defer func() {
_ = f.Close()
}()
}

return ioutil.WriteFile(n, b, 0644)
}

func ReadYaml(path, name string) (i []interface{}, err error) {
n := fmt.Sprintf("%s/%s", path, name)

Expand Down

0 comments on commit 2416ea0

Please # to comment.