github.com/netdata/go.d.plugin@v0.58.1/modules/dnsmasq/dnsmasq.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package dnsmasq
     4  
     5  import (
     6  	_ "embed"
     7  	"time"
     8  
     9  	"github.com/netdata/go.d.plugin/agent/module"
    10  	"github.com/netdata/go.d.plugin/pkg/web"
    11  
    12  	"github.com/miekg/dns"
    13  )
    14  
    15  //go:embed "config_schema.json"
    16  var configSchema string
    17  
    18  func init() {
    19  	module.Register("dnsmasq", module.Creator{
    20  		JobConfigSchema: configSchema,
    21  		Create:          func() module.Module { return New() },
    22  	})
    23  }
    24  
    25  func New() *Dnsmasq {
    26  	return &Dnsmasq{
    27  		Config: Config{
    28  			Protocol: "udp",
    29  			Address:  "127.0.0.1:53",
    30  			Timeout:  web.Duration{Duration: time.Second},
    31  		},
    32  
    33  		newDNSClient: func(network string, timeout time.Duration) dnsClient {
    34  			return &dns.Client{
    35  				Net:     network,
    36  				Timeout: timeout,
    37  			}
    38  		},
    39  	}
    40  }
    41  
    42  type Config struct {
    43  	Protocol string       `yaml:"protocol"`
    44  	Address  string       `yaml:"address"`
    45  	Timeout  web.Duration `yaml:"timeout"`
    46  }
    47  
    48  type (
    49  	Dnsmasq struct {
    50  		module.Base
    51  		Config `yaml:",inline"`
    52  
    53  		newDNSClient func(network string, timeout time.Duration) dnsClient
    54  		dnsClient    dnsClient
    55  
    56  		charts *module.Charts
    57  	}
    58  
    59  	dnsClient interface {
    60  		Exchange(msg *dns.Msg, address string) (resp *dns.Msg, rtt time.Duration, err error)
    61  	}
    62  )
    63  
    64  func (d *Dnsmasq) Init() bool {
    65  	err := d.validateConfig()
    66  	if err != nil {
    67  		d.Errorf("config validation: %v", err)
    68  		return false
    69  	}
    70  
    71  	client, err := d.initDNSClient()
    72  	if err != nil {
    73  		d.Errorf("init DNS client: %v", err)
    74  		return false
    75  	}
    76  	d.dnsClient = client
    77  
    78  	charts, err := d.initCharts()
    79  	if err != nil {
    80  		d.Errorf("init charts: %v", err)
    81  		return false
    82  	}
    83  	d.charts = charts
    84  
    85  	return true
    86  }
    87  
    88  func (d *Dnsmasq) Check() bool {
    89  	return len(d.Collect()) > 0
    90  }
    91  
    92  func (d *Dnsmasq) Charts() *module.Charts {
    93  	return d.charts
    94  }
    95  
    96  func (d *Dnsmasq) Collect() map[string]int64 {
    97  	ms, err := d.collect()
    98  	if err != nil {
    99  		d.Error(err)
   100  	}
   101  
   102  	if len(ms) == 0 {
   103  		return nil
   104  	}
   105  	return ms
   106  }
   107  
   108  func (Dnsmasq) Cleanup() {}