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

package dnsdist

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"

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

const (
	urlPathJSONStat = "/jsonstat"
)

func (d *DNSdist) collect() (map[string]int64, error) {
	statistics, err := d.scrapeStatistics()
	if err != nil {
		return nil, err
	}

	collected := make(map[string]int64)
	d.collectStatistic(collected, statistics)

	return collected, nil
}

func (d *DNSdist) collectStatistic(collected map[string]int64, statistics *statisticMetrics) {
	for metric, value := range stm.ToMap(statistics) {
		collected[metric] = value
	}
}

func (d *DNSdist) scrapeStatistics() (*statisticMetrics, error) {
	req, _ := web.NewHTTPRequest(d.Request)
	req.URL.Path = urlPathJSONStat
	req.URL.RawQuery = url.Values{"command": []string{"stats"}}.Encode()

	var statistics statisticMetrics
	if err := d.doOKDecode(req, &statistics); err != nil {
		return nil, err
	}

	return &statistics, nil
}

func (d *DNSdist) doOKDecode(req *http.Request, in interface{}) error {
	resp, err := d.httpClient.Do(req)
	if err != nil {
		return fmt.Errorf("error on HTTP request '%s': %v", req.URL, err)
	}
	defer closeBody(resp)

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("'%s' returned HTTP status code: %d", req.URL, resp.StatusCode)
	}

	if err := json.NewDecoder(resp.Body).Decode(in); err != nil {
		return fmt.Errorf("error on decoding response from '%s': %v", req.URL, err)
	}

	return nil
}

func closeBody(resp *http.Response) {
	if resp != nil && resp.Body != nil {
		_, _ = io.Copy(io.Discard, resp.Body)
		_ = resp.Body.Close()
	}
}