Tim Windelschmidt | 886c386 | 2023-05-23 16:47:41 +0200 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "time" |
| 6 | |
Tim Windelschmidt | 72a903f | 2023-06-27 15:49:36 +0200 | [diff] [blame] | 7 | "github.com/packethost/packngo" |
Tim Windelschmidt | 886c386 | 2023-05-23 16:47:41 +0200 | [diff] [blame] | 8 | "github.com/spf13/cobra" |
| 9 | "k8s.io/klog/v2" |
| 10 | |
Tim Windelschmidt | b6308cd | 2023-10-10 21:19:03 +0200 | [diff] [blame^] | 11 | "source.monogon.dev/cloud/equinix/wrapngo" |
Tim Windelschmidt | 886c386 | 2023-05-23 16:47:41 +0200 | [diff] [blame] | 12 | clicontext "source.monogon.dev/metropolis/cli/pkg/context" |
| 13 | ) |
| 14 | |
| 15 | var deleteCmd = &cobra.Command{ |
| 16 | Use: "delete [target]", |
| 17 | Short: "Delete all devices from one project", |
| 18 | Args: cobra.ExactArgs(1), |
| 19 | Run: doDelete, |
| 20 | } |
| 21 | |
| 22 | func init() { |
| 23 | rootCmd.AddCommand(deleteCmd) |
| 24 | } |
| 25 | |
| 26 | func doDelete(cmd *cobra.Command, args []string) { |
| 27 | ctx := clicontext.WithInterrupt(context.Background()) |
| 28 | api := wrapngo.New(&c) |
| 29 | |
| 30 | klog.Infof("Listing devices for %q", args[0]) |
| 31 | |
| 32 | devices, err := api.ListDevices(ctx, args[0]) |
| 33 | if err != nil { |
| 34 | klog.Exitf("failed listing devices: %v", err) |
| 35 | } |
| 36 | |
| 37 | if len(devices) == 0 { |
| 38 | klog.Infof("No devices found in %s", args[0]) |
| 39 | return |
| 40 | } |
| 41 | |
| 42 | klog.Infof("Deleting %d Devices in %s. THIS WILL DELETE SERVERS! You have five seconds to cancel!", len(devices), args[0]) |
| 43 | time.Sleep(5 * time.Second) |
| 44 | |
| 45 | for _, d := range devices { |
Tim Windelschmidt | 72a903f | 2023-06-27 15:49:36 +0200 | [diff] [blame] | 46 | h := "deleted-" + d.Hostname |
| 47 | _, err := api.UpdateDevice(ctx, d.ID, &packngo.DeviceUpdateRequest{ |
| 48 | Hostname: &h, |
| 49 | }) |
| 50 | if err != nil { |
| 51 | klog.Infof("failed updating device %s (%s): %v", d.ID, d.Hostname, err) |
| 52 | continue |
| 53 | } |
| 54 | |
Tim Windelschmidt | 886c386 | 2023-05-23 16:47:41 +0200 | [diff] [blame] | 55 | klog.Infof("deleting %s (%s)...", d.ID, d.Hostname) |
| 56 | if err := api.DeleteDevice(ctx, d.ID); err != nil { |
| 57 | klog.Infof("failed deleting device %s (%s): %v", d.ID, d.Hostname, err) |
| 58 | continue |
| 59 | } |
| 60 | } |
| 61 | } |