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

package httpcheck

import (
	"errors"
	"fmt"
	"net/http"
	"regexp"

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

type headerMatch struct {
	exclude    bool
	key        string
	valMatcher matcher.Matcher
}

func (hc *HTTPCheck) validateConfig() error {
	if hc.URL == "" {
		return errors.New("'url' not set")
	}
	return nil
}

func (hc *HTTPCheck) initHTTPClient() (*http.Client, error) {
	return web.NewHTTPClient(hc.Client)
}

func (hc *HTTPCheck) initResponseMatchRegexp() (*regexp.Regexp, error) {
	if hc.ResponseMatch == "" {
		return nil, nil
	}
	return regexp.Compile(hc.ResponseMatch)
}

func (hc *HTTPCheck) initHeaderMatch() ([]headerMatch, error) {
	if len(hc.HeaderMatch) == 0 {
		return nil, nil
	}

	var hms []headerMatch

	for _, v := range hc.HeaderMatch {
		if v.Key == "" {
			continue
		}

		hm := headerMatch{
			exclude:    v.Exclude,
			key:        v.Key,
			valMatcher: nil,
		}

		if v.Value != "" {
			m, err := matcher.Parse(v.Value)
			if err != nil {
				return nil, fmt.Errorf("parse key '%s value '%s': %v", v.Key, v.Value, err)
			}
			if v.Exclude {
				m = matcher.Not(m)
			}
			hm.valMatcher = m
		}

		hms = append(hms, hm)
	}

	return hms, nil
}

func (hc *HTTPCheck) initCharts() *module.Charts {
	charts := httpCheckCharts.Copy()

	for _, chart := range *charts {
		chart.Labels = []module.Label{
			{Key: "url", Value: hc.URL},
		}
	}

	return charts
}