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