add uncloud machine init command to initialise a new cluster on local machine

This commit is contained in:
Pavel Sviderski
2024-09-05 12:21:01 +10:00
parent 58fb3105cd
commit 3f71aec275
7 changed files with 222 additions and 53 deletions
+64
View File
@@ -0,0 +1,64 @@
package machine
import (
"fmt"
"github.com/spf13/cobra"
"net/netip"
"uncloud/internal/machine"
"uncloud/internal/machine/api/pb"
"uncloud/internal/machine/daemon"
"uncloud/internal/machine/network"
"uncloud/internal/secret"
)
type initOptions struct {
name string
network string
userPublicKey string
dataDir string
}
func NewInitCommand() *cobra.Command {
opts := initOptions{}
cmd := &cobra.Command{
Use: "init",
Short: "Initialise a new cluster that consists of the local or remote machine",
RunE: func(cmd *cobra.Command, args []string) error {
netPrefix, err := netip.ParsePrefix(opts.network)
if err != nil {
return fmt.Errorf("parse network CIDR: %w", err)
}
var users []*pb.User
if opts.userPublicKey != "" {
pubKey, uErr := secret.FromHexString(opts.userPublicKey)
if uErr != nil {
return fmt.Errorf("parse user's public key: %w", uErr)
}
user := &pb.User{
Network: &pb.NetworkConfig{
ManagementIp: pb.NewIP(network.ManagementIP(pubKey)),
PublicKey: pubKey,
},
}
users = append(users, user)
}
if err = daemon.InitCluster(opts.dataDir, opts.name, netPrefix, users); err != nil {
return fmt.Errorf("initialise cluster: %w", err)
}
return nil
},
}
cmd.Flags().StringVarP(&opts.name, "name", "n", "", "Assign a name to the machine")
cmd.Flags().StringVar(&opts.network, "network", network.DefaultNetwork.String(),
"IPv4 network CIDR to use for machines and services")
cmd.Flags().StringVarP(&opts.userPublicKey, "user-pubkey", "u", "",
"User's public key which will be able to access the cluster (hex-encoded)")
cmd.Flags().StringVarP(&opts.dataDir, "data-dir", "d", machine.DefaultDataDir,
"Directory for storing persistent machine state")
_ = cmd.MarkFlagDirname("data-dir")
return cmd
}
+1
View File
@@ -11,6 +11,7 @@ func NewRootCommand() *cobra.Command {
}
cmd.AddCommand(
NewAddCommand(),
NewInitCommand(),
)
return cmd
}
+9 -2
View File
@@ -21,7 +21,14 @@ func main() {
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
return daemon.Run(cmd.Context(), dataDir)
d, err := daemon.New(dataDir)
if err != nil {
return err
}
if err = d.Run(cmd.Context()); err == nil {
slog.Info("Daemon stopped.")
}
return err
},
}
cmd.PersistentFlags().StringVarP(&dataDir, "data-dir", "d", machine.DefaultDataDir,
@@ -41,5 +48,5 @@ func main() {
}()
cobra.CheckErr(cmd.ExecuteContext(ctx))
slog.Info("Daemon stopped.")
}