master
go 116 lines 2.38 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package lighttpd
4
5 import (
6 "context"
7 _ "embed"
8 "errors"
9 "fmt"
10 "net/http"
11 "strings"
12 "time"
13
14 "github.com/netdata/netdata/go/plugins/pkg/confopt"
15 "github.com/netdata/netdata/go/plugins/pkg/web"
16 "github.com/netdata/netdata/go/plugins/plugin/framework/collectorapi"
17 )
18
19 //go:embed "config_schema.json"
20 var configSchema string
21
22 func init() {
23 collectorapi.Register("lighttpd", collectorapi.Creator{
24 JobConfigSchema: configSchema,
25 Create: func() collectorapi.CollectorV1 { return New() },
26 Config: func() any { return &Config{} },
27 })
28 }
29
30 func New() *Collector {
31 return &Collector{Config: Config{
32 HTTPConfig: web.HTTPConfig{
33 RequestConfig: web.RequestConfig{
34 URL: "http://127.0.0.1/server-status?auto",
35 },
36 ClientConfig: web.ClientConfig{
37 Timeout: confopt.Duration(time.Second * 2),
38 },
39 },
40 },
41 charts: charts.Copy(),
42 }
43 }
44
45 type Config struct {
46 Vnode string `yaml:"vnode,omitempty" json:"vnode"`
47 UpdateEvery int `yaml:"update_every,omitempty" json:"update_every"`
48 AutoDetectionRetry int `yaml:"autodetection_retry,omitempty" json:"autodetection_retry"`
49 web.HTTPConfig `yaml:",inline" json:""`
50 }
51
52 type Collector struct {
53 collectorapi.Base
54 Config `yaml:",inline" json:""`
55
56 charts *collectorapi.Charts
57
58 httpClient *http.Client
59 }
60
61 func (c *Collector) Configuration() any {
62 return c.Config
63 }
64
65 func (c *Collector) Init(context.Context) error {
66 if c.URL == "" {
67 return errors.New("URL is required but not set")
68 }
69 if !strings.HasSuffix(c.URL, "?auto") {
70 return fmt.Errorf("bad URL '%s', should ends in '?auto'", c.URL)
71 }
72
73 httpClient, err := web.NewHTTPClient(c.ClientConfig)
74 if err != nil {
75 return fmt.Errorf("failed to create http client: %v", err)
76 }
77 c.httpClient = httpClient
78
79 c.Debugf("using URL %s", c.URL)
80 c.Debugf("using timeout: %s", c.Timeout.Duration())
81
82 return nil
83 }
84
85 func (c *Collector) Check(context.Context) error {
86 mx, err := c.collect()
87 if err != nil {
88 return err
89 }
90
91 if len(mx) == 0 {
92 return errors.New("no metrics collected")
93 }
94
95 return nil
96 }
97
98 func (c *Collector) Charts() *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 return nil
107 }
108
109 return mx
110 }
111
112 func (c *Collector) Cleanup(context.Context) {
113 if c.httpClient != nil {
114 c.httpClient.CloseIdleConnections()
115 }
116 }