| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package nginxunit |
| 4 | |
| 5 | import ( |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "net/http" |
| 10 | |
| 11 | "github.com/netdata/netdata/go/plugins/pkg/stm" |
| 12 | "github.com/netdata/netdata/go/plugins/pkg/web" |
| 13 | ) |
| 14 | |
| 15 | const ( |
| 16 | urlPathStatus = "/status" |
| 17 | ) |
| 18 | |
| 19 | // https://unit.nginx.org/statusapi/ |
| 20 | type nuStatus struct { |
| 21 | Connections *struct { |
| 22 | Accepted int64 `json:"accepted" stm:"accepted"` |
| 23 | Active int64 `json:"active" stm:"active"` |
| 24 | Idle int64 `json:"idle" stm:"idle"` |
| 25 | Closed int64 `json:"closed" stm:"closed"` |
| 26 | } `json:"connections" stm:"connections"` |
| 27 | Requests struct { |
| 28 | Total int64 `json:"total" stm:"total"` |
| 29 | } `json:"requests" stm:"requests"` |
| 30 | } |
| 31 | |
| 32 | func (c *Collector) collect() (map[string]int64, error) { |
| 33 | req, err := web.NewHTTPRequestWithPath(c.RequestConfig, urlPathStatus) |
| 34 | if err != nil { |
| 35 | return nil, fmt.Errorf("failed to create HTTP request to '%s': %v", c.URL, err) |
| 36 | } |
| 37 | |
| 38 | var status nuStatus |
| 39 | |
| 40 | wc := web.DoHTTP(c.httpClient).OnNokCode(func(resp *http.Response) (bool, error) { |
| 41 | var msg struct { |
| 42 | Error string `json:"error"` |
| 43 | } |
| 44 | if json.NewDecoder(resp.Body).Decode(&msg) == nil && msg.Error != "" { |
| 45 | return false, errors.New(msg.Error) |
| 46 | } |
| 47 | return false, nil |
| 48 | }) |
| 49 | |
| 50 | if err := wc.RequestJSON(req, &status); err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | |
| 54 | if status.Connections == nil { |
| 55 | return nil, errors.New("unexpected response: no connections available") |
| 56 | } |
| 57 | |
| 58 | return stm.ToMap(status), nil |
| 59 | } |