forked from bf2fc6cc711aee1a0c2a/kas-fleet-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
233 lines (202 loc) · 6.61 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
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
233
package observatorium
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"strings"
"time"
"github.com/golang/glog"
"github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/pkg/logger"
"github.com/bf2fc6cc711aee1a0c2a/kas-fleet-manager/pkg/metrics"
"github.com/pkg/errors"
pAPI "github.com/prometheus/client_golang/api"
pV1 "github.com/prometheus/client_golang/api/prometheus/v1"
pModel "github.com/prometheus/common/model"
)
type ClientConfiguration struct {
BaseURL string
Timeout time.Duration
AuthToken string
Cookie string
Debug bool
EnableMock bool
Insecure bool
AuthType string
}
type Client struct {
// Configuration
Config *ClientConfiguration
connection pV1.API
Service APIObservatoriumService
}
func NewObservatoriumClient(c *ObservabilityConfiguration) (client *Client, err error) {
// Create Observatorium client
observatoriumConfig := &Configuration{
Cookie: c.Cookie,
Timeout: c.Timeout,
Debug: c.Debug,
Insecure: c.Insecure,
AuthType: c.AuthType,
}
if c.AuthType == AuthTypeSso {
observatoriumConfig.BaseURL = c.RedHatSsoTokenRefresherUrl
} else {
observatoriumConfig.BaseURL = c.ObservatoriumGateway + "/api/metrics/v1/" + c.ObservatoriumTenant
observatoriumConfig.AuthToken = c.AuthToken
}
if c.EnableMock {
glog.Infof("Using Mock Observatorium Client")
client, err = NewClientMock(observatoriumConfig)
} else {
client, err = NewClient(observatoriumConfig)
}
if err != nil {
glog.Errorf("Unable to create Observatorium client: %s", err)
}
return
}
func NewClient(config *Configuration) (*Client, error) {
client := &Client{
Config: &ClientConfiguration{
Timeout: config.Timeout,
AuthToken: config.AuthToken,
Cookie: config.Cookie,
Debug: config.Debug,
EnableMock: false,
Insecure: config.Insecure,
AuthType: config.AuthType,
},
}
// Ensure baseURL has a trailing slash
baseURL := strings.TrimSuffix(config.BaseURL, "/")
client.Config.BaseURL = baseURL + "/"
client.Service = &ServiceObservatorium{client: client}
if config.Insecure {
pAPI.DefaultRoundTripper.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
}
apiClient, err := pAPI.NewClient(pAPI.Config{
Address: client.Config.BaseURL,
RoundTripper: observatoriumRoundTripper{
config: *client.Config,
wrapped: pAPI.DefaultRoundTripper,
},
})
if err != nil {
return nil, err
}
client.connection = pV1.NewAPI(apiClient)
client.Service = &ServiceObservatorium{client: client}
return client, nil
}
func NewClientMock(config *Configuration) (*Client, error) {
client := &Client{
Config: &ClientConfiguration{
Timeout: config.Timeout,
AuthToken: config.AuthToken,
Debug: false,
EnableMock: true,
Insecure: config.Insecure,
},
}
client.Service = &ServiceObservatorium{client: client}
client.connection = client.MockAPI()
return client, nil
}
type observatoriumRoundTripper struct {
config ClientConfiguration
wrapped http.RoundTripper
}
func (p observatoriumRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
var statusCode int
path := strings.TrimPrefix(request.URL.String(), p.config.BaseURL)
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
if p.config.AuthType == AuthTypeDex {
if p.config.AuthToken != "" {
request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", p.config.AuthToken))
} else if p.config.Cookie != "" {
request.Header.Add("Cookie", p.config.Cookie)
} else {
metrics.IncreaseObservatoriumRequestCount(statusCode, path, request.Method)
return nil, errors.Errorf("can't request metrics without auth")
}
}
start := time.Now()
resp, err := p.wrapped.RoundTrip(request)
elapsedTime := time.Since(start)
if resp != nil {
statusCode = resp.StatusCode
}
metrics.IncreaseObservatoriumRequestCount(statusCode, path, request.Method)
metrics.UpdateObservatoriumRequestDurationMetric(statusCode, path, request.Method, elapsedTime)
return resp, err
}
// Send a POST request to server.
func (c *Client) send(query string) (pModel.Value, pV1.Warnings, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.Config.Timeout)
defer cancel()
return c.connection.Query(ctx, query, time.Now())
}
// Send a POST request to server.
func (c *Client) sendRange(query string, bounds pV1.Range) (pModel.Value, pV1.Warnings, error) {
ctx, cancel := context.WithTimeout(context.Background(), c.Config.Timeout)
defer cancel()
return c.connection.QueryRange(ctx, query, bounds)
}
// Query sends a metrics request to server and returns unmashalled Vector response.
// The VectorResult(s) inside will contain either .Value for queries resulting in instant vector,
// or .Values for queries resulting in a range vector.
//
// queryTemplate must contain one %s for labels, e.g. `some_metric{%s}` or `count(some_metric{state="up",%s})`.
// (Undocumented PromQL: empty labels some_metric{} are OK - https://github.com/prometheus/prometheus/issues/3697)
// labels 0 or more constraints separated by comma e.g. `` or `foo="bar",quux="baz"`.
func (c *Client) Query(queryTemplate string, label string) Metric {
queryString := fmt.Sprintf(queryTemplate, label)
values, warnings, err := c.send(queryString)
if len(warnings) > 0 {
logger.Logger.Warningf("Prometheus client got warnings %s", all(warnings, "and"))
}
if err != nil {
return Metric{Err: err}
}
v, ok := values.(pModel.Vector)
if !ok {
logger.Logger.Errorf("Prometheus client got data of type %T, but expected model.Vector", values)
return Metric{Err: errors.Errorf("Prometheus client got data of type %T, but expected model.Vector", values)}
}
return Metric{Vector: v}
}
func (c *Client) QueryRange(queryTemplate string, label string, bounds pV1.Range) Metric {
queryString := fmt.Sprintf(queryTemplate, label)
values, warnings, err := c.sendRange(queryString, bounds)
if len(warnings) > 0 {
logger.Logger.Warningf("Prometheus client got warnings %s", all(warnings, "and"))
}
if err != nil {
return Metric{Err: err}
}
m, ok := values.(pModel.Matrix)
if !ok {
logger.Logger.Errorf("Prometheus client got data of type %T, but expected model.Matrix", values)
return Metric{Err: errors.Errorf("Prometheus client got data of type %T, but expected model.Matrix", values)}
}
return Metric{Matrix: m}
}
func all(items []string, conjunction string) string {
count := len(items)
if count == 0 {
return ""
}
quoted := make([]string, len(items))
for i, item := range items {
quoted[i] = fmt.Sprintf("'%s'", item)
}
if count == 1 {
return quoted[0]
}
head := quoted[0 : count-1]
tail := quoted[count-1]
return fmt.Sprintf("%s %s %s", strings.Join(head, ", "), conjunction, tail)
}