|
| 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 | +) |
| 14 | + |
| 15 | +var applyCmd = &cobra.Command{ |
| 16 | + Use: "apply", |
| 17 | + Aliases: []string{"a"}, |
| 18 | + Short: "Apply a dhcp client", |
| 19 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 20 | + if !(viper.GetString(configFileKey) == configFileDefault) { |
| 21 | + viper.SetConfigFile(viper.GetString(configFileKey)) |
| 22 | + |
| 23 | + if err := viper.ReadInConfig(); err != nil { |
| 24 | + return err |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + conn, err := grpc.Dial(viper.GetString(serverHostPortKey), grpc.WithInsecure(), grpc.WithBlock()) |
| 29 | + if err != nil { |
| 30 | + return err |
| 31 | + } |
| 32 | + defer conn.Close() |
| 33 | + |
| 34 | + client := godhcpd.NewDHClientManagerClient(conn) |
| 35 | + |
| 36 | + ctx, cancel := context.WithCancel(context.Background()) |
| 37 | + defer cancel() |
| 38 | + |
| 39 | + response, err := client.Create(ctx, &godhcpd.DHClient{ |
| 40 | + Device: viper.GetString(deviceKey), |
| 41 | + }) |
| 42 | + if err != nil { |
| 43 | + return err |
| 44 | + } |
| 45 | + |
| 46 | + fmt.Printf("dhcp client \"%s\" created\n", response.GetId()) |
| 47 | + |
| 48 | + return nil |
| 49 | + }, |
| 50 | +} |
| 51 | + |
| 52 | +func init() { |
| 53 | + var ( |
| 54 | + serverHostPortFlag string |
| 55 | + configFileFlag string |
| 56 | + deviceFlag string |
| 57 | + ) |
| 58 | + |
| 59 | + applyCmd.PersistentFlags().StringVarP(&serverHostPortFlag, serverHostPortKey, "s", constants.DHClientDHostPortDefault, "Host:port of the dhclientd server to use.") |
| 60 | + applyCmd.PersistentFlags().StringVarP(&configFileFlag, configFileKey, "f", configFileDefault, "Configuration file to use.") |
| 61 | + applyCmd.PersistentFlags().StringVarP(&deviceFlag, deviceKey, "d", "edge1", "Device to bind to.") |
| 62 | + |
| 63 | + if err := viper.BindPFlags(applyCmd.PersistentFlags()); err != nil { |
| 64 | + log.Fatal(constants.CouldNotBindFlagsErrorMessage, rz.Err(err)) |
| 65 | + } |
| 66 | + |
| 67 | + viper.AutomaticEnv() |
| 68 | + |
| 69 | + rootCmd.AddCommand(applyCmd) |
| 70 | +} |
0 commit comments