master
go 128 lines 2.65 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package nginxplus
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("nginxplus", 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",
35 },
36 ClientConfig: web.ClientConfig{
37 Timeout: confopt.Duration(time.Second * 1),
38 },
39 },
40 },
41 charts: baseCharts.Copy(),
42 queryEndpointsEvery: time.Minute,
43 cache: newCache(),
44 }
45 }
46
47 type Config struct {
48 Vnode string `yaml:"vnode,omitempty" json:"vnode"`
49 UpdateEvery int `yaml:"update_every,omitempty" json:"update_every"`
50 AutoDetectionRetry int `yaml:"autodetection_retry,omitempty" json:"autodetection_retry"`
51 web.HTTPConfig `yaml:",inline" json:""`
52 }
53
54 type Collector struct {
55 collectorapi.Base
56 Config `yaml:",inline" json:""`
57
58 charts *collectorapi.Charts
59
60 httpClient *http.Client
61
62 apiVersion int64
63 endpoints struct {
64 nginx bool
65 connections bool
66 ssl bool
67 httpCaches bool
68 httpRequest bool
69 httpServerZones bool
70 httpLocationZones bool
71 httpUpstreams bool
72 streamServerZones bool
73 streamUpstreams bool
74 resolvers bool
75 }
76 queryEndpointsTime time.Time
77 queryEndpointsEvery time.Duration
78 cache *cache
79 }
80
81 func (c *Collector) Configuration() any {
82 return c.Config
83 }
84
85 func (c *Collector) Init(context.Context) error {
86 if c.URL == "" {
87 return errors.New("config: 'url' can not be empty'")
88 }
89
90 client, err := web.NewHTTPClient(c.ClientConfig)
91 if err != nil {
92 return fmt.Errorf("init HTTP client: %v", err)
93 }
94 c.httpClient = client
95
96 return nil
97 }
98
99 func (c *Collector) Check(context.Context) error {
100 mx, err := c.collect()
101 if err != nil {
102 return err
103 }
104 if len(mx) == 0 {
105 return errors.New("no metrics collected")
106 }
107 return nil
108 }
109
110 func (c *Collector) Charts() *collectorapi.Charts {
111 return c.charts
112 }
113
114 func (c *Collector) Collect(context.Context) map[string]int64 {
115 mx, err := c.collect()
116 if err != nil {
117 c.Error(err)
118 return nil
119 }
120
121 return mx
122 }
123
124 func (c *Collector) Cleanup(context.Context) {
125 if c.httpClient != nil {
126 c.httpClient.CloseIdleConnections()
127 }
128 }