master
go 119 lines 2.34 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package pihole
4
5 import (
6 "context"
7 _ "embed"
8 "errors"
9 "fmt"
10 "net/http"
11 "time"
12
13 "github.com/netdata/netdata/go/plugins/pkg/confopt"
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("pihole", collectorapi.Creator{
23 JobConfigSchema: configSchema,
24 Defaults: collectorapi.Defaults{
25 UpdateEvery: 1,
26 },
27 Create: func() collectorapi.CollectorV1 { return New() },
28 Config: func() any { return &Config{} },
29 })
30 }
31
32 func New() *Collector {
33 return &Collector{
34 Config: Config{
35 HTTPConfig: web.HTTPConfig{
36 RequestConfig: web.RequestConfig{
37 URL: "http://127.0.0.1",
38 Password: "",
39 },
40 ClientConfig: web.ClientConfig{
41 Timeout: confopt.Duration(time.Second * 1),
42 },
43 },
44 },
45 charts: summaryCharts.Copy(),
46 }
47 }
48
49 type Config struct {
50 Vnode string `yaml:"vnode,omitempty" json:"vnode"`
51 UpdateEvery int `yaml:"update_every,omitempty" json:"update_every"`
52 AutoDetectionRetry int `yaml:"autodetection_retry,omitempty" json:"autodetection_retry"`
53 web.HTTPConfig `yaml:",inline" json:""`
54 }
55
56 type Collector struct {
57 collectorapi.Base
58 Config `yaml:",inline" json:""`
59
60 charts *collectorapi.Charts
61
62 httpClient *http.Client
63 auth *ftlAPIAuthResponse
64 }
65
66 func (c *Collector) Configuration() any {
67 return c.Config
68 }
69
70 func (c *Collector) Init(context.Context) error {
71 if c.URL == "" {
72 return errors.New("url not set")
73 }
74 if c.Password == "" {
75 return errors.New("password not set")
76 }
77
78 httpClient, err := web.NewHTTPClient(c.ClientConfig)
79 if err != nil {
80 return fmt.Errorf("init http client: %v", err)
81 }
82 c.httpClient = httpClient
83
84 return nil
85 }
86
87 func (c *Collector) Check(context.Context) error {
88 mx, err := c.collect()
89 if err != nil {
90 return err
91 }
92 if len(mx) == 0 {
93 return errors.New("no metrics collected")
94 }
95 return nil
96 }
97
98 func (c *Collector) Charts() *collectorapi.Charts {
99 return c.charts
100 }
101
102 func (c *Collector) Collect(context.Context) map[string]int64 {
103 mx, err := c.collect()
104 if err != nil {
105 c.Error(err)
106 }
107
108 if len(mx) == 0 {
109 return nil
110 }
111
112 return mx
113 }
114
115 func (c *Collector) Cleanup(context.Context) {
116 if c.httpClient != nil {
117 c.httpClient.CloseIdleConnections()
118 }
119 }