summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/prometheus/init.go
blob: f5cc8bca9fb5e9b00de82df5e98ed94749f23685 (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
// SPDX-License-Identifier: GPL-3.0-or-later

package prometheus

import (
	"errors"
	"fmt"
	"os"

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

func (p *Prometheus) validateConfig() error {
	if p.URL == "" {
		return errors.New("'url' can not be empty")
	}
	return nil
}

func (p *Prometheus) initPrometheusClient() (prometheus.Prometheus, error) {
	httpClient, err := web.NewHTTPClient(p.Client)
	if err != nil {
		return nil, fmt.Errorf("init HTTP client: %v", err)
	}

	req := p.Request.Copy()
	if p.BearerTokenFile != "" {
		token, err := os.ReadFile(p.BearerTokenFile)
		if err != nil {
			return nil, fmt.Errorf("bearer token file: %v", err)
		}
		req.Headers["Authorization"] = "Bearer " + string(token)
	}

	sr, err := p.Selector.Parse()
	if err != nil {
		return nil, fmt.Errorf("parsing selector: %v", err)
	}

	if sr != nil {
		return prometheus.NewWithSelector(httpClient, req, sr), nil
	}
	return prometheus.New(httpClient, req), nil
}

func (p *Prometheus) initFallbackTypeMatcher(expr []string) (matcher.Matcher, error) {
	if len(expr) == 0 {
		return nil, nil
	}

	m := matcher.FALSE()

	for _, pattern := range expr {
		v, err := matcher.NewGlobMatcher(pattern)
		if err != nil {
			return nil, fmt.Errorf("error on parsing pattern '%s': %v", pattern, err)
		}
		m = matcher.Or(m, v)
	}

	return m, nil
}