From 4c093fa13a6bdfc4eb9ae059738e887cb7d5f5cb Mon Sep 17 00:00:00 2001 From: Ryota Sakamoto Date: Sun, 16 Jun 2024 21:42:39 +0900 Subject: [PATCH] add clean command --- pkg/cmd/clean.go | 19 +++++++++++++++++++ pkg/multipass/multipass.go | 18 ++++++++++++++++++ pkg/provisioner/cluster.go | 25 +++++++++++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 pkg/cmd/clean.go diff --git a/pkg/cmd/clean.go b/pkg/cmd/clean.go new file mode 100644 index 0000000..044da90 --- /dev/null +++ b/pkg/cmd/clean.go @@ -0,0 +1,19 @@ +package cmd + +import ( + "github.com/ryota-sakamoto/kubernetes-on-multipass/pkg/provisioner" + "github.com/spf13/cobra" +) + +var cleanCmd = &cobra.Command{ + Use: "clean", + Short: "Clean up a cluster", + RunE: func(cmd *cobra.Command, args []string) error { + return provisioner.Clean(cmd.Flag("cluster-name").Value.String()) + }, +} + +func init() { + rootCmd.AddCommand(cleanCmd) + cleanCmd.Flags().StringP("cluster-name", "", "kubernetes", "Cluster name") +} diff --git a/pkg/multipass/multipass.go b/pkg/multipass/multipass.go index 7db9d0f..eef4e7b 100644 --- a/pkg/multipass/multipass.go +++ b/pkg/multipass/multipass.go @@ -62,6 +62,24 @@ func LaunchInstance(config InstanceConfig, cloudinit string) error { return err } +func DeleteInstance(name string) error { + _, err := exec.Command("multipass", "delete", name).Output() + if err != nil { + return err + } + + return nil +} + +func Purge() error { + _, err := exec.Command("multipass", "purge").Output() + if err != nil { + return err + } + + return nil +} + func Exec(name string, command string) (string, error) { args := []string{"exec", name, "--"} args = append(args, strings.Fields(command)...) diff --git a/pkg/provisioner/cluster.go b/pkg/provisioner/cluster.go index 85703c3..473d3ac 100644 --- a/pkg/provisioner/cluster.go +++ b/pkg/provisioner/cluster.go @@ -4,6 +4,7 @@ import ( "fmt" "log/slog" "os" + "strings" "github.com/goccy/go-yaml" "k8s.io/apimachinery/pkg/runtime" @@ -148,3 +149,27 @@ func GenerateKubeconfig(name string) error { return nil } + +func Clean(clusterName string) error { + slog.Debug("clean", slog.String("clusterName", clusterName)) + + instances, err := multipass.ListInstances() + if err != nil { + return fmt.Errorf("failed to list instances: %w", err) + } + + for _, instance := range instances.List { + if !strings.HasPrefix(instance.Name, clusterName) { + continue + } + + slog.Debug("delete instance", slog.String("name", instance.Name)) + err := multipass.DeleteInstance(instance.Name) + if err != nil { + return fmt.Errorf("failed to delete instance: %w", err) + } + } + + slog.Debug("purge instances") + return multipass.Purge() +}