master
go 106 lines 2.03 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package wireguard
4
5 import (
6 "context"
7 _ "embed"
8 "errors"
9 "time"
10
11 "github.com/netdata/netdata/go/plugins/plugin/framework/collectorapi"
12
13 "golang.zx2c4.com/wireguard/wgctrl"
14 "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
15 )
16
17 //go:embed "config_schema.json"
18 var configSchema string
19
20 func init() {
21 collectorapi.Register("wireguard", collectorapi.Creator{
22 JobConfigSchema: configSchema,
23 Create: func() collectorapi.CollectorV1 { return New() },
24 Config: func() any { return &Config{} },
25 })
26 }
27
28 func New() *Collector {
29 return &Collector{
30 newWGClient: func() (wgClient, error) { return wgctrl.New() },
31 charts: &collectorapi.Charts{},
32 devices: make(map[string]bool),
33 peers: make(map[string]bool),
34 cleanupEvery: time.Minute,
35 }
36 }
37
38 type Config struct {
39 UpdateEvery int `yaml:"update_every,omitempty" json:"update_every"`
40 }
41
42 type (
43 Collector struct {
44 collectorapi.Base
45 Config `yaml:",inline" json:""`
46
47 charts *collectorapi.Charts
48
49 client wgClient
50 newWGClient func() (wgClient, error)
51
52 cleanupLastTime time.Time
53 cleanupEvery time.Duration
54 devices map[string]bool
55 peers map[string]bool
56 }
57 wgClient interface {
58 Devices() ([]*wgtypes.Device, error)
59 Close() error
60 }
61 )
62
63 func (c *Collector) Configuration() any {
64 return c.Config
65 }
66
67 func (c *Collector) Init(context.Context) error {
68 return nil
69 }
70
71 func (c *Collector) Check(context.Context) error {
72 mx, err := c.collect()
73 if err != nil {
74 return err
75 }
76 if len(mx) == 0 {
77 return errors.New("no metrics collected")
78 }
79 return nil
80 }
81
82 func (c *Collector) Charts() *collectorapi.Charts {
83 return c.charts
84 }
85
86 func (c *Collector) Collect(context.Context) map[string]int64 {
87 mx, err := c.collect()
88 if err != nil {
89 c.Error(err)
90 }
91
92 if len(mx) == 0 {
93 return nil
94 }
95 return mx
96 }
97
98 func (c *Collector) Cleanup(context.Context) {
99 if c.client == nil {
100 return
101 }
102 if err := c.client.Close(); err != nil {
103 c.Warningf("cleanup: error on closing connection: %v", err)
104 }
105 c.client = nil
106 }