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

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package ping
     4  
     5  import (
     6  	_ "embed"
     7  	"time"
     8  
     9  	"github.com/netdata/go.d.plugin/agent/module"
    10  	"github.com/netdata/go.d.plugin/logger"
    11  	"github.com/netdata/go.d.plugin/pkg/web"
    12  
    13  	probing "github.com/prometheus-community/pro-bing"
    14  )
    15  
    16  //go:embed "config_schema.json"
    17  var configSchema string
    18  
    19  func init() {
    20  	module.Register("ping", module.Creator{
    21  		JobConfigSchema: configSchema,
    22  		Defaults: module.Defaults{
    23  			UpdateEvery: 5,
    24  		},
    25  		Create: func() module.Module { return New() },
    26  	})
    27  }
    28  
    29  func New() *Ping {
    30  	return &Ping{
    31  		Config: Config{
    32  			Network:     "ip",
    33  			Privileged:  true,
    34  			SendPackets: 5,
    35  			Interval:    web.Duration{Duration: time.Millisecond * 100},
    36  		},
    37  
    38  		charts:    &module.Charts{},
    39  		hosts:     make(map[string]bool),
    40  		newProber: newPingProber,
    41  	}
    42  }
    43  
    44  type Config struct {
    45  	UpdateEvery int          `yaml:"update_every"`
    46  	Hosts       []string     `yaml:"hosts"`
    47  	Network     string       `yaml:"network"`
    48  	Privileged  bool         `yaml:"privileged"`
    49  	SendPackets int          `yaml:"packets"`
    50  	Interval    web.Duration `yaml:"interval"`
    51  	Interface   string       `yaml:"interface"`
    52  }
    53  
    54  type (
    55  	Ping struct {
    56  		module.Base
    57  		Config `yaml:",inline"`
    58  
    59  		charts *module.Charts
    60  
    61  		hosts map[string]bool
    62  
    63  		newProber func(pingProberConfig, *logger.Logger) prober
    64  		prober    prober
    65  	}
    66  	prober interface {
    67  		ping(host string) (*probing.Statistics, error)
    68  	}
    69  )
    70  
    71  func (p *Ping) Init() bool {
    72  	err := p.validateConfig()
    73  	if err != nil {
    74  		p.Errorf("config validation: %v", err)
    75  		return false
    76  	}
    77  
    78  	pr, err := p.initProber()
    79  	if err != nil {
    80  		p.Errorf("init prober: %v", err)
    81  		return false
    82  	}
    83  	p.prober = pr
    84  
    85  	return true
    86  }
    87  
    88  func (p *Ping) Check() bool {
    89  	return len(p.Collect()) > 0
    90  }
    91  
    92  func (p *Ping) Charts() *module.Charts {
    93  	return p.charts
    94  }
    95  
    96  func (p *Ping) Collect() map[string]int64 {
    97  	mx, err := p.collect()
    98  	if err != nil {
    99  		p.Error(err)
   100  	}
   101  
   102  	if len(mx) == 0 {
   103  		return nil
   104  	}
   105  	return mx
   106  }
   107  
   108  func (p *Ping) Cleanup() {}