| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package httpcheck |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net/http" |
| 9 | "regexp" |
| 10 | |
| 11 | "github.com/netdata/netdata/go/plugins/pkg/matcher" |
| 12 | "github.com/netdata/netdata/go/plugins/pkg/web" |
| 13 | "github.com/netdata/netdata/go/plugins/plugin/framework/collectorapi" |
| 14 | ) |
| 15 | |
| 16 | type headerMatch struct { |
| 17 | exclude bool |
| 18 | key string |
| 19 | valMatcher matcher.Matcher |
| 20 | } |
| 21 | |
| 22 | func (c *Collector) validateConfig() error { |
| 23 | if c.URL == "" { |
| 24 | return errors.New("'url' not set") |
| 25 | } |
| 26 | return nil |
| 27 | } |
| 28 | |
| 29 | func (c *Collector) initHTTPClient() (*http.Client, error) { |
| 30 | return web.NewHTTPClient(c.ClientConfig) |
| 31 | } |
| 32 | |
| 33 | func (c *Collector) initResponseMatchRegexp() (*regexp.Regexp, error) { |
| 34 | if c.ResponseMatch == "" { |
| 35 | return nil, nil |
| 36 | } |
| 37 | return regexp.Compile(c.ResponseMatch) |
| 38 | } |
| 39 | |
| 40 | func (c *Collector) initHeaderMatch() ([]headerMatch, error) { |
| 41 | if len(c.HeaderMatch) == 0 { |
| 42 | return nil, nil |
| 43 | } |
| 44 | |
| 45 | var hms []headerMatch |
| 46 | |
| 47 | for _, v := range c.HeaderMatch { |
| 48 | if v.Key == "" { |
| 49 | continue |
| 50 | } |
| 51 | |
| 52 | hm := headerMatch{ |
| 53 | exclude: v.Exclude, |
| 54 | key: v.Key, |
| 55 | valMatcher: nil, |
| 56 | } |
| 57 | |
| 58 | if v.Value != "" { |
| 59 | m, err := matcher.Parse(v.Value) |
| 60 | if err != nil { |
| 61 | return nil, fmt.Errorf("parse key '%s value '%s': %v", v.Key, v.Value, err) |
| 62 | } |
| 63 | if v.Exclude { |
| 64 | m = matcher.Not(m) |
| 65 | } |
| 66 | hm.valMatcher = m |
| 67 | } |
| 68 | |
| 69 | hms = append(hms, hm) |
| 70 | } |
| 71 | |
| 72 | return hms, nil |
| 73 | } |
| 74 | |
| 75 | func (c *Collector) initCharts() *collectorapi.Charts { |
| 76 | charts := httpCheckCharts.Copy() |
| 77 | |
| 78 | for _, chart := range *charts { |
| 79 | chart.Labels = []collectorapi.Label{ |
| 80 | {Key: "url", Value: c.URL}, |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | return charts |
| 85 | } |