master
go 130 lines 2.66 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package ipfs
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("ipfs", 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:5001",
35 Method: http.MethodPost,
36 },
37 ClientConfig: web.ClientConfig{
38 Timeout: confopt.Duration(time.Second * 1),
39 },
40 },
41 QueryRepoApi: false,
42 QueryPinApi: false,
43 },
44 charts: charts.Copy(),
45 }
46 }
47
48 type Config struct {
49 Vnode string `yaml:"vnode,omitempty" json:"vnode"`
50 UpdateEvery int `yaml:"update_every,omitempty" json:"update_every"`
51 AutoDetectionRetry int `yaml:"autodetection_retry,omitempty" json:"autodetection_retry"`
52 web.HTTPConfig `yaml:",inline" json:""`
53 QueryPinApi bool `yaml:"pinapi" json:"pinapi"`
54 QueryRepoApi bool `yaml:"repoapi" json:"repoapi"`
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
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
75 client, err := web.NewHTTPClient(c.ClientConfig)
76 if err != nil {
77 return fmt.Errorf("http client init: %w", err)
78 }
79 c.httpClient = client
80
81 if !c.QueryPinApi {
82 _ = c.Charts().Remove(repoPinnedObjChart.ID)
83 }
84 if !c.QueryRepoApi {
85 _ = c.Charts().Remove(datastoreUtilizationChart.ID)
86 _ = c.Charts().Remove(repoSizeChart.ID)
87 _ = c.Charts().Remove(repoObjChart.ID)
88 }
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
102 if len(mx) == 0 {
103 return errors.New("no metrics collected")
104 }
105
106 return nil
107 }
108
109 func (c *Collector) Charts() *collectorapi.Charts {
110 return c.charts
111 }
112
113 func (c *Collector) Collect(context.Context) map[string]int64 {
114 mx, err := c.collect()
115 if err != nil {
116 c.Error(err)
117 }
118
119 if len(mx) == 0 {
120 return nil
121 }
122
123 return mx
124 }
125
126 func (c *Collector) Cleanup(context.Context) {
127 if c.httpClient != nil {
128 c.httpClient.CloseIdleConnections()
129 }
130 }