| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | //go:build linux || freebsd || openbsd || netbsd || dragonfly |
| 4 | |
| 5 | package isc_dhcpd |
| 6 | |
| 7 | import ( |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "strings" |
| 11 | |
| 12 | "github.com/netdata/netdata/go/plugins/plugin/framework/collectorapi" |
| 13 | "github.com/netdata/netdata/go/plugins/plugin/go.d/pkg/iprange" |
| 14 | ) |
| 15 | |
| 16 | type ipPool struct { |
| 17 | name string |
| 18 | addresses *iprange.Pool |
| 19 | } |
| 20 | |
| 21 | func (c *Collector) validateConfig() error { |
| 22 | if c.Config.LeasesPath == "" { |
| 23 | return errors.New("'lease_path' parameter not set") |
| 24 | } |
| 25 | if len(c.Config.Pools) == 0 { |
| 26 | return errors.New("'pools' parameter not set") |
| 27 | } |
| 28 | for i, cfg := range c.Config.Pools { |
| 29 | if cfg.Name == "" { |
| 30 | return fmt.Errorf("'pools[%d]->pool.name' parameter not set", i+1) |
| 31 | } |
| 32 | if cfg.Networks == "" { |
| 33 | return fmt.Errorf("'pools[%d]->pool.networks' parameter not set", i+1) |
| 34 | } |
| 35 | } |
| 36 | return nil |
| 37 | } |
| 38 | |
| 39 | func (c *Collector) initPools() ([]ipPool, error) { |
| 40 | var pools []ipPool |
| 41 | |
| 42 | for i, cfg := range c.Pools { |
| 43 | ipRange, err := iprange.ParseRanges(cfg.Networks) |
| 44 | if err != nil { |
| 45 | return nil, fmt.Errorf("parse pools[%d]->pool.networks '%s' ('%s'): %v", i+1, cfg.Name, cfg.Networks, err) |
| 46 | } |
| 47 | if len(ipRange) == 0 { |
| 48 | continue |
| 49 | } |
| 50 | |
| 51 | pool := ipPool{name: cfg.Name, addresses: iprange.NewPool(ipRange...)} |
| 52 | pools = append(pools, pool) |
| 53 | } |
| 54 | |
| 55 | return pools, nil |
| 56 | } |
| 57 | |
| 58 | func (c *Collector) initCharts(pools []ipPool) (*collectorapi.Charts, error) { |
| 59 | charts := &collectorapi.Charts{} |
| 60 | |
| 61 | if err := charts.Add(activeLeasesTotalChart.Copy()); err != nil { |
| 62 | return nil, err |
| 63 | } |
| 64 | |
| 65 | for _, pool := range pools { |
| 66 | poolCharts := dhcpPoolChartsTmpl.Copy() |
| 67 | |
| 68 | for _, chart := range *poolCharts { |
| 69 | chart.ID = fmt.Sprintf(chart.ID, cleanPoolNameForChart(pool.name)) |
| 70 | chart.Labels = []collectorapi.Label{ |
| 71 | {Key: "dhcp_pool_name", Value: pool.name}, |
| 72 | } |
| 73 | for _, dim := range chart.Dims { |
| 74 | dim.ID = fmt.Sprintf(dim.ID, pool.name) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | if err := charts.Add(*poolCharts...); err != nil { |
| 79 | return nil, err |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | return charts, nil |
| 84 | } |
| 85 | |
| 86 | func cleanPoolNameForChart(name string) string { |
| 87 | name = strings.ReplaceAll(name, " ", "_") |
| 88 | name = strings.ReplaceAll(name, ".", "_") |
| 89 | return name |
| 90 | } |