master
go 128 lines 2.58 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package nats
4
5 import (
6 "context"
7 _ "embed"
8 "errors"
9 "fmt"
10 "net/http"
11 "sync"
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("nats", collectorapi.Creator{
24 Create: func() collectorapi.CollectorV1 { return New() },
25 JobConfigSchema: configSchema,
26 Config: func() any { return &Config{} },
27 })
28 }
29
30 func New() *Collector {
31 return &Collector{
32 Config: Config{
33 HTTPConfig: web.HTTPConfig{
34 RequestConfig: web.RequestConfig{
35 URL: "http://127.0.0.1:8222",
36 },
37 ClientConfig: web.ClientConfig{
38 Timeout: confopt.Duration(time.Second),
39 },
40 },
41 HealthzCheck: "default",
42 },
43 charts: &collectorapi.Charts{},
44 cache: newCache(),
45 onceAddSrvCharts: &sync.Once{},
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 HealthzCheck string `yaml:"healthz_check,omitempty" json:"healthz_check"`
54 web.HTTPConfig `yaml:",inline" json:""`
55 }
56
57 type Collector struct {
58 collectorapi.Base
59 Config `yaml:",inline" json:""`
60
61 charts *collectorapi.Charts
62
63 httpClient *http.Client
64
65 cache *cache
66
67 srvMeta struct {
68 id string
69 name string
70 clusterName string
71 }
72 onceAddSrvCharts *sync.Once
73 }
74
75 func (c *Collector) Configuration() any {
76 return c.Config
77 }
78
79 func (c *Collector) Init(context.Context) error {
80 if c.URL == "" {
81 return errors.New("URL required but not set")
82 }
83
84 httpClient, err := web.NewHTTPClient(c.ClientConfig)
85 if err != nil {
86 return fmt.Errorf("init HTTP client: %v", err)
87 }
88 c.httpClient = httpClient
89
90 c.Debugf("using URL %s", c.URL)
91 c.Debugf("using timeout: %s", c.Timeout)
92
93 return nil
94 }
95
96 func (c *Collector) Check(context.Context) error {
97 mx, err := c.collect()
98 if err != nil {
99 return err
100 }
101 if len(mx) == 0 {
102 return errors.New("no metrics collected")
103
104 }
105 return nil
106 }
107
108 func (c *Collector) Charts() *collectorapi.Charts {
109 return c.charts
110 }
111
112 func (c *Collector) Collect(context.Context) map[string]int64 {
113 mx, err := c.collect()
114 if err != nil {
115 c.Error(err)
116 }
117
118 if len(mx) == 0 {
119 return nil
120 }
121 return mx
122 }
123
124 func (c *Collector) Cleanup(context.Context) {
125 if c.httpClient != nil {
126 c.httpClient.CloseIdleConnections()
127 }
128 }