summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/bind/bind.go
blob: 2eeda09ef4a9646455820763de36f0af35cb8be9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
// SPDX-License-Identifier: GPL-3.0-or-later

package bind

import (
	_ "embed"
	"errors"
	"net/http"
	"time"

	"github.com/netdata/netdata/go/go.d.plugin/pkg/matcher"
	"github.com/netdata/netdata/go/go.d.plugin/pkg/web"

	"github.com/netdata/netdata/go/go.d.plugin/agent/module"
)

//go:embed "config_schema.json"
var configSchema string

func init() {
	module.Register("bind", module.Creator{
		JobConfigSchema: configSchema,
		Create:          func() module.Module { return New() },
	})
}

func New() *Bind {
	return &Bind{
		Config: Config{
			HTTP: web.HTTP{
				Request: web.Request{
					URL: "http://127.0.0.1:8653/json/v1",
				},
				Client: web.Client{
					Timeout: web.Duration(time.Second),
				},
			},
		},
		charts: &Charts{},
	}
}

type Config struct {
	web.HTTP    `yaml:",inline" json:""`
	UpdateEvery int    `yaml:"update_every" json:"update_every"`
	PermitView  string `yaml:"permit_view" json:"permit_view"`
}

type (
	Bind struct {
		module.Base
		Config `yaml:",inline" json:""`

		charts *Charts

		httpClient *http.Client
		bindAPIClient

		permitView matcher.Matcher
	}

	bindAPIClient interface {
		serverStats() (*serverStats, error)
	}
)

func (b *Bind) Configuration() any {
	return b.Config
}

func (b *Bind) Init() error {
	if err := b.validateConfig(); err != nil {
		b.Errorf("config verification: %v", err)
		return err
	}

	pvm, err := b.initPermitViewMatcher()
	if err != nil {
		b.Error(err)
		return err
	}
	if pvm != nil {
		b.permitView = pvm
	}

	httpClient, err := web.NewHTTPClient(b.Client)
	if err != nil {
		b.Errorf("creating http client : %v", err)
		return err
	}
	b.httpClient = httpClient

	bindClient, err := b.initBindApiClient(httpClient)
	if err != nil {
		b.Error(err)
		return err
	}
	b.bindAPIClient = bindClient

	return nil
}

func (b *Bind) Check() error {
	mx, err := b.collect()
	if err != nil {
		b.Error(err)
		return err
	}
	if len(mx) == 0 {
		return errors.New("no metrics collected")

	}
	return nil
}

func (b *Bind) Charts() *Charts {
	return b.charts
}

func (b *Bind) Collect() map[string]int64 {
	mx, err := b.collect()

	if err != nil {
		b.Error(err)
		return nil
	}

	return mx
}

func (b *Bind) Cleanup() {
	if b.httpClient != nil {
		b.httpClient.CloseIdleConnections()
	}
}