master
go 123 lines 2.61 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package dnsmasq
4
5 import (
6 "context"
7 _ "embed"
8 "errors"
9 "fmt"
10 "time"
11
12 "github.com/miekg/dns"
13
14 "github.com/netdata/netdata/go/plugins/pkg/confopt"
15 "github.com/netdata/netdata/go/plugins/plugin/framework/collectorapi"
16 )
17
18 //go:embed "config_schema.json"
19 var configSchema string
20
21 func init() {
22 collectorapi.Register("dnsmasq", collectorapi.Creator{
23 JobConfigSchema: configSchema,
24 Create: func() collectorapi.CollectorV1 { return New() },
25 Config: func() any { return &Config{} },
26 })
27 }
28
29 func New() *Collector {
30 return &Collector{
31 Config: Config{
32 Protocol: "udp",
33 Address: "127.0.0.1:53",
34 Timeout: confopt.Duration(time.Second),
35 },
36
37 newDNSClient: func(network string, timeout time.Duration) dnsClient {
38 return &dns.Client{
39 Net: network,
40 Timeout: timeout,
41 }
42 },
43 }
44 }
45
46 type Config struct {
47 Vnode string `yaml:"vnode,omitempty" json:"vnode"`
48 UpdateEvery int `yaml:"update_every,omitempty" json:"update_every"`
49 AutoDetectionRetry int `yaml:"autodetection_retry,omitempty" json:"autodetection_retry"`
50 Address string `yaml:"address" json:"address"`
51 Protocol string `yaml:"protocol,omitempty" json:"protocol"`
52 Timeout confopt.Duration `yaml:"timeout,omitempty" json:"timeout"`
53 }
54
55 type (
56 Collector struct {
57 collectorapi.Base
58 Config `yaml:",inline" json:""`
59
60 charts *collectorapi.Charts
61
62 dnsClient dnsClient
63 newDNSClient func(network string, timeout time.Duration) dnsClient
64 }
65 dnsClient interface {
66 Exchange(msg *dns.Msg, address string) (resp *dns.Msg, rtt time.Duration, err error)
67 }
68 )
69
70 func (c *Collector) Configuration() any {
71 return c.Config
72 }
73
74 func (c *Collector) Init(context.Context) error {
75 err := c.validateConfig()
76 if err != nil {
77 return fmt.Errorf("config validation: %v", err)
78 }
79
80 client, err := c.initDNSClient()
81 if err != nil {
82 return fmt.Errorf("init DNS client: %v", err)
83 }
84 c.dnsClient = client
85
86 charts, err := c.initCharts()
87 if err != nil {
88 return fmt.Errorf("init charts: %v", err)
89 }
90 c.charts = charts
91
92 return nil
93 }
94
95 func (c *Collector) Check(context.Context) error {
96 mx, err := c.collect()
97 if err != nil {
98 return err
99 }
100 if len(mx) == 0 {
101 return errors.New("no metrics collected")
102
103 }
104 return nil
105 }
106
107 func (c *Collector) Charts() *collectorapi.Charts {
108 return c.charts
109 }
110
111 func (c *Collector) Collect(context.Context) map[string]int64 {
112 ms, err := c.collect()
113 if err != nil {
114 c.Error(err)
115 }
116
117 if len(ms) == 0 {
118 return nil
119 }
120 return ms
121 }
122
123 func (c *Collector) Cleanup(context.Context) {}