Skip to content

Commit

Permalink
refactor(autok3s): change command flags
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 18, 2020
1 parent 2416ea0 commit 13e83b4
Show file tree
Hide file tree
Showing 10 changed files with 130 additions and 117 deletions.
14 changes: 13 additions & 1 deletion cmd/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,33 @@ import (

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

"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)

var (
Provider = ""
P providers.Provider

SSH = &types.SSH{
SSHKey: "~/.ssh/id_rsa",
User: "root",
Port: "22",
}
)

func BindPFlags(cmd *cobra.Command, p providers.Provider) {
name, err := cmd.Flags().GetString("provider")
if err != nil {
logrus.Fatalln(err)
}

cmd.Flags().Visit(func(f *pflag.Flag) {
if IsCredentialFlag(f.Name, p.GetCredentialFlags(cmd)) {
if IsCredentialFlag(f.Name, p.BindCredentialFlags()) {
if err := viper.BindPFlag(fmt.Sprintf(common.BindPrefix, name, f.Name), f); err != nil {
logrus.Fatalln(err)
}
Expand Down
28 changes: 9 additions & 19 deletions cmd/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cmd
import (
"github.com/Jason-ZW/autok3s/cmd/common"
"github.com/Jason-ZW/autok3s/pkg/providers"
"github.com/Jason-ZW/autok3s/pkg/types"

"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
Expand All @@ -16,22 +15,13 @@ var (
Short: "Create k3s cluster",
Example: ` autok3s create --provider alibaba`,
}

provider = ""
p providers.Provider

ssh = &types.SSH{
SSHKeyPath: "~/.ssh/id_rsa",
User: "root",
Port: "22",
}
)

func init() {
createCmd.Flags().StringVarP(&provider, "provider", "p", provider, "Provider is a module which provides an interface for managing cloud resources")
createCmd.Flags().StringVar(&ssh.User, "sshUser", ssh.User, "SSH user for host")
createCmd.Flags().StringVar(&ssh.Port, "sshPort", ssh.Port, "SSH port for host")
createCmd.Flags().StringVar(&ssh.SSHKeyPath, "sshKeyPath", ssh.SSHKeyPath, "SSH private key path")
createCmd.Flags().StringVarP(&common.Provider, "provider", "p", common.Provider, "Provider is a module which provides an interface for managing cloud resources")
createCmd.Flags().StringVar(&common.SSH.User, "user", common.SSH.User, "SSH user for host")
createCmd.Flags().StringVar(&common.SSH.Port, "ssh-port", common.SSH.Port, "SSH port for host")
createCmd.Flags().StringVar(&common.SSH.SSHKey, "ssh-key", common.SSH.SSHKey, "SSH private key path")
}

func CreateCommand() *cobra.Command {
Expand All @@ -41,16 +31,16 @@ func CreateCommand() *cobra.Command {
if reg, err := providers.Register(pStr); err != nil {
logrus.Fatalln(err)
} else {
p = reg
common.P = reg
}

createCmd.Flags().AddFlagSet(p.GetCredentialFlags(createCmd))
createCmd.Flags().AddFlagSet(p.GetCreateFlags(createCmd))
createCmd.Flags().AddFlagSet(common.P.GetCredentialFlags(createCmd))
createCmd.Flags().AddFlagSet(common.P.GetCreateFlags(createCmd))
}

createCmd.Run = func(cmd *cobra.Command, args []string) {
// must bind after dynamic provider flags loaded.
common.BindPFlags(cmd, p)
common.BindPFlags(cmd, common.P)

// read options from config.
if err := viper.ReadInConfig(); err != nil {
Expand All @@ -62,7 +52,7 @@ func CreateCommand() *cobra.Command {
logrus.Fatalln(err)
}

if err := p.CreateK3sCluster(ssh); err != nil {
if err := common.P.CreateK3sCluster(common.SSH); err != nil {
logrus.Fatalln(err)
}
}
Expand Down
21 changes: 10 additions & 11 deletions pkg/hosts/dialer.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ type Host struct {
}

type dialer struct {
signer ssh.Signer
sshKeyString string
sshAddress string
username string
netConn string
signer ssh.Signer
sshKey string
sshAddress string
username string
netConn string
}

type DialersOptions struct {
Expand Down Expand Up @@ -73,14 +73,13 @@ func newDialer(h *Host, kind string) (*dialer, error) {
}

d = &dialer{
sshAddress: fmt.Sprintf("%s:%s", h.PublicIPAddress[0], h.Port),
username: h.User,
sshKeyString: h.SSHKey,
sshAddress: fmt.Sprintf("%s:%s", h.PublicIPAddress[0], h.Port),
username: h.User,
}

if d.sshKeyString == "" {
if d.sshKey == "" {
var err error
d.sshKeyString, err = utils.SSHPrivateKeyPath(h.SSHKeyPath)
d.sshKey, err = utils.SSHPrivateKeyPath(h.SSHKey)
if err != nil {
return nil, err
}
Expand All @@ -95,7 +94,7 @@ func newDialer(h *Host, kind string) (*dialer, error) {
}

func (d *dialer) getSSHTunnelConnection() (*ssh.Client, error) {
cfg, err := utils.GetSSHConfig(d.username, d.sshKeyString)
cfg, err := utils.GetSSHConfig(d.username, d.sshKey)
if err != nil {
return nil, err
}
Expand Down
36 changes: 21 additions & 15 deletions pkg/providers/alibaba/alibaba.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import (
)

const (
accessKeyID = "accessKeyID"
accessKeySecret = "accessKeySecret"
accessKeyID = "access-key"
accessKeySecret = "access-secret"
imageID = "ubuntu_18_04_x64_20G_alibase_20200618.vhd"
instanceType = "ecs.c6.large"
internetMaxBandwidthOut = "50"
Expand Down Expand Up @@ -60,8 +60,8 @@ func NewProvider() *Alibaba {
Options: alibaba.Options{
DiskCategory: diskCategory,
DiskSize: diskSize,
ImageID: imageID,
InstanceType: instanceType,
Image: imageID,
Type: instanceType,
InternetMaxBandwidthOut: internetMaxBandwidthOut,
},
Status: types.Status{
Expand Down Expand Up @@ -133,13 +133,13 @@ func (p *Alibaba) generateClientSDK() error {
func (p *Alibaba) runInstances(num int, master bool) error {
request := ecs.CreateRunInstancesRequest()
request.Scheme = "https"
request.InstanceType = p.InstanceType
request.ImageId = p.ImageID
request.VSwitchId = p.VSwitchID
request.KeyPairName = p.KeyPairName
request.InstanceType = p.Type
request.ImageId = p.Image
request.VSwitchId = p.VSwitch
request.KeyPairName = p.KeyPair
request.SystemDiskCategory = p.DiskCategory
request.SystemDiskSize = p.DiskSize
request.SecurityGroupId = p.SecurityGroupID
request.SecurityGroupId = p.SecurityGroup
outBandWidth, _ := strconv.Atoi(p.InternetMaxBandwidthOut)
request.InternetMaxBandwidthOut = requests.NewInteger(outBandWidth)
request.Amount = requests.NewInteger(num)
Expand Down Expand Up @@ -242,7 +242,7 @@ func (p *Alibaba) assembleInstanceStatus(ssh *types.SSH) (*types.Cluster, error)
v := value.(types.Node)
v.Port = ssh.Port
v.User = ssh.User
v.SSHKeyPath = ssh.SSHKeyPath
v.SSHKey = ssh.SSHKey
if v.Master {
p.Status.MasterNodes = append(p.Status.MasterNodes, v)
} else {
Expand Down Expand Up @@ -271,21 +271,27 @@ func (p *Alibaba) describeInstances() (*ecs.DescribeInstancesResponse, error) {
return response, nil
}

func (p *Alibaba) isClusterExist() bool {
func (p *Alibaba) isClusterExist() (bool, error) {
request := ecs.CreateDescribeInstancesRequest()
request.Scheme = "https"
request.InstanceName = strings.ToLower(fmt.Sprintf(common.WildcardInstanceName, p.Name))

response, err := p.c.DescribeInstances(request)
if err == nil && len(response.Instances.Instance) == 0 {
return true
if err != nil || len(response.Instances.Instance) > 0 {
return false, err
}

return false
return true, nil
}

func (p *Alibaba) preflight() error {
if !p.isClusterExist() {
exist, err := p.isClusterExist()

if err != nil {
return err
}

if !exist {
return errors.New(fmt.Sprintf("[%s] calling preflight error: cluster name `%s` already exist\n",
p.GetProviderName(), p.Name))
}
Expand Down
78 changes: 41 additions & 37 deletions pkg/providers/alibaba/flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,69 +25,69 @@ func (p *Alibaba) GetCreateFlags(cmd *cobra.Command) *pflag.FlagSet {
P: &p.Region,
V: p.Region,
ShortHand: "r",
Usage: "Regions are physical locations (data centers) that spread all over the world to reduce the network latency",
Usage: "Physical locations (data centers) that spread all over the world to reduce the network latency",
Required: true,
},
{
Name: "keyPairName",
P: &p.KeyPairName,
V: p.KeyPairName,
Name: "key-pair",
P: &p.KeyPair,
V: p.KeyPair,
ShortHand: "k",
Usage: "KeyPairName is used to connect to an instance",
Usage: "Used to connect to an instance",
Required: true,
},
{
Name: "imageID",
P: &p.ImageID,
V: p.ImageID,
Name: "image",
P: &p.Image,
V: p.Image,
ShortHand: "i",
Usage: "ImageID is used to specify the image to be used by the instance",
Usage: "Used to specify the image to be used by the instance",
Required: true,
},
{
Name: "instanceType",
P: &p.InstanceType,
V: p.InstanceType,
Name: "type",
P: &p.Type,
V: p.Type,
ShortHand: "t",
Usage: "InstanceType is used to specify the type to be used by the instance",
Usage: "Used to specify the type to be used by the instance",
Required: true,
},
{
Name: "vSwitchID",
P: &p.VSwitchID,
V: p.VSwitchID,
Name: "v-switch",
P: &p.VSwitch,
V: p.VSwitch,
ShortHand: "v",
Usage: "VSwitchID is used to specify the vSwitch to be used by the instance",
Usage: "Used to specify the vSwitch to be used by the instance",
Required: true,
},
{
Name: "diskCategory",
Name: "disk-category",
P: &p.DiskCategory,
V: p.DiskCategory,
Usage: "diskCategory is used to specify the system disk category used by the instance",
Usage: "Used to specify the system disk category used by the instance",
Required: true,
},
{
Name: "diskSize",
Name: "disk-size",
P: &p.DiskSize,
V: p.DiskSize,
Usage: "diskSize is used to specify the system disk size used by the instance",
Usage: "Used to specify the system disk size used by the instance",
Required: true,
},
{
Name: "securityGroupID",
P: &p.SecurityGroupID,
V: p.SecurityGroupID,
Name: "security-group",
P: &p.SecurityGroup,
V: p.SecurityGroup,
ShortHand: "s",
Usage: "securityGroupID is used to specify the security group used by the instance",
Usage: "Used to specify the security group used by the instance",
Required: true,
},
{
Name: "InternetMaxBandwidthOut",
Name: "internet-max-bandwidth-out",
P: &p.InternetMaxBandwidthOut,
V: p.InternetMaxBandwidthOut,
ShortHand: "o",
Usage: "internetMaxBandwidthOut is used to specify the maximum out flow of the instance internet",
Usage: "Used to specify the maximum out flow of the instance internet",
Required: true,
},
{
Expand Down Expand Up @@ -144,33 +144,30 @@ func (p *Alibaba) GetCredentialFlags(cmd *cobra.Command) *pflag.FlagSet {
fs := []types.Flag{
{
Name: accessKeyID,
P: &p.AccessKeyID,
V: p.AccessKeyID,
Usage: "User access key ID.",
P: &p.AccessKey,
V: p.AccessKey,
Usage: "User access key ID",
Required: true,
},
{
Name: accessKeySecret,
P: &p.AccessKeySecret,
V: p.AccessKeySecret,
Usage: "User access key secret.",
P: &p.AccessSecret,
V: p.AccessSecret,
Usage: "User access key secret",
Required: true,
},
}

nfs := pflag.NewFlagSet("", pflag.ContinueOnError)

for _, f := range fs {
if f.ShortHand == "" {
if cmd.Flags().Lookup(f.Name) == nil {
cmd.Flags().StringVar(f.P, f.Name, f.V, f.Usage)
nfs.StringVar(f.P, f.Name, f.V, f.Usage)
}
} else {
if cmd.Flags().Lookup(f.Name) == nil {
cmd.Flags().StringVarP(f.P, f.Name, f.ShortHand, f.V, f.Usage)
nfs.StringVarP(f.P, f.Name, f.ShortHand, f.V, f.Usage)
}

}
}

Expand All @@ -190,5 +187,12 @@ func (p *Alibaba) GetCredentialFlags(cmd *cobra.Command) *pflag.FlagSet {
return errors.New(fmt.Sprintf("required flags(s) \"%s\" not set\n", errFlags))
}

return cmd.Flags()
}

func (p *Alibaba) BindCredentialFlags() *pflag.FlagSet {
nfs := pflag.NewFlagSet("", pflag.ContinueOnError)
nfs.StringVar(&p.AccessKey, accessKeyID, p.AccessKey, "User access key ID")
nfs.StringVar(&p.AccessSecret, accessKeySecret, p.AccessSecret, "User access key secret")
return nfs
}
2 changes: 2 additions & 0 deletions pkg/providers/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ type Provider interface {
GetProviderName() string
GetCreateFlags(cmd *cobra.Command) *pflag.FlagSet
GetCredentialFlags(cmd *cobra.Command) *pflag.FlagSet
// Use this method to bind Viper, although it is somewhat repetitive.
BindCredentialFlags() *pflag.FlagSet
CreateK3sCluster(ssh *types.SSH) error
}

Expand Down
Loading

0 comments on commit 13e83b4

Please # to comment.