summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/pihole/collect.go
blob: ab0e48ff055f2580fa09576f37cd43aa6ab1b934 (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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// SPDX-License-Identifier: GPL-3.0-or-later

package pihole

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"sync"
	"time"

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

const wantAPIVersion = 3

const (
	urlPathAPI                        = "/admin/api.php"
	urlQueryKeyAuth                   = "auth"
	urlQueryKeyAPIVersion             = "version"
	urlQueryKeySummaryRaw             = "summaryRaw"
	urlQueryKeyGetQueryTypes          = "getQueryTypes"          // need auth
	urlQueryKeyGetForwardDestinations = "getForwardDestinations" // need auth
)

const (
	precision = 1000
)

func (p *Pihole) collect() (map[string]int64, error) {
	if p.checkVersion {
		ver, err := p.queryAPIVersion()
		if err != nil {
			return nil, err
		}
		if ver != wantAPIVersion {
			return nil, fmt.Errorf("API version: %d, supported version: %d", ver, wantAPIVersion)
		}
		p.checkVersion = false
	}

	pmx := new(piholeMetrics)
	p.queryMetrics(pmx, true)

	if pmx.hasQueryTypes() {
		p.addQueriesTypesOnce.Do(p.addChartDNSQueriesType)
	}
	if pmx.hasForwarders() {
		p.addFwsDestinationsOnce.Do(p.addChartDNSQueriesForwardedDestinations)
	}

	mx := make(map[string]int64)
	p.collectMetrics(mx, pmx)

	return mx, nil
}

func (p *Pihole) collectMetrics(mx map[string]int64, pmx *piholeMetrics) {
	if pmx.hasSummary() {
		mx["ads_blocked_today"] = pmx.summary.AdsBlockedToday
		mx["ads_percentage_today"] = int64(pmx.summary.AdsPercentageToday * 100)
		mx["domains_being_blocked"] = pmx.summary.DomainsBeingBlocked
		// GravityLastUpdated.Absolute is <nil> if the file does not exist (deleted/moved)
		if pmx.summary.GravityLastUpdated.Absolute != nil {
			mx["blocklist_last_update"] = time.Now().Unix() - *pmx.summary.GravityLastUpdated.Absolute
		}
		mx["dns_queries_today"] = pmx.summary.DNSQueriesToday
		mx["queries_forwarded"] = pmx.summary.QueriesForwarded
		mx["queries_cached"] = pmx.summary.QueriesCached
		mx["unique_clients"] = pmx.summary.UniqueClients
		mx["blocking_status_enabled"] = boolToInt(pmx.summary.Status == "enabled")
		mx["blocking_status_disabled"] = boolToInt(pmx.summary.Status != "enabled")

		tot := pmx.summary.QueriesCached + pmx.summary.AdsBlockedToday + pmx.summary.QueriesForwarded
		mx["queries_cached_perc"] = calcPercentage(pmx.summary.QueriesCached, tot)
		mx["ads_blocked_today_perc"] = calcPercentage(pmx.summary.AdsBlockedToday, tot)
		mx["queries_forwarded_perc"] = calcPercentage(pmx.summary.QueriesForwarded, tot)
	}

	if pmx.hasQueryTypes() {
		mx["A"] = int64(pmx.queryTypes.Types.A * 100)
		mx["AAAA"] = int64(pmx.queryTypes.Types.AAAA * 100)
		mx["ANY"] = int64(pmx.queryTypes.Types.ANY * 100)
		mx["PTR"] = int64(pmx.queryTypes.Types.PTR * 100)
		mx["SOA"] = int64(pmx.queryTypes.Types.SOA * 100)
		mx["SRV"] = int64(pmx.queryTypes.Types.SRV * 100)
		mx["TXT"] = int64(pmx.queryTypes.Types.TXT * 100)
	}

	if pmx.hasForwarders() {
		for k, v := range pmx.forwarders.Destinations {
			name := strings.Split(k, "|")[0]
			mx["destination_"+name] = int64(v * 100)
		}
	}
}

func (p *Pihole) queryMetrics(pmx *piholeMetrics, doConcurrently bool) {
	type task func(*piholeMetrics)

	var tasks = []task{p.querySummary}

	if p.Password != "" {
		tasks = []task{
			p.querySummary,
			p.queryQueryTypes,
			p.queryForwardedDestinations,
		}
	}

	wg := &sync.WaitGroup{}

	wrap := func(call task) task {
		return func(metrics *piholeMetrics) { call(metrics); wg.Done() }
	}

	for _, task := range tasks {
		if doConcurrently {
			wg.Add(1)
			task = wrap(task)
			go task(pmx)
		} else {
			task(pmx)
		}
	}

	wg.Wait()
}

func (p *Pihole) querySummary(pmx *piholeMetrics) {
	req, err := web.NewHTTPRequest(p.Request)
	if err != nil {
		p.Error(err)
		return
	}

	req.URL.Path = urlPathAPI
	req.URL.RawQuery = url.Values{
		urlQueryKeyAuth:       []string{p.Password},
		urlQueryKeySummaryRaw: []string{"true"},
	}.Encode()

	var v summaryRawMetrics
	if err = p.doWithDecode(&v, req); err != nil {
		p.Error(err)
		return
	}

	pmx.summary = &v
}

func (p *Pihole) queryQueryTypes(pmx *piholeMetrics) {
	req, err := web.NewHTTPRequest(p.Request)
	if err != nil {
		p.Error(err)
		return
	}

	req.URL.Path = urlPathAPI
	req.URL.RawQuery = url.Values{
		urlQueryKeyAuth:          []string{p.Password},
		urlQueryKeyGetQueryTypes: []string{"true"},
	}.Encode()

	var v queryTypesMetrics
	err = p.doWithDecode(&v, req)
	if err != nil {
		p.Error(err)
		return
	}

	pmx.queryTypes = &v
}

func (p *Pihole) queryForwardedDestinations(pmx *piholeMetrics) {
	req, err := web.NewHTTPRequest(p.Request)
	if err != nil {
		p.Error(err)
		return
	}

	req.URL.Path = urlPathAPI
	req.URL.RawQuery = url.Values{
		urlQueryKeyAuth:                   []string{p.Password},
		urlQueryKeyGetForwardDestinations: []string{"true"},
	}.Encode()

	var v forwardDestinations
	err = p.doWithDecode(&v, req)
	if err != nil {
		p.Error(err)
		return
	}

	pmx.forwarders = &v
}

func (p *Pihole) queryAPIVersion() (int, error) {
	req, err := web.NewHTTPRequest(p.Request)
	if err != nil {
		return 0, err
	}

	req.URL.Path = urlPathAPI
	req.URL.RawQuery = url.Values{
		urlQueryKeyAuth:       []string{p.Password},
		urlQueryKeyAPIVersion: []string{"true"},
	}.Encode()

	var v piholeAPIVersion
	err = p.doWithDecode(&v, req)
	if err != nil {
		return 0, err
	}

	return v.Version, nil
}

func (p *Pihole) doWithDecode(dst interface{}, req *http.Request) error {
	resp, err := p.httpClient.Do(req)
	if err != nil {
		return err
	}
	defer closeBody(resp)

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

	content, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("error on reading response from %s : %v", req.URL, err)
	}

	// empty array if unauthorized query or wrong query
	if isEmptyArray(content) {
		return fmt.Errorf("unauthorized access to %s", req.URL)
	}

	if err := json.Unmarshal(content, dst); err != nil {
		return fmt.Errorf("error on parsing response from %s : %v", req.URL, err)
	}

	return nil
}

func isEmptyArray(data []byte) bool {
	empty := "[]"
	return len(data) == len(empty) && string(data) == empty
}

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

func boolToInt(b bool) int64 {
	if !b {
		return 0
	}
	return 1
}

func calcPercentage(value, total int64) (v int64) {
	if total == 0 {
		return 0
	}
	return int64(float64(value) * 100 / float64(total) * precision)
}