-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_client.go
79 lines (65 loc) · 1.88 KB
/
api_client.go
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
package puppet
import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"github.com/prometheus/client_golang/prometheus"
"github.com/bonsai-oss/puppet-report-exporter/internal/metrics"
)
type ApiClient struct {
url *url.URL
}
type ApiClientOption func(client *ApiClient) error
// WithUrl - ApiClientOption set the URL of the PuppetDB API
func WithUrl(uri string) ApiClientOption {
return func(client *ApiClient) error {
parsedURL, parseError := url.Parse(uri)
if parseError != nil {
return parseError
}
client.url = parsedURL
return nil
}
}
func NewApiClient(options ...ApiClientOption) *ApiClient {
client := &ApiClient{}
for _, opt := range options {
if optionError := opt(client); optionError != nil {
log.Println(optionError)
}
}
return client
}
// GetNodes - Get all nodes from the PuppetDB API
func (client *ApiClient) GetNodes() ([]Node, error) {
var nodes []Node
go metrics.PuppetDBQueries.With(prometheus.Labels{metrics.LabelEndpoint: "nodes"}).Inc()
response, err := http.Get(client.url.JoinPath("pdb/query/v4/nodes").String())
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
return nil, fmt.Errorf("unexpected status code %d", response.StatusCode)
}
decodeError := json.NewDecoder(response.Body).Decode(&nodes)
if decodeError != nil {
return nil, decodeError
}
return nodes, err
}
func (client *ApiClient) GetReportHashInfo(hash string) ([]ReportLogEntry, error) {
go metrics.PuppetDBQueries.With(prometheus.Labels{metrics.LabelEndpoint: "reports"}).Inc()
response, reportFetchError := http.Get(client.url.JoinPath("pdb/query/v4/reports", hash, "logs").String())
if reportFetchError != nil {
return nil, reportFetchError
}
var report []ReportLogEntry
decodeError := json.NewDecoder(response.Body).Decode(&report)
if decodeError != nil {
return nil, decodeError
}
defer response.Body.Close()
return report, nil
}