This repository has been archived by the owner on Dec 1, 2018. It is now read-only.
/
driver.go
296 lines (248 loc) · 7.26 KB
/
driver.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
// 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 hawkular
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"sync"
"github.com/golang/glog"
"github.com/hawkular/hawkular-client-go/metrics"
"k8s.io/heapster/metrics/core"
kube_client "k8s.io/kubernetes/pkg/client/unversioned"
kubeClientCmd "k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
)
const (
unitsTag = "units"
descriptionTag = "_description"
descriptorTag = "descriptor_name"
groupTag = "group_id"
separator = "/"
batchSizeDefault = 1000
concurrencyDefault = 5
defaultServiceAccountFile = "/var/run/secrets/kubernetes.io/serviceaccount/token"
)
// START: ExternalSink interface implementations
func (self *hawkularSink) Register(mds []core.MetricDescriptor) error {
// Create model definitions based on the MetricDescriptors
for _, md := range mds {
hmd := self.descriptorToDefinition(&md)
self.models[md.Name] = &hmd
}
// Fetch currently known metrics from Hawkular-Metrics and cache them
types := []metrics.MetricType{metrics.Gauge, metrics.Counter}
for _, t := range types {
err := self.updateDefinitions(t)
if err != nil {
return err
}
}
return nil
}
func (self *hawkularSink) Stop() {
self.regLock.Lock()
defer self.regLock.Unlock()
self.init()
}
func (self *hawkularSink) ExportData(db *core.DataBatch) {
totalCount := 0
for _, ms := range db.MetricSets {
totalCount += len(ms.MetricValues)
}
if len(db.MetricSets) > 0 {
tmhs := make(map[string][]metrics.MetricHeader)
if &self.labelTenant == nil {
tmhs[self.client.Tenant] = make([]metrics.MetricHeader, 0, totalCount)
}
wg := &sync.WaitGroup{}
for _, ms := range db.MetricSets {
Store:
for metricName := range ms.MetricValues {
for _, filter := range self.filters {
if !filter(ms, metricName) {
continue Store
}
}
tenant := self.client.Tenant
if &self.labelTenant != nil {
if v, found := ms.Labels[self.labelTenant]; found {
tenant = v
}
}
// Registering should not block the processing
// This isn't concurrency limited (and is mostly network limited on HWKMETRICS end)
wg.Add(1)
go func(ms *core.MetricSet, metricName string, tenant string) {
defer wg.Done()
self.registerIfNecessary(ms, metricName, metrics.Tenant(tenant))
}(ms, metricName, tenant)
mH, err := self.pointToMetricHeader(ms, metricName, db.Timestamp)
if err != nil {
// One transformation error should not prevent the whole process
glog.Errorf(err.Error())
continue
}
if _, found := tmhs[tenant]; !found {
tmhs[tenant] = make([]metrics.MetricHeader, 0)
}
tmhs[tenant] = append(tmhs[tenant], *mH)
}
}
self.sendData(tmhs, wg) // Send to a limited channel? Only batches.. egg.
wg.Wait()
}
}
func (self *hawkularSink) DebugInfo() string {
info := fmt.Sprintf("%s\n", self.Name())
self.regLock.Lock()
defer self.regLock.Unlock()
info += fmt.Sprintf("Known metrics: %d\n", len(self.reg))
if &self.labelTenant != nil {
info += fmt.Sprintf("Using label '%s' as tenant information\n", self.labelTenant)
}
// TODO Add here statistics from the Hawkular-Metrics client instance
return info
}
func (self *hawkularSink) Name() string {
return "Hawkular-Metrics Sink"
}
func NewHawkularSink(u *url.URL) (core.DataSink, error) {
sink := &hawkularSink{
uri: u,
batchSize: 1000,
}
if err := sink.init(); err != nil {
return nil, err
}
metrics := make([]core.MetricDescriptor, 0, len(core.StandardMetrics))
for _, metric := range core.StandardMetrics {
metrics = append(metrics, metric.MetricDescriptor)
}
sink.Register(metrics)
return sink, nil
}
func (self *hawkularSink) init() error {
self.reg = make(map[string]*metrics.MetricDefinition)
self.models = make(map[string]*metrics.MetricDefinition)
self.modifiers = make([]metrics.Modifier, 0)
self.filters = make([]Filter, 0)
self.batchSize = batchSizeDefault
self.concurrencyLimit = concurrencyDefault
p := metrics.Parameters{
Tenant: "heapster",
Url: self.uri.String(),
}
opts := self.uri.Query()
if v, found := opts["tenant"]; found {
p.Tenant = v[0]
}
if v, found := opts["labelToTenant"]; found {
self.labelTenant = v[0]
}
if v, found := opts["useServiceAccount"]; found {
if b, _ := strconv.ParseBool(v[0]); b {
// If a readable service account token exists, then use it
if contents, err := ioutil.ReadFile(defaultServiceAccountFile); err == nil {
p.Token = string(contents)
}
}
}
// Authentication / Authorization parameters
tC := &tls.Config{}
if v, found := opts["auth"]; found {
if _, f := opts["caCert"]; f {
return fmt.Errorf("Both auth and caCert files provided, combination is not supported")
}
if len(v[0]) > 0 {
// Authfile
kubeConfig, err := kubeClientCmd.NewNonInteractiveDeferredLoadingClientConfig(&kubeClientCmd.ClientConfigLoadingRules{
ExplicitPath: v[0]},
&kubeClientCmd.ConfigOverrides{}).ClientConfig()
if err != nil {
return err
}
tC, err = kube_client.TLSConfigFor(kubeConfig)
if err != nil {
return err
}
}
}
if u, found := opts["user"]; found {
if _, wrong := opts["useServiceAccount"]; wrong {
return fmt.Errorf("If user and password are used, serviceAccount cannot be used")
}
if p, f := opts["pass"]; f {
self.modifiers = append(self.modifiers, func(req *http.Request) error {
req.SetBasicAuth(u[0], p[0])
return nil
})
}
}
if v, found := opts["caCert"]; found {
caCert, err := ioutil.ReadFile(v[0])
if err != nil {
return err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tC.RootCAs = caCertPool
}
if v, found := opts["insecure"]; found {
_, f := opts["caCert"]
_, f2 := opts["auth"]
if f || f2 {
return fmt.Errorf("Insecure can't be defined with auth or caCert")
}
insecure, err := strconv.ParseBool(v[0])
if err != nil {
return err
}
tC.InsecureSkipVerify = insecure
}
p.TLSConfig = tC
// Filters
if v, found := opts["filter"]; found {
filters, err := parseFilters(v)
if err != nil {
return err
}
self.filters = filters
}
// Concurrency limitations
if v, found := opts["concurrencyLimit"]; found {
cs, err := strconv.Atoi(v[0])
if err != nil || cs < 0 {
return fmt.Errorf("Supplied concurrency value of %s is invalid", v[0])
}
self.concurrencyLimit = cs
}
if v, found := opts["batchSize"]; found {
bs, err := strconv.Atoi(v[0])
if err != nil || bs < 0 {
return fmt.Errorf("Supplied batchSize value of %s is invalid", v[0])
}
self.batchSize = bs
}
c, err := metrics.NewHawkularClient(p)
if err != nil {
return err
}
self.client = c
glog.Infof("Initialised Hawkular Sink with parameters %v", p)
return nil
}