refactor cluster connection in CLI

This commit is contained in:
Pavel Sviderski
2024-09-11 18:40:06 +10:00
parent c56f81bac2
commit 03c2c0df39
4 changed files with 95 additions and 111 deletions
+25 -17
View File
@@ -1,15 +1,14 @@
package machine
import (
"context"
"fmt"
"github.com/spf13/cobra"
"uncloud/internal/cli"
"uncloud/internal/cli/config"
)
type addOptions struct {
name string
user string
port int
sshKey string
cluster string
}
@@ -17,25 +16,34 @@ type addOptions struct {
func NewAddCommand() *cobra.Command {
opts := addOptions{}
cmd := &cobra.Command{
// TODO: add support for [USER@]HOST[:PORT] syntax
Use: "add HOST",
Short: "Add a new machine to a cluster.",
Use: "add [USER@]HOST[:PORT]",
Short: "Add a remote machine to a cluster.",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
uncli := cmd.Context().Value("cli").(*cli.CLI)
return add(cmd.Context(), uncli, args[0], opts)
user, host, port, err := config.SSHDestination(args[0]).Parse()
if err != nil {
return fmt.Errorf("parse remote machine: %w", err)
}
remoteMachine := cli.RemoteMachine{
User: user,
Host: host,
Port: port,
KeyPath: opts.sshKey,
}
return uncli.AddMachine(cmd.Context(), remoteMachine, opts.cluster, opts.name)
},
}
cmd.Flags().StringVarP(&opts.name, "name", "n", "", "Assign a name to the machine")
cmd.Flags().StringVarP(&opts.user, "user", "u", "root", "Username for SSH remote login")
cmd.Flags().IntVarP(&opts.port, "port", "p", 22, "Port for SSH remote login")
cmd.Flags().StringVarP(&opts.sshKey, "ssh-key", "i", "",
"path to SSH private key for SSH remote login (default ~/.ssh/id_*)")
cmd.Flags().StringVarP(&opts.cluster, "cluster", "c", "",
"Name of the cluster to add the machine to (default is the current cluster)")
cmd.Flags().StringVarP(
&opts.sshKey, "ssh-key", "i", "",
"path to SSH private key for SSH remote login (default ~/.ssh/id_*)",
)
cmd.Flags().StringVarP(
&opts.cluster, "cluster", "c", "",
"Name of the cluster to add the machine to (default is the current cluster)",
)
return cmd
}
func add(ctx context.Context, uncli *cli.CLI, host string, opts addOptions) error {
return uncli.AddMachine(ctx, opts.cluster, opts.name, opts.user, host, opts.port, opts.sshKey)
}