|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + constants "github.com/pojntfx/godhcpd/cmd" |
| 7 | + godhcpd "github.com/pojntfx/godhcpd/pkg/proto/generated" |
| 8 | + "github.com/spf13/cobra" |
| 9 | + "github.com/spf13/viper" |
| 10 | + "gitlab.com/bloom42/libs/rz-go" |
| 11 | + "gitlab.com/bloom42/libs/rz-go/log" |
| 12 | + "google.golang.org/grpc" |
| 13 | + "sync" |
| 14 | +) |
| 15 | + |
| 16 | +var deleteCmd = &cobra.Command{ |
| 17 | + Use: "delete <id> [id...]", |
| 18 | + Aliases: []string{"d"}, |
| 19 | + Short: "Delete one or more dhcp client(s)", |
| 20 | + Args: cobra.MinimumNArgs(1), |
| 21 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 22 | + conn, err := grpc.Dial(viper.GetString(serverHostPortKey), grpc.WithInsecure(), grpc.WithBlock()) |
| 23 | + if err != nil { |
| 24 | + return err |
| 25 | + } |
| 26 | + defer conn.Close() |
| 27 | + |
| 28 | + client := godhcpd.NewDHClientManagerClient(conn) |
| 29 | + |
| 30 | + ctx, cancel := context.WithCancel(context.Background()) |
| 31 | + defer cancel() |
| 32 | + |
| 33 | + var wg sync.WaitGroup |
| 34 | + |
| 35 | + for _, id := range args { |
| 36 | + wg.Add(1) |
| 37 | + |
| 38 | + go func(id string, wg *sync.WaitGroup) { |
| 39 | + response, err := client.Delete(ctx, &godhcpd.DHClientManagedId{ |
| 40 | + Id: id, |
| 41 | + }) |
| 42 | + if err != nil { |
| 43 | + log.Error(err.Error()) |
| 44 | + |
| 45 | + wg.Done() |
| 46 | + |
| 47 | + return |
| 48 | + } |
| 49 | + |
| 50 | + fmt.Printf("dhcp client \"%s\" deleted\n", response.GetId()) |
| 51 | + |
| 52 | + wg.Done() |
| 53 | + }(id, &wg) |
| 54 | + } |
| 55 | + |
| 56 | + wg.Wait() |
| 57 | + |
| 58 | + return nil |
| 59 | + }, |
| 60 | +} |
| 61 | + |
| 62 | +func init() { |
| 63 | + var ( |
| 64 | + serverHostPortFlag string |
| 65 | + ) |
| 66 | + |
| 67 | + deleteCmd.PersistentFlags().StringVarP(&serverHostPortFlag, serverHostPortKey, "s", constants.DHClientDHostPortDefault, "Host:port of the godhcpd server to use.") |
| 68 | + |
| 69 | + if err := viper.BindPFlags(deleteCmd.PersistentFlags()); err != nil { |
| 70 | + log.Fatal(constants.CouldNotBindFlagsErrorMessage, rz.Err(err)) |
| 71 | + } |
| 72 | + |
| 73 | + viper.AutomaticEnv() |
| 74 | + |
| 75 | + rootCmd.AddCommand(deleteCmd) |
| 76 | +} |
0 commit comments