-
Notifications
You must be signed in to change notification settings - Fork 11
/
api_client.go
executable file
·232 lines (196 loc) · 5.18 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
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
package mimir
// Largely copied from https://github.com/Mastercard/terraform-provider-restapi/blob/master/restapi/api_client.go
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
)
type apiClientOpt struct {
uri string
rulerURI string
alertmanagerURI string
distributorURI string
cert string
key string
ca string
token string
insecure bool
username string
password string
proxyURL string
headers map[string]string
timeout int
debug bool
}
type apiClient struct {
httpClient *http.Client
uri string
rulerURI string
alertmanagerURI string
distributorURI string
insecure bool
token string
username string
password string
headers map[string]string
debug bool
}
// Make a new api client for RESTful calls
func NewAPIClient(opt *apiClientOpt) (*apiClient, error) {
if opt.uri == "" && opt.rulerURI == "" && opt.alertmanagerURI == "" && opt.distributorURI == "" {
return nil, fmt.Errorf("no provider URIs defined. Please set uri, or ruler_uri/alertmanager_uri/distributor_uri")
}
/* Remove any trailing slashes since we will append
to this URL with our own root-prefixed location */
opt.uri = strings.TrimSuffix(opt.uri, "/")
// Setup HTTPS client
tlsConfig := &tls.Config{}
// Set insecure verify
if opt.insecure {
tlsConfig.InsecureSkipVerify = true
}
if opt.cert != "" && opt.key != "" {
var cert tls.Certificate
var err error
if strings.HasPrefix(opt.cert, "-----BEGIN") && strings.HasPrefix(opt.key, "-----BEGIN") {
cert, err = tls.X509KeyPair([]byte(opt.cert), []byte(opt.key))
} else {
cert, err = tls.LoadX509KeyPair(opt.cert, opt.key)
}
if err != nil {
return nil, err
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
if opt.ca != "" {
var caCert []byte
var err error
if strings.HasPrefix(opt.ca, "-----BEGIN") {
caCert = []byte(opt.ca)
} else {
caCert, err = os.ReadFile(opt.ca)
if err != nil {
return nil, err
}
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = caCertPool
}
tr := &http.Transport{
TLSClientConfig: tlsConfig,
Proxy: http.ProxyFromEnvironment,
}
if opt.proxyURL != "" {
log.Printf("api_client.go: Using proxy: %s\n", opt.proxyURL)
proxy, err := url.Parse(opt.proxyURL)
if err != nil {
return nil, fmt.Errorf("error parsing proxy url: %s", err)
}
tr.Proxy = http.ProxyURL(proxy)
}
client := apiClient{
httpClient: &http.Client{
Timeout: time.Second * time.Duration(opt.timeout),
Transport: tr,
},
uri: opt.uri,
rulerURI: opt.rulerURI,
alertmanagerURI: opt.alertmanagerURI,
distributorURI: opt.distributorURI,
insecure: opt.insecure,
token: opt.token,
username: opt.username,
password: opt.password,
headers: opt.headers,
debug: opt.debug,
}
return &client, nil
}
/*
Helper function that handles sending/receiving and handling
of HTTP data in and out.
*/
func (client *apiClient) sendRequest(component, method string, path, data string, headers map[string]string) (string, error) {
var fullURI string
switch {
case component == "ruler" && client.rulerURI != "":
fullURI = client.rulerURI + path
case component == "alertmanager" && client.alertmanagerURI != "":
fullURI = client.alertmanagerURI + path
case component == "distributor" && client.distributorURI != "":
fullURI = client.distributorURI + path
default:
fullURI = client.uri + path
}
var req *http.Request
var err error
buffer := bytes.NewBuffer([]byte(data))
if data == "" {
req, err = http.NewRequest(method, fullURI, nil)
} else {
req, err = http.NewRequest(method, fullURI, buffer)
}
if err != nil {
log.Fatal(err)
}
if client.token != "" {
req.Header.Set("Authorization", "Bearer "+client.token)
}
// Set client headers from provider
if len(client.headers) > 0 {
for n, v := range client.headers {
req.Header.Set(n, v)
}
}
// Set client headers from resource
if len(headers) > 0 {
for n, v := range headers {
req.Header.Set(n, v)
}
}
if client.username != "" && client.password != "" {
/* ... and fall back to basic auth if configured */
req.SetBasicAuth(client.username, client.password)
}
if client.debug {
reqDump, err := httputil.DumpRequestOut(req, true)
if err != nil {
log.Fatal(err)
}
log.Printf("REQUEST:\n%s", string(reqDump))
}
resp, err := client.httpClient.Do(req)
if err != nil {
if client.debug {
log.Printf("api_client.go: Error detected: %s\n", err)
}
return "", err
}
if client.debug {
respDump, err := httputil.DumpResponse(resp, true)
if err != nil {
log.Fatal(err)
}
log.Printf("RESPONSE:\n%s", string(respDump))
}
bodyBytes, err2 := io.ReadAll(resp.Body)
resp.Body.Close()
if err2 != nil {
return "", err2
}
body := string(bodyBytes)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return body, fmt.Errorf("unexpected response code '%d': %s", resp.StatusCode, body)
}
return body, nil
}