forked from kubernetes-retired/heapster
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
384 lines (321 loc) · 9.99 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
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
// Copyright 2016 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 hawkular
import (
"fmt"
"math"
"regexp"
"strings"
"sync"
"time"
"github.com/golang/glog"
"github.com/hawkular/hawkular-client-go/metrics"
"k8s.io/heapster/metrics/core"
)
// Fetches definitions from the server and checks that they're matching the descriptors
func (self *hawkularSink) updateDefinitions(mt metrics.MetricType) error {
m := make([]metrics.Modifier, len(self.modifiers), len(self.modifiers)+1)
copy(m, self.modifiers)
m = append(m, metrics.Filters(metrics.TypeFilter(mt)))
mds, err := self.client.Definitions(m...)
if err != nil {
return err
}
self.regLock.Lock()
defer self.regLock.Unlock()
for _, p := range mds {
// If no descriptorTag is found, this metric does not belong to Heapster
if mk, found := p.Tags[descriptorTag]; found {
if model, f := self.models[mk]; f {
if !self.recent(p, model) {
if err := self.client.UpdateTags(mt, p.Id, p.Tags, self.modifiers...); err != nil {
return err
}
}
}
self.reg[p.Id] = p
}
}
return nil
}
// Checks that stored definition is up to date with the model
func (self *hawkularSink) recent(live *metrics.MetricDefinition, model *metrics.MetricDefinition) bool {
recent := true
for k := range model.Tags {
if v, found := live.Tags[k]; !found {
// There's a label that wasn't in our stored definition
live.Tags[k] = v
recent = false
}
}
return recent
}
// Transform the MetricDescriptor to a format used by Hawkular-Metrics
func (self *hawkularSink) descriptorToDefinition(md *core.MetricDescriptor) metrics.MetricDefinition {
tags := make(map[string]string)
// Postfix description tags with _description
for _, l := range md.Labels {
if len(l.Description) > 0 {
tags[l.Key+descriptionTag] = l.Description
}
}
if len(md.Units.String()) > 0 {
tags[unitsTag] = md.Units.String()
}
tags[descriptorTag] = md.Name
hmd := metrics.MetricDefinition{
Id: md.Name,
Tags: tags,
Type: heapsterTypeToHawkularType(md.Type),
}
return hmd
}
func (self *hawkularSink) groupName(ms *core.MetricSet, metricName string) string {
n := []string{ms.Labels[core.LabelContainerName.Key], metricName}
return strings.Join(n, separator)
}
func (self *hawkularSink) idName(ms *core.MetricSet, metricName string) string {
n := make([]string, 0, 3)
n = append(n, ms.Labels[core.LabelContainerName.Key])
if ms.Labels[core.LabelPodId.Key] != "" {
n = append(n, ms.Labels[core.LabelPodId.Key])
} else {
n = append(n, ms.Labels[core.LabelHostID.Key])
}
n = append(n, metricName)
return strings.Join(n, separator)
}
// Check that metrics tags are defined on the Hawkular server and if not,
// register the metric definition.
func (self *hawkularSink) registerIfNecessary(ms *core.MetricSet, metricName string, m ...metrics.Modifier) error {
key := self.idName(ms, metricName)
self.regLock.Lock()
defer self.regLock.Unlock()
// If found, check it matches the current stored definition (could be old info from
// the stored metrics cache for example)
if _, found := self.reg[key]; !found {
// Register the metric descriptor here..
if md, f := self.models[metricName]; f {
// Copy the original map
mdd := *md
tags := make(map[string]string)
for k, v := range mdd.Tags {
tags[k] = v
}
mdd.Tags = tags
// Set tag values
for k, v := range ms.Labels {
mdd.Tags[k] = v
}
mdd.Tags[groupTag] = self.groupName(ms, metricName)
mdd.Tags[descriptorTag] = metricName
m = append(m, self.modifiers...)
// Create metric, use updateTags instead of Create because we know it is unique
if err := self.client.UpdateTags(mdd.Type, key, mdd.Tags, m...); err != nil {
// Log error and don't add this key to the lookup table
glog.Errorf("Could not update tags: %s", err)
return err
}
// Add to the lookup table
self.reg[key] = &mdd
} else {
return fmt.Errorf("Could not find definition model with name %s", metricName)
}
}
// TODO Compare the definition tags and update if necessary? Quite expensive operation..
return nil
}
func (self *hawkularSink) registerLabeledIfNecessary(ms *core.MetricSet, metric core.LabeledMetric, m ...metrics.Modifier) error {
key := self.idName(ms, metric.Name)
if resourceId, found := metric.Labels[core.LabelResourceID.Key]; found {
key = self.idName(ms, metric.Name+separator+resourceId)
}
self.regLock.Lock()
defer self.regLock.Unlock()
// If found, check it matches the current stored definition (could be old info from
// the stored metrics cache for example)
if _, found := self.reg[key]; !found {
// Register the metric descriptor here..
if md, f := self.models[metric.Name]; f {
// Copy the original map
mdd := *md
tags := make(map[string]string)
for k, v := range mdd.Tags {
tags[k] = v
}
mdd.Tags = tags
// Set tag values
for k, v := range ms.Labels {
mdd.Tags[k] = v
}
// Set the labelled values
for k, v := range metric.Labels {
mdd.Tags[k] = v
}
mdd.Tags[groupTag] = self.groupName(ms, metric.Name)
mdd.Tags[descriptorTag] = metric.Name
m = append(m, self.modifiers...)
// Create metric, use updateTags instead of Create because we know it is unique
if err := self.client.UpdateTags(heapsterTypeToHawkularType(metric.MetricType), key, mdd.Tags, m...); err != nil {
// Log error and don't add this key to the lookup table
glog.Errorf("Could not update tags: %s", err)
return err
}
// Add to the lookup table
self.reg[key] = &mdd
} else {
return fmt.Errorf("Could not find definition model with name %s", metric.Name)
}
}
// TODO Compare the definition tags and update if necessary? Quite expensive operation..
return nil
}
func toBatches(m []metrics.MetricHeader, batchSize int) chan []metrics.MetricHeader {
if batchSize == 0 {
c := make(chan []metrics.MetricHeader, 1)
c <- m
return c
}
size := int(math.Ceil(float64(len(m)) / float64(batchSize)))
c := make(chan []metrics.MetricHeader, size)
for i := 0; i < len(m); i += batchSize {
n := i + batchSize
if len(m) < n {
n = len(m)
}
part := m[i:n]
c <- part
}
return c
}
func (self *hawkularSink) sendData(tmhs map[string][]metrics.MetricHeader, wg *sync.WaitGroup) {
for k, v := range tmhs {
parts := toBatches(v, self.batchSize)
close(parts)
for i := 0; i < self.concurrencyLimit; i++ {
wg.Add(1)
go func(v []metrics.MetricHeader, k string) {
defer wg.Done()
for p := range parts {
m := make([]metrics.Modifier, len(self.modifiers), len(self.modifiers)+1)
copy(m, self.modifiers)
m = append(m, metrics.Tenant(k))
if err := self.client.Write(p, m...); err != nil {
glog.Errorf(err.Error())
}
}
}(v, k)
}
}
}
// Converts Timeseries to metric structure used by the Hawkular
func (self *hawkularSink) pointToMetricHeader(ms *core.MetricSet, metricName string, timestamp time.Time) (*metrics.MetricHeader, error) {
metricValue := ms.MetricValues[metricName]
name := self.idName(ms, metricName)
var value float64
if metricValue.ValueType == core.ValueInt64 {
value = float64(metricValue.IntValue)
} else {
value = float64(metricValue.FloatValue)
}
m := metrics.Datapoint{
Value: value,
Timestamp: metrics.UnixMilli(timestamp),
}
mh := &metrics.MetricHeader{
Id: name,
Data: []metrics.Datapoint{m},
Type: heapsterTypeToHawkularType(metricValue.MetricType),
}
return mh, nil
}
// Converts Timeseries to metric structure used by the Hawkular
func (self *hawkularSink) pointToLabeledMetricHeader(ms *core.MetricSet, metric core.LabeledMetric, timestamp time.Time) (*metrics.MetricHeader, error) {
name := self.idName(ms, metric.Name)
if resourceId, found := metric.Labels[core.LabelResourceID.Key]; found {
name = self.idName(ms, metric.Name+separator+resourceId)
}
var value float64
if metric.ValueType == core.ValueInt64 {
value = float64(metric.IntValue)
} else {
value = float64(metric.FloatValue)
}
m := metrics.Datapoint{
Value: value,
Timestamp: metrics.UnixMilli(timestamp),
}
mh := &metrics.MetricHeader{
Id: name,
Data: []metrics.Datapoint{m},
Type: heapsterTypeToHawkularType(metric.MetricType),
}
return mh, nil
}
// If Heapster gets filters, remove these..
func parseFilters(v []string) ([]Filter, error) {
fs := make([]Filter, 0, len(v))
for _, s := range v {
p := strings.Index(s, "(")
if p < 0 {
return nil, fmt.Errorf("Incorrect syntax in filter parameters, missing (")
}
if strings.Index(s, ")") != len(s)-1 {
return nil, fmt.Errorf("Incorrect syntax in filter parameters, missing )")
}
t := Unknown.From(s[:p])
if t == Unknown {
return nil, fmt.Errorf("Unknown filter type")
}
command := s[p+1 : len(s)-1]
switch t {
case Label:
proto := strings.SplitN(command, ":", 2)
if len(proto) < 2 {
return nil, fmt.Errorf("Missing : from label filter")
}
r, err := regexp.Compile(proto[1])
if err != nil {
return nil, err
}
fs = append(fs, labelFilter(proto[0], r))
break
case Name:
r, err := regexp.Compile(command)
if err != nil {
return nil, err
}
fs = append(fs, nameFilter(r))
break
}
}
return fs, nil
}
func labelFilter(label string, r *regexp.Regexp) Filter {
return func(ms *core.MetricSet, metricName string) bool {
for k, v := range ms.Labels {
if k == label {
if r.MatchString(v) {
return false
}
}
}
return true
}
}
func nameFilter(r *regexp.Regexp) Filter {
return func(ms *core.MetricSet, metricName string) bool {
return !r.MatchString(metricName)
}
}