github.com/netdata/go.d.plugin@v0.58.1/modules/portcheck/portcheck.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package portcheck 4 5 import ( 6 _ "embed" 7 "net" 8 "time" 9 10 "github.com/netdata/go.d.plugin/agent/module" 11 "github.com/netdata/go.d.plugin/pkg/web" 12 ) 13 14 //go:embed "config_schema.json" 15 var configSchema string 16 17 func init() { 18 module.Register("portcheck", module.Creator{ 19 JobConfigSchema: configSchema, 20 Defaults: module.Defaults{ 21 UpdateEvery: 5, 22 }, 23 Create: func() module.Module { return New() }, 24 }) 25 } 26 27 func New() *PortCheck { 28 return &PortCheck{ 29 Config: Config{ 30 Timeout: web.Duration{Duration: time.Second * 2}, 31 }, 32 dial: net.DialTimeout, 33 } 34 } 35 36 type Config struct { 37 Host string `yaml:"host"` 38 Ports []int `yaml:"ports"` 39 Timeout web.Duration `yaml:"timeout"` 40 } 41 42 type dialFunc func(network, address string, timeout time.Duration) (net.Conn, error) 43 44 type port struct { 45 number int 46 state checkState 47 inState int 48 latency int 49 } 50 51 type PortCheck struct { 52 module.Base 53 Config `yaml:",inline"` 54 UpdateEvery int `yaml:"update_every"` 55 56 charts *module.Charts 57 dial dialFunc 58 ports []*port 59 } 60 61 func (pc *PortCheck) Init() bool { 62 if err := pc.validateConfig(); err != nil { 63 pc.Errorf("config validation: %v", err) 64 return false 65 } 66 67 charts, err := pc.initCharts() 68 if err != nil { 69 pc.Errorf("init charts: %v", err) 70 return false 71 } 72 pc.charts = charts 73 74 for _, p := range pc.Ports { 75 pc.ports = append(pc.ports, &port{number: p}) 76 } 77 78 pc.Debugf("using host: %s", pc.Host) 79 pc.Debugf("using ports: %v", pc.Ports) 80 pc.Debugf("using TCP connection timeout: %s", pc.Timeout) 81 82 return true 83 } 84 85 func (pc *PortCheck) Check() bool { 86 return true 87 } 88 89 func (pc *PortCheck) Charts() *module.Charts { 90 return pc.charts 91 } 92 93 func (pc *PortCheck) Collect() map[string]int64 { 94 mx, err := pc.collect() 95 if err != nil { 96 pc.Error(err) 97 } 98 99 if len(mx) == 0 { 100 return nil 101 } 102 return mx 103 } 104 105 func (pc *PortCheck) Cleanup() {}