master
go 122 lines 2.49 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package portcheck
4
5 import (
6 "context"
7 _ "embed"
8 "errors"
9 "fmt"
10 "net"
11 "time"
12
13 "github.com/netdata/netdata/go/plugins/pkg/confopt"
14 "github.com/netdata/netdata/go/plugins/plugin/framework/collectorapi"
15 )
16
17 //go:embed "config_schema.json"
18 var configSchema string
19
20 func init() {
21 collectorapi.Register("portcheck", collectorapi.Creator{
22 JobConfigSchema: configSchema,
23 Defaults: collectorapi.Defaults{
24 UpdateEvery: 5,
25 },
26 Create: func() collectorapi.CollectorV1 { return New() },
27 Config: func() any { return &Config{} },
28 })
29 }
30
31 func New() *Collector {
32 return &Collector{
33 Config: Config{
34 Timeout: confopt.Duration(time.Second * 2),
35 },
36 charts: &collectorapi.Charts{},
37
38 dialTCP: net.DialTimeout,
39
40 scanUDP: scanUDPPort,
41 doUdpPorts: true,
42
43 seenUdpPorts: make(map[int]bool),
44 seenTcpPorts: make(map[int]bool),
45 }
46 }
47
48 type Config struct {
49 Vnode string `yaml:"vnode,omitempty" json:"vnode"`
50 UpdateEvery int `yaml:"update_every,omitempty" json:"update_every"`
51 Host string `yaml:"host" json:"host"`
52 Ports []int `yaml:"ports" json:"ports"`
53 UDPPorts []int `yaml:"udp_ports,omitempty" json:"udp_ports"`
54 Timeout confopt.Duration `yaml:"timeout,omitempty" json:"timeout"`
55 }
56
57 type Collector struct {
58 collectorapi.Base
59 Config `yaml:",inline" json:""`
60
61 charts *collectorapi.Charts
62
63 dialTCP dialTCPFunc
64 scanUDP func(address string, timeout time.Duration) (bool, error)
65
66 tcpPorts []*tcpPort
67 seenTcpPorts map[int]bool
68
69 udpPorts []*udpPort
70 seenUdpPorts map[int]bool
71 doUdpPorts bool
72 }
73
74 func (c *Collector) Configuration() any {
75 return c.Config
76 }
77
78 func (c *Collector) Init(context.Context) error {
79 if err := c.validateConfig(); err != nil {
80 return fmt.Errorf("config validation: %v", err)
81 }
82
83 c.tcpPorts, c.udpPorts = c.initPorts()
84
85 c.Debugf("using host: %s", c.Host)
86 c.Debugf("using ports: tcp %v udp %v", c.Ports, c.UDPPorts)
87 c.Debugf("using connection timeout: %s", c.Timeout)
88
89 return nil
90 }
91
92 func (c *Collector) Check(context.Context) error {
93 mx, err := c.collect()
94 if err != nil {
95 return err
96 }
97
98 if len(mx) == 0 {
99 return errors.New("no metrics collected")
100 }
101
102 return nil
103 }
104
105 func (c *Collector) Charts() *collectorapi.Charts {
106 return c.charts
107 }
108
109 func (c *Collector) Collect(context.Context) map[string]int64 {
110 mx, err := c.collect()
111 if err != nil {
112 c.Error(err)
113 }
114
115 if len(mx) == 0 {
116 return nil
117 }
118
119 return mx
120 }
121
122 func (c *Collector) Cleanup(context.Context) {}