ipam/cmd/subnet-list.go

89 lines
2.2 KiB
Go
Raw Normal View History

2023-03-11 13:49:35 +01:00
/*
Copyright © 2023 Laura Kalb <dev@lauka.net>
*/
package cmd
import (
"fmt"
2023-03-14 17:21:49 +01:00
"math"
"net/netip"
"os"
"sort"
2023-03-11 13:49:35 +01:00
"github.com/spf13/cobra"
)
// listCmd represents the list command
var subnetlistCmd = &cobra.Command{
Use: "list",
Short: "List all subnets",
Long: `List all subnets`,
Aliases: []string{"l"},
Args: cobra.ExactArgs(0),
2023-03-14 17:21:49 +01:00
Example: "cmdb subnet list",
2023-03-11 13:49:35 +01:00
Run: func(cmd *cobra.Command, args []string) {
2023-03-16 20:57:21 +01:00
//verbose, _ := cmd.Flags().GetBool("verbose")
2023-03-14 17:21:49 +01:00
subnetlist := ListSubnets()
var subnets []Subnet
for _, subnet := range subnetlist {
prefix, _ := netip.ParsePrefix(subnet)
net, err := GetSubnet(prefix)
if err != nil {
fmt.Println("[ERROR]", err)
os.Exit(1)
}
subnets = append(subnets, net)
}
sort.Slice(subnets, func(i, j int) bool {
return subnets[i].Subnet.Addr().Less(subnets[j].Subnet.Addr())
})
2023-03-24 17:59:51 +01:00
fmt.Printf("%-15s VLAN %-25s Free IPs\n", "Prefix", "Name")
2023-03-14 17:21:49 +01:00
for _, subnet := range subnets {
2023-03-16 20:57:21 +01:00
var numip, freeip int
2023-03-14 17:21:49 +01:00
2023-03-16 20:57:21 +01:00
if subnet.Subnet.Addr().Is4() {
hostbits := float64(32 - subnet.Subnet.Bits())
2023-03-23 13:53:46 +01:00
if subnet.Subnet.Bits() == 31 {
numip = 2
} else {
numip = int(math.Pow(2, hostbits)) - 2
}
2023-03-16 20:57:21 +01:00
freeip = numip - len(subnet.Addresses)
2023-03-14 17:21:49 +01:00
2023-03-24 17:59:51 +01:00
if freeip > 1000 {
fmt.Printf("%-15s %-4s %-25s >1000\n", subnet.Subnet, subnet.Vlan, subnet.Name)
} else {
//fmt.Printf("| %-20s | %-20s |\n", "vegetables", "fruits")
fmt.Printf("%-15s %-4s %-25s %v\n", subnet.Subnet, subnet.Vlan, subnet.Name, freeip)
}
2023-03-14 17:21:49 +01:00
} else {
fmt.Printf("%v:\t%v\t(vl: %v)\n", subnet.Subnet, subnet.Name, subnet.Vlan)
2023-03-24 17:59:51 +01:00
//todo
2023-03-14 17:21:49 +01:00
}
2023-03-16 20:57:21 +01:00
//} else {
// fmt.Printf("%v:\t%v\t(vl: %v)\n", subnet.Subnet, subnet.Name, subnet.Vlan)
//}
2023-03-14 17:21:49 +01:00
}
2023-03-11 13:49:35 +01:00
},
}
func init() {
subnetCmd.AddCommand(subnetlistCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// listCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
2023-03-16 20:57:21 +01:00
// subnetlistCmd.Flags().BoolP("verbose", "v", false, "Show verbose output like free IPs")
2023-03-11 13:49:35 +01:00
}