Skip to content

Commit

Permalink
refactor(autok3s): refactor get command & instances' name logic
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 Sep 8, 2020
1 parent 4c16456 commit a6de6a7
Show file tree
Hide file tree
Showing 6 changed files with 181 additions and 138 deletions.
108 changes: 65 additions & 43 deletions cmd/get.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
package cmd

import (
"fmt"
"os"
"strings"

"github.com/cnrancher/autok3s/pkg/cluster"
"github.com/cnrancher/autok3s/pkg/common"
"github.com/cnrancher/autok3s/pkg/providers"
"github.com/cnrancher/autok3s/pkg/providers/alibaba"
"github.com/cnrancher/autok3s/pkg/types"
typesAli "github.com/cnrancher/autok3s/pkg/types/alibaba"
"github.com/cnrancher/autok3s/pkg/utils"

"github.com/ghodss/yaml"
"github.com/olekukonko/tablewriter"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
Expand All @@ -22,15 +26,8 @@ var (
Args: cobra.ExactArgs(1),
Example: ` autok3s get cluster`,
}

name, region string
)

func init() {
getCmd.Flags().StringVar(&name, "name", name, "Cluster name")
getCmd.Flags().StringVar(&region, "region", region, "Physical locations (data centers) that spread all over the world to reduce the network latency")
}

func GetCommand() *cobra.Command {
getCmd.Run = func(cmd *cobra.Command, args []string) {
switch args[0] {
Expand Down Expand Up @@ -64,47 +61,72 @@ func getCluster() {
logrus.Fatalf("failed to unmarshal state file, msg: %s\n", err.Error())
}

var (
p providers.Provider
filters []*types.Cluster
removeCtx []string
)

// filter useless clusters & contexts.
for _, r := range result {
if name != "" && region != "" {
if fmt.Sprintf("%s.%s", name, region) == r.Name {
table.Append([]string{
name,
region,
r.Provider,
r.Master,
r.Worker,
})
switch r.Provider {
case "alibaba":
region := r.Name[strings.LastIndex(r.Name, ".")+1:]

b, err := yaml.Marshal(r.Options)
if err != nil {
logrus.Debugf("failed to convert cluster %s options\n", r.Name)
removeCtx = append(removeCtx, r.Name)
continue
}

option := &typesAli.Options{}
if err := yaml.Unmarshal(b, option); err != nil {
removeCtx = append(removeCtx, r.Name)
logrus.Debugf("failed to convert cluster %s options\n", r.Name)
continue
}
option.Region = region

p = &alibaba.Alibaba{
Metadata: r.Metadata,
Options: *option,
}
} else if name != "" {
if strings.Contains(r.Name, name) {
table.Append([]string{
r.Name[:strings.LastIndex(r.Name, ".")],
r.Name[strings.LastIndex(r.Name, ".")+1:],
r.Provider,
r.Master,
r.Worker,
})

isExist, ids, err := p.IsClusterExist()
if err != nil {
logrus.Fatalln(err)
}
} else if region != "" {
if strings.Contains(r.Name, region) {
table.Append([]string{
r.Name[:strings.LastIndex(r.Name, ".")],
r.Name[strings.LastIndex(r.Name, ".")+1:],
r.Provider,
r.Master,
r.Worker,
})

if isExist && len(ids) > 0 {
filters = append(filters, &r)
} else {
removeCtx = append(removeCtx, r.Name)
}
} else {
table.Append([]string{
r.Name[:strings.LastIndex(r.Name, ".")],
r.Name[strings.LastIndex(r.Name, ".")+1:],
r.Provider,
r.Master,
r.Worker,
})
}
}

// remove useless clusters from .state.
if err := cluster.FilterState(filters); err != nil {
logrus.Fatalf("failed to remove useless clusters\n")
}

// remove useless contexts from kubeCfg.
for _, r := range removeCtx {
if err := cluster.OverwriteCfg(r); err != nil {
logrus.Fatalf("failed to remove useless contexts\n")
}
}

for _, f := range filters {
table.Append([]string{
f.Name[:strings.LastIndex(f.Name, ".")],
f.Name[strings.LastIndex(f.Name, ".")+1:],
f.Provider,
f.Master,
f.Worker,
})
}

table.Render()
}
102 changes: 53 additions & 49 deletions pkg/cluster/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,12 +187,12 @@ func InitK3sCluster(cluster *types.Cluster) error {
}

// merge current cluster to kube config.
if err := saveCfg(cfg, publicIP, cluster.Name); err != nil {
if err := SaveCfg(cfg, publicIP, cluster.Name); err != nil {
return err
}

// write current cluster to state file.
if err := saveState(cluster); err != nil {
if err := SaveState(cluster); err != nil {
return err
}

Expand Down Expand Up @@ -236,8 +236,6 @@ func JoinK3sNode(merged, added *types.Cluster) error {
merged.URL = merged.MasterNodes[0].InternalIPAddress[0]
}

workerNum := 0

// TODO: join master node will be added soon.
for i := 0; i < len(added.WorkerNodes); i++ {
for _, full := range merged.WorkerNodes {
Expand All @@ -260,18 +258,15 @@ func JoinK3sNode(merged, added *types.Cluster) error {
return err
}

workerNum, _ = strconv.Atoi(merged.Worker)
workerNum = workerNum + 1

break
}
}
}

merged.Worker = strconv.Itoa(workerNum)
merged.Worker = strconv.Itoa(len(merged.WorkerNodes))

// write current cluster to state file.
return saveState(merged)
return SaveState(merged)
}

func ReadFromState(cluster *types.Cluster) ([]types.Cluster, error) {
Expand Down Expand Up @@ -358,38 +353,21 @@ func ConvertToClusters(origin []interface{}) ([]types.Cluster, error) {
return result, nil
}

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

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

result, err := tunnel.ExecuteCommand(cmd)
func SaveState(cluster *types.Cluster) error {
r, err := AppendToState(cluster)
if err != nil {
return "", err
return err
}

if print {
fmt.Printf("[dialer] execute command result:\n %s\n", result)
v := common.CfgPath
if v == "" {
return errors.New("[cluster] cfg path is empty\n")
}

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

func saveState(cluster *types.Cluster) error {
r, err := AppendToState(cluster)
if err != nil {
return err
}

func FilterState(r []*types.Cluster) error {
v := common.CfgPath
if v == "" {
return errors.New("[cluster] cfg path is empty\n")
Expand All @@ -398,7 +376,7 @@ func saveState(cluster *types.Cluster) error {
return utils.WriteYaml(r, v, common.StateFile)
}

func saveCfg(cfg, ip, context string) error {
func SaveCfg(cfg, ip, context string) error {
replacer := strings.NewReplacer(
"127.0.0.1", ip,
"localhost", ip,
Expand Down Expand Up @@ -428,6 +406,45 @@ func saveCfg(cfg, ip, context string) error {
return mergeCfg(context, temp.Name())
}

func OverwriteCfg(context string) error {
c, err := clientcmd.LoadFromFile(fmt.Sprintf("%s/%s", common.CfgPath, common.KubeCfgFile))
if err != nil {
return err
}

delete(c.Clusters, context)
delete(c.Contexts, context)
delete(c.AuthInfos, context)

return clientcmd.WriteToFile(*c, fmt.Sprintf("%s/%s", common.CfgPath, common.KubeCfgFile))
}

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

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

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

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

return result, nil
}

func mergeCfg(context, right string) error {
defer func() {
if err := os.Remove(right); err != nil {
Expand All @@ -439,7 +456,7 @@ func mergeCfg(context, right string) error {
return fmt.Errorf("[cluster] ensure kubecfg exist error, msg=%s\n", err.Error())
}

if err := overwriteCfg(context); err != nil {
if err := OverwriteCfg(context); err != nil {
return fmt.Errorf("[cluster] overwrite kubecfg error, msg=%s\n", err.Error())
}

Expand Down Expand Up @@ -469,16 +486,3 @@ func mergeCfg(context, right string) error {

return utils.WriteBytesToYaml(out.Bytes(), common.CfgPath, common.KubeCfgFile)
}

func overwriteCfg(context string) error {
c, err := clientcmd.LoadFromFile(fmt.Sprintf("%s/%s", common.CfgPath, common.KubeCfgFile))
if err != nil {
return err
}

delete(c.Clusters, context)
delete(c.Contexts, context)
delete(c.AuthInfos, context)

return clientcmd.WriteToFile(*c, fmt.Sprintf("%s/%s", common.CfgPath, common.KubeCfgFile))
}
15 changes: 6 additions & 9 deletions pkg/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,12 @@ import (
)

const (
MasterInstancePrefix = "autok3s.%s.m." // autok3s.<cluster.region>.m
WorkerInstancePrefix = "autok3s.%s.w." // autok3s.<cluster.region>.w
WildcardInstanceName = "autok3s.%s.*" // autok3s.<cluster.region>.*
BindPrefix = "autok3s.providers.%s.%s"
ConfigFile = "config.yaml"
StateFile = ".state"
KubeCfgFile = ".kube/config"
KubeCfgTempName = "autok3s-temp"
K3sManifestsDir = "/var/lib/rancher/k3s/server/manifests"
BindPrefix = "autok3s.providers.%s.%s"
ConfigFile = "config.yaml"
StateFile = ".state"
KubeCfgFile = ".kube/config"
KubeCfgTempName = "autok3s-temp"
K3sManifestsDir = "/var/lib/rancher/k3s/server/manifests"
)

var (
Expand Down
Loading

0 comments on commit a6de6a7

Please # to comment.