| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package pihole |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "maps" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/netdata/netdata/go/plugins/pkg/stm" |
| 12 | "github.com/netdata/netdata/go/plugins/pkg/web" |
| 13 | ) |
| 14 | |
| 15 | const ( |
| 16 | precision = 1000 |
| 17 | ) |
| 18 | |
| 19 | func (c *Collector) collect() (map[string]int64, error) { |
| 20 | if err := c.checkAuthSession(); err != nil { |
| 21 | return nil, err |
| 22 | } |
| 23 | if c.auth == nil { |
| 24 | auth, err := c.getAuthSession() |
| 25 | if err != nil { |
| 26 | return nil, err |
| 27 | } |
| 28 | c.auth = auth |
| 29 | } |
| 30 | |
| 31 | mx := make(map[string]int64) |
| 32 | |
| 33 | if err := c.collectMetrics(mx); err != nil { |
| 34 | if web.IsStatusCode(err, 401) { |
| 35 | c.auth = nil |
| 36 | } |
| 37 | return nil, err |
| 38 | } |
| 39 | |
| 40 | return mx, nil |
| 41 | } |
| 42 | |
| 43 | func (c *Collector) collectMetrics(mx map[string]int64) error { |
| 44 | if c.auth == nil { |
| 45 | return errors.New("no auth session") |
| 46 | } |
| 47 | |
| 48 | req, err := web.NewHTTPRequestWithPath(c.RequestConfig, urlPathAPIStatsSummary) |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | req.Header.Set("X-FTL-SID", c.auth.Session.Sid) |
| 53 | req.Header.Set("X-FTL-CSRF", c.auth.Session.Csrf) |
| 54 | |
| 55 | var resp ftlAPIStatsSummaryResponse |
| 56 | |
| 57 | if err := web.DoHTTP(c.httpClient).RequestJSON(req, &resp); err != nil { |
| 58 | return err |
| 59 | } |
| 60 | |
| 61 | if resp.Took == nil { |
| 62 | return fmt.Errorf("unexpected response from %s", req.URL) |
| 63 | } |
| 64 | |
| 65 | maps.Copy(mx, stm.ToMap(resp)) |
| 66 | |
| 67 | // 0 if unknown |
| 68 | if resp.Gravity.LastUpdate != 0 { |
| 69 | mx["gravity_last_update_seconds_ago"] = int64(time.Since(time.Unix(resp.Gravity.LastUpdate, 0)).Seconds()) |
| 70 | } |
| 71 | |
| 72 | return nil |
| 73 | } |