master
go 116 lines 2.35 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package haproxy
4
5 import (
6 "context"
7 _ "embed"
8 "errors"
9 "fmt"
10 "time"
11
12 "github.com/netdata/netdata/go/plugins/pkg/confopt"
13 "github.com/netdata/netdata/go/plugins/pkg/prometheus"
14 "github.com/netdata/netdata/go/plugins/pkg/web"
15 "github.com/netdata/netdata/go/plugins/plugin/framework/collectorapi"
16 )
17
18 //go:embed "config_schema.json"
19 var configSchema string
20
21 func init() {
22 collectorapi.Register("haproxy", collectorapi.Creator{
23 JobConfigSchema: configSchema,
24 Create: func() collectorapi.CollectorV1 { return New() },
25 Config: func() any { return &Config{} },
26 })
27 }
28
29 func New() *Collector {
30 return &Collector{
31 Config: Config{
32 HTTPConfig: web.HTTPConfig{
33 RequestConfig: web.RequestConfig{
34 URL: "http://127.0.0.1:8404/metrics",
35 },
36 ClientConfig: web.ClientConfig{
37 Timeout: confopt.Duration(time.Second),
38 },
39 },
40 },
41
42 charts: charts.Copy(),
43 proxies: make(map[string]bool),
44 validateMetrics: true,
45 }
46 }
47
48 type Config struct {
49 web.HTTPConfig `yaml:",inline" json:""`
50 UpdateEvery int `yaml:"update_every" json:"update_every"`
51 AutoDetectionRetry int `yaml:"autodetection_retry,omitempty" json:"autodetection_retry"`
52 }
53
54 type Collector struct {
55 collectorapi.Base
56 Config `yaml:",inline" json:""`
57
58 charts *collectorapi.Charts
59
60 prom prometheus.Prometheus
61
62 validateMetrics bool
63 proxies map[string]bool
64 }
65
66 func (c *Collector) Configuration() any {
67 return c.Config
68 }
69
70 func (c *Collector) Init(context.Context) error {
71 if err := c.validateConfig(); err != nil {
72 return fmt.Errorf("config validation: %v", err)
73 }
74
75 prom, err := c.initPrometheusClient()
76 if err != nil {
77 return fmt.Errorf("prometheus client initialization: %v", err)
78 }
79 c.prom = prom
80
81 return nil
82 }
83
84 func (c *Collector) Check(context.Context) error {
85 mx, err := c.collect()
86 if err != nil {
87 return err
88 }
89 if len(mx) == 0 {
90 return errors.New("no metrics collected")
91 }
92 return nil
93 }
94
95 func (c *Collector) Charts() *collectorapi.Charts {
96 return c.charts
97 }
98
99 func (c *Collector) Collect(context.Context) map[string]int64 {
100 mx, err := c.collect()
101 if err != nil {
102 c.Error(err)
103 return nil
104 }
105
106 if len(mx) == 0 {
107 return nil
108 }
109 return mx
110 }
111
112 func (c *Collector) Cleanup(context.Context) {
113 if c.prom != nil && c.prom.HTTPClient() != nil {
114 c.prom.HTTPClient().CloseIdleConnections()
115 }
116 }