-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstats.go
More file actions
65 lines (59 loc) · 2.14 KB
/
Copy pathstats.go
File metadata and controls
65 lines (59 loc) · 2.14 KB
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
package cinc
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
// StatMetric is one measured value within a Stat, optionally carrying
// Prometheus-style labels.
type StatMetric struct {
Value string `json:"value"`
Labels map[string]string `json:"labels,omitempty"`
}
// Stat is one metric family reported by the /_stats endpoint.
type Stat struct {
Name string `json:"name"`
Type string `json:"type"`
Help string `json:"help"`
Metrics []StatMetric `json:"metrics"`
}
// StatsService accesses the top-level /_stats endpoint, which reports
// connection-pool, PostgreSQL, and Erlang VM statistics.
//
// Unlike every other endpoint, /_stats authenticates with HTTP Basic auth
// (default user "statsuser") rather than the Chef signing protocol, so its
// requests are NOT Chef-signed.
type StatsService struct{ client *Client }
// Get fetches the server statistics as JSON, authenticating with the given
// Basic-auth credentials (the stats user and its password, available from
// `chef-server-ctl show-service-credentials`).
func (s *StatsService) Get(ctx context.Context, user, password string) ([]Stat, *Response, error) {
u := s.client.baseURLStr + "/_stats?format=json"
req, err := http.NewRequestWithContext(ctx, "GET", u, nil)
if err != nil {
return nil, nil, fmt.Errorf("cinc: build stats request: %w", err)
}
req.SetBasicAuth(user, password)
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", s.client.opts.userAgent)
httpResp, err := s.client.httpClient.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("cinc: GET /_stats: %w", err)
}
defer httpResp.Body.Close()
data, err := io.ReadAll(httpResp.Body)
if err != nil {
return nil, nil, fmt.Errorf("cinc: read body: %w", err)
}
resp := &Response{HTTPResponse: httpResp, StatusCode: httpResp.StatusCode}
if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 {
return nil, resp, newErrorResponse("GET", "/_stats", httpResp.StatusCode, data)
}
var stats []Stat
if err := json.Unmarshal(data, &stats); err != nil {
return nil, resp, fmt.Errorf("cinc: decode response: %w", err)
}
return stats, resp, nil
}