forked from kubernetes-retired/heapster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.go
484 lines (419 loc) · 13.1 KB
/
core.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gcm
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/GoogleCloudPlatform/gcloud-golang/compute/metadata"
"github.com/GoogleCloudPlatform/heapster/util"
"github.com/GoogleCloudPlatform/heapster/util/gce"
"github.com/GoogleCloudPlatform/heapster/util/gcstore"
"github.com/golang/glog"
sink_api "github.com/GoogleCloudPlatform/heapster/sinks/api/v1"
)
const GCLAuthScope = "https://www.googleapis.com/auth/monitoring"
type GcmCore struct {
// Token to use for authentication.
token string
// When the token expires.
tokenExpiration time.Time
// TODO(vmarmol): Make this configurable and not only detected.
// GCE project.
project string
// TODO(vmarmol): Also store labels?
// Map of metrics we currently export.
exportedMetrics map[string]metricDescriptor
// The last value we have pushed for every cumulative metric.
lastValue gcstore.GCStore
}
func (self *GcmCore) refreshToken() error {
if time.Now().After(self.tokenExpiration) {
token, err := gce.GetAuthToken()
if err != nil {
return err
}
// Expire the token a bit early.
const earlyRefreshSeconds = 60
if token.ExpiresIn > earlyRefreshSeconds {
token.ExpiresIn -= earlyRefreshSeconds
}
self.token = token.AccessToken
self.tokenExpiration = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)
}
return nil
}
// GCM request structures for a MetricDescriptor.
type typeDescriptor struct {
MetricType string `json:"metricType,omitempty"`
ValueType string `json:"valueType,omitempty"`
}
type metricDescriptor struct {
Name string `json:"name,omitempty"`
Project string `json:"project,omitempty"`
Description string `json:"description,omitempty"`
Labels []sink_api.LabelDescriptor `json:"labels,omitempty"`
TypeDescriptor typeDescriptor `json:"typeDescriptor,omitempty"`
}
// Map of metric name to translation function.
var translationFuncs = map[string]func(float64) float64{
"uptime_rate": func(value float64) float64 {
// Convert from milliseconds to seconds.
return value / 1000
},
"cpu/usage_rate": func(value float64) float64 {
// Convert from billionths of a core to millicores.
return value / 1000000
},
}
type listMetricsResponse struct {
Metrics []metricDescriptor `json:"metrics,omitempty"`
}
func (self *GcmCore) defaultUrlPath() string {
return fmt.Sprintf("https://www.googleapis.com/cloudmonitoring/v2beta2/projects/%s", self.project)
}
func (self *GcmCore) listMetrics() error {
response := listMetricsResponse{}
url, err := url.Parse(self.defaultUrlPath() + "/metricDescriptors")
if err != nil {
return err
}
err = sendRequest("GET", self.token, url, nil, &response)
if err != nil {
glog.Errorf("[GCM] list metrics failed %v", err)
return err
}
apiPrefix := fmt.Sprintf("%s/%s", customApiPrefix, metricDomain)
for idx, m := range response.Metrics {
if strings.HasPrefix(m.Name, apiPrefix) {
self.exportedMetrics[m.Name] = response.Metrics[idx]
}
}
return nil
}
func (self *GcmCore) deleteMetric(metricName string) error {
url := &url.URL{
Scheme: "https",
Host: "www.googleapis.com",
Opaque: fmt.Sprintf("%s/metricDescriptors/%s", self.defaultUrlPath(), url.QueryEscape(metricName)),
}
err := sendRequest("DELETE", self.token, url, nil, nil)
if err != nil {
glog.V(2).Infof("[GCM] Deleting metric %q failed: %v", metricName, err)
}
return err
}
func (self *GcmCore) addMetric(request metricDescriptor) error {
if existingMetric, found := self.exportedMetrics[request.Name]; found {
if existingMetric.TypeDescriptor != request.TypeDescriptor {
if err := self.deleteMetric(request.Name); err != nil {
return err
}
}
}
url, err := url.Parse(self.defaultUrlPath() + "/metricDescriptors")
if err != nil {
return err
}
if err = sendRequest("POST", self.token, url, request, nil); err == nil {
glog.V(3).Infof("[GCM] Added metric %q", request.Name)
// Add metric to exportedMetrics.
self.exportedMetrics[request.Name] = request
}
return err
}
func (self *GcmCore) Register(name, description, metricType, valueType string, labels []sink_api.LabelDescriptor) error {
// Enforce the most labels that GCM allows.
if len(labels) > maxNumLabels {
return fmt.Errorf("metrics cannot have more than %d labels and %q has %d", maxNumLabels, name, len(labels))
}
// Ensure all labels are in the correct format.
for i := range labels {
labels[i].Key = fullLabelName(labels[i].Key)
}
request := metricDescriptor{
Name: FullMetricName(name),
Project: self.project,
Description: description,
Labels: labels,
TypeDescriptor: typeDescriptor{
MetricType: metricType,
ValueType: valueType,
},
}
if err := self.addMetric(request); err != nil {
return err
}
return nil
}
// GCM request structures for writing time-series data.
type timeseriesDescriptor struct {
Project string `json:"project,omitempty"`
Metric string `json:"metric,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
}
type point struct {
Start time.Time `json:"start,omitempty"`
End time.Time `json:"end,omitempty"`
DoubleValue *float64 `json:"doubleValue,omitempty"`
Int64Value *int64 `json:"int64Value,omitempty"`
}
type Timeseries struct {
TimeseriesDescriptor timeseriesDescriptor `json:"timeseriesDesc,omitempty"`
Point point `json:"point,omitempty"`
}
type metricWriteRequest struct {
Timeseries []Timeseries `json:"timeseries,omitempty"`
}
type lastValueKey struct {
metricName string
labels string
}
type lastValueData struct {
value int64
timestamp time.Time
}
func (self *GcmCore) StoreTimeseries(metrics map[string][]Timeseries) error {
// Ensure the metrics exist.
for name := range metrics {
// TODO: Remove this check if possible.
if _, ok := self.exportedMetrics[FullMetricName(name)]; !ok {
return fmt.Errorf("unable to push unknown metric %q", name)
}
}
// Only send one metric of each type per request.
var lastErr error
for len(metrics) != 0 {
var request metricWriteRequest
for name, values := range metrics {
// Remove metrics with no more values.
if len(values) == 0 {
delete(metrics, name)
continue
}
m := values[0]
metrics[name] = values[1:]
request.Timeseries = append(request.Timeseries, m)
}
err := self.pushMetrics(&request)
if err != nil {
lastErr = err
}
}
return lastErr
}
func (self *GcmCore) GetMetric(metric *sink_api.Point) (*Timeseries, error) {
// TODO(vmarmol): Validation and cleanup of data.
// TODO(vmarmol): Handle non-int64 data types. There is an issue with using omitempty since 0 is a valid value for us.
value, ok := metric.Value.(int64)
if !ok {
return nil, fmt.Errorf("non-int64 data not implemented. Seen for metric %q", metric.Name)
}
// Use full label names.
labels := make(map[string]string, len(metric.Labels))
for key, value := range metric.Labels {
labels[fullLabelName(key)] = value
}
return &Timeseries{
TimeseriesDescriptor: timeseriesDescriptor{
Metric: FullMetricName(metric.Name),
Labels: labels,
},
Point: point{
Start: metric.Start,
End: metric.End,
Int64Value: &value,
},
}, nil
}
func (self *GcmCore) GetEquivalentRateMetric(metric *sink_api.Point) (*Timeseries, error) {
// TODO(vmarmol): Validation and cleanup of data.
// TODO(vmarmol): Handle non-int64 data types. There is an issue with using omitempty since 0 is a valid value for us.
value, ok := metric.Value.(int64)
if !ok {
return nil, fmt.Errorf("non-int64 data not implemented. Seen for metric %q", metric.Name)
}
// Use full label names.
labels := make(map[string]string, len(metric.Labels))
for key, value := range metric.Labels {
labels[fullLabelName(key)] = value
}
rateMetric, exists := gcmRateMetrics[metric.Name]
if !exists {
return nil, nil
}
key := lastValueKey{
metricName: FullMetricName(rateMetric.name),
labels: util.LabelsToString(labels, ","),
}
lastValueRaw := self.lastValue.Get(key)
self.lastValue.Put(key, lastValueData{
value: value,
timestamp: metric.End,
})
// We need two metrics to do a delta, skip first value.
if lastValueRaw == nil {
return nil, nil
}
lastValue, ok := lastValueRaw.(lastValueData)
if !ok {
return nil, nil
}
doubleValue := float64(value)
doubleValue = float64(value-lastValue.value) / float64(metric.End.UnixNano()-lastValue.timestamp.UnixNano()) * float64(time.Second)
// Translate to a float using the custom translation function.
if transFunc, ok := translationFuncs[rateMetric.name]; ok {
doubleValue = transFunc(doubleValue)
}
return &Timeseries{
TimeseriesDescriptor: timeseriesDescriptor{
Metric: FullMetricName(rateMetric.name),
Labels: labels,
},
Point: point{
Start: metric.End,
End: metric.End,
DoubleValue: &doubleValue,
},
}, nil
}
func (self *GcmCore) pushMetrics(request *metricWriteRequest) error {
if len(request.Timeseries) == 0 {
return nil
}
// TODO(vmarmol): Split requests in this case.
if len(request.Timeseries) > maxTimeseriesPerRequest {
return fmt.Errorf("unable to write more than %d metrics at once and %d were provided", maxTimeseriesPerRequest, len(request.Timeseries))
}
// Refresh token.
err := self.refreshToken()
if err != nil {
return err
}
url, err := url.Parse(fmt.Sprintf("%s/timeseries:write", self.defaultUrlPath()))
if err != nil {
return err
}
const requestAttempts = 3
for i := 1; i <= requestAttempts; i++ {
err = sendRequest("POST", self.token, url, request, nil)
if err != nil {
glog.Warningf("[GCM] Push attempt %d failed: %v", i, err)
} else {
break
}
}
if err != nil {
prettyRequest, _ := json.MarshalIndent(request, "", " ")
glog.Warningf("[GCM] Pushing %d metrics \n%s\n failed: %v", len(request.Timeseries), string(prettyRequest), err)
} else {
glog.V(2).Infof("[GCM] Pushing %d metrics: SUCCESS", len(request.Timeseries))
}
return err
}
const (
// Domain for the metrics.
metricDomain = "kubernetes.io"
customApiPrefix = "custom.cloudmonitoring.googleapis.com"
maxNumLabels = 10
// The largest number of timeseries we can write to per request.
maxTimeseriesPerRequest = 200
)
func fullLabelName(name string) string {
if !strings.Contains(name, "custom.cloudmonitoring.googleapis.com/") && !strings.Contains(name, "compute.googleapis.com") {
return fmt.Sprintf("custom.cloudmonitoring.googleapis.com/%s/label/%s", metricDomain, name)
}
return name
}
func FullMetricName(name string) string {
if !strings.HasPrefix(name, customApiPrefix) {
return fmt.Sprintf("%s/%s/%s", customApiPrefix, metricDomain, name)
}
return name
}
func sendRequest(method, token string, url *url.URL, request interface{}, value interface{}) error {
var rawRequest io.Reader = nil
if request != nil {
jsonRequest, err := json.Marshal(request)
if err != nil {
return err
}
rawRequest = bytes.NewReader(jsonRequest)
}
req, err := http.NewRequest(method, url.String(), rawRequest)
if err != nil {
return err
}
req.URL = url
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
resp, err := (&http.Client{}).Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("request %+v failed with status %q and response: %+v, Body: %q", req, resp.Status, resp, string(body))
}
if value != nil {
err = json.Unmarshal(body, value)
if err != nil {
return fmt.Errorf("failed to parse output. Response: %q. Error: %v", string(body), err)
}
}
return nil
}
// Returns a thread-compatible implementation of GCM interactions.
func NewCore() (*GcmCore, error) {
// TODO: Retry OnGCE call for ~15 seconds before declaring failure.
time.Sleep(3 * time.Second)
// Only support GCE for now.
if !metadata.OnGCE() {
return nil, fmt.Errorf("the GCM sink is currently only supported on GCE")
}
// Detect project.
project, err := metadata.ProjectID()
if err != nil {
return nil, err
}
// Check required service accounts
err = gce.VerifyAuthScope(GCLAuthScope)
if err != nil {
return nil, err
}
core := &GcmCore{
project: project,
exportedMetrics: make(map[string]metricDescriptor),
lastValue: gcstore.New(time.Hour),
}
// Get an initial token.
err = core.refreshToken()
if err != nil {
return nil, err
}
if err := core.listMetrics(); err != nil {
return nil, err
}
return core, nil
}