kea-manage/cmd/root.go

94 lines
2.5 KiB
Go
Raw Normal View History

/*
Copyright © 2024 Matthew Stobbs <matthew@stobbs.ca>
*/
package cmd
import (
"errors"
"log/slog"
"os"
"git.staur.ca/stobbsm/kea-manage/ipv4/reservation"
"git.staur.ca/stobbsm/kea-manage/lib/database"
"git.staur.ca/stobbsm/kea-manage/lib/database/postgres"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "kea-manage",
Short: "Manage the isc-kea dhcp server",
Long: `Manage the isc-kea dhcp server backend in database.`,
Run: runMain,
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func init() {
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.kea-manage.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
// Manage kea dhcp host reservations in postgresql directly
// postgresql schema used from [https://gitlab.isc.org/isc-projects/kea/-/wikis/docs/editing-host-reservations]
// This will only work with hw-address identifiers. If I need support for more, I'll add it
func runMain(cmd *cobra.Command, args []string) {
reslist := []*reservation.ReservationV4{}
vlist := viper.Get("reservationV4").([]any)
for _, v := range vlist {
v := v.(map[string]any)
r := reservation.ReserveV4MacAddr(
v["type"].(string),
v["identifier"].(string),
v["ipv4"].(string),
v["hostname"].(string),
v["subnetid"].(int),
)
if !r.Validate() {
slog.Error("reservation", slog.Any("validate", r))
continue
}
reslist = append(
reslist,
r,
)
}
slog.Debug("reslist", slog.Any("slice", reslist))
dbconf := viper.GetStringMapString("database")
pg := postgres.Open(dbconf["host"], dbconf["port"], dbconf["user"], dbconf["password"], dbconf["name"])
for _, v := range reslist {
v := v
2024-09-22 02:02:02 +00:00
if err := pg.InsertResV4(v); err != nil {
if errors.As(err, &database.Exists) {
slog.Info("exists", slog.Any("reservation", *v))
} else {
slog.Error(err.Error())
}
continue
}
slog.Info("inserted", slog.Any("reservation", *v))
}
}