-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
101 lines (83 loc) · 2.37 KB
/
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
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
config_util "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/storage/remote"
)
func initHTTPTransport(caFile string, keyFile, certFile string, insecure bool) (http.RoundTripper, error) {
tlsConfig := &tls.Config{MinVersion: tls.VersionTLS12}
var tr http.RoundTripper = &http.Transport{}
if insecure {
tlsConfig.InsecureSkipVerify = insecure
}
caCertPool := x509.NewCertPool()
if caFile != "" {
caCert, err := os.ReadFile(filepath.Clean(caFile))
if err != nil {
return tr, err
}
caCertPool.AppendCertsFromPEM(caCert)
}
if certFile != "" && keyFile != "" {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return tr, err
}
tlsConfig.RootCAs = caCertPool
tlsConfig.Certificates = []tls.Certificate{cert}
}
tr = &http.Transport{TLSClientConfig: tlsConfig}
return tr, nil
}
func initRemoteWriteClient(baseURL *url.URL, timeout time.Duration, roundTripper http.RoundTripper, username, password string, headers map[string]string) (*remote.Client, error) {
addressURL, err := url.Parse(baseURL.String())
if err != nil {
return nil, err
}
// build remote write client
writeClient, err := remote.NewWriteClient("remote-write", &remote.ClientConfig{
URL: &config_util.URL{URL: addressURL},
Timeout: model.Duration(timeout),
RetryOnRateLimit: true,
})
if err != nil {
return nil, err
}
// set custom tls config from httpConfigFilePath
// set custom headers to every request
client, ok := writeClient.(*remote.Client)
if !ok {
return nil, err
}
if username != "" && password != "" {
headers["Authorization"] = fmt.Sprintf("Basic %s", basicAuth(username, password))
}
client.Client.Transport = &setHeadersTransport{
RoundTripper: roundTripper,
headers: headers,
}
return client, nil
}
func basicAuth(username, password string) string {
auth := username + ":" + password
return base64.StdEncoding.EncodeToString([]byte(auth))
}
type setHeadersTransport struct {
http.RoundTripper
headers map[string]string
}
func (s *setHeadersTransport) RoundTrip(req *http.Request) (*http.Response, error) {
for key, value := range s.headers {
req.Header.Set(key, value)
}
return s.RoundTripper.RoundTrip(req)
}