forked from intelsdi-x/snap
/
grpc.go
478 lines (419 loc) · 12 KB
/
grpc.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
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Corporation
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 client
import (
"crypto/rsa"
"errors"
"fmt"
"strconv"
"strings"
"time"
"google.golang.org/grpc"
"golang.org/x/net/context"
log "github.com/Sirupsen/logrus"
"github.com/intelsdi-x/snap/control/plugin"
"github.com/intelsdi-x/snap/control/plugin/cpolicy"
"github.com/intelsdi-x/snap/control/plugin/encrypter"
"github.com/intelsdi-x/snap/control/plugin/rpc"
"github.com/intelsdi-x/snap/core"
"github.com/intelsdi-x/snap/core/cdata"
"github.com/intelsdi-x/snap/core/ctypes"
"github.com/intelsdi-x/snap/pkg/rpcutil"
)
type pluginClient interface {
Ping(ctx context.Context, in *rpc.Empty, opts ...grpc.CallOption) (*rpc.ErrReply, error)
Kill(ctx context.Context, in *rpc.KillArg, opts ...grpc.CallOption) (*rpc.ErrReply, error)
GetConfigPolicy(ctx context.Context, in *rpc.Empty, opts ...grpc.CallOption) (*rpc.GetConfigPolicyReply, error)
}
type grpcClient struct {
collector rpc.CollectorClient
processor rpc.ProcessorClient
publisher rpc.PublisherClient
plugin pluginClient
pluginType plugin.PluginType
timeout time.Duration
conn *grpc.ClientConn
encrypter *encrypter.Encrypter
}
// NewCollectorGrpcClient returns a collector gRPC Client.
func NewCollectorGrpcClient(address string, timeout time.Duration, pub *rsa.PublicKey, secure bool) (PluginCollectorClient, error) {
address, port, err := parseAddress(address)
if err != nil {
return nil, err
}
p, err := newGrpcClient(address, int(port), timeout, plugin.CollectorPluginType)
if err != nil {
return nil, err
}
return p, nil
}
// NewProcessorGrpcClient returns a processor gRPC Client.
func NewProcessorGrpcClient(address string, timeout time.Duration, pub *rsa.PublicKey, secure bool) (PluginProcessorClient, error) {
address, port, err := parseAddress(address)
if err != nil {
return nil, err
}
p, err := newGrpcClient(address, int(port), timeout, plugin.ProcessorPluginType)
if err != nil {
return nil, err
}
if secure {
key, err := encrypter.GenerateKey()
if err != nil {
return nil, err
}
encrypter := encrypter.New(pub, nil)
encrypter.Key = key
p.encrypter = encrypter
}
return p, nil
}
// NewPublisherGrpcClient returns a publisher gRPC Client.
func NewPublisherGrpcClient(address string, timeout time.Duration, pub *rsa.PublicKey, secure bool) (PluginPublisherClient, error) {
address, port, err := parseAddress(address)
if err != nil {
return nil, err
}
p, err := newGrpcClient(address, int(port), timeout, plugin.PublisherPluginType)
if err != nil {
return nil, err
}
if secure {
key, err := encrypter.GenerateKey()
if err != nil {
return nil, err
}
encrypter := encrypter.New(pub, nil)
encrypter.Key = key
p.encrypter = encrypter
}
return p, nil
}
func parseAddress(address string) (string, int64, error) {
addr := strings.Split(address, ":")
if len(addr) != 2 {
return "", 0, fmt.Errorf("bad address")
}
address = addr[0]
port, err := strconv.ParseInt(addr[1], 10, 64)
if err != nil {
return "", 0, err
}
return address, port, nil
}
func newGrpcClient(addr string, port int, timeout time.Duration, typ plugin.PluginType) (*grpcClient, error) {
conn, err := rpcutil.GetClientConnection(addr, port)
if err != nil {
return nil, err
}
p := &grpcClient{
timeout: timeout,
conn: conn,
}
switch typ {
case plugin.CollectorPluginType:
p.collector = rpc.NewCollectorClient(conn)
p.plugin = p.collector
case plugin.ProcessorPluginType:
p.processor = rpc.NewProcessorClient(conn)
p.plugin = p.processor
case plugin.PublisherPluginType:
p.publisher = rpc.NewPublisherClient(conn)
p.plugin = p.publisher
default:
return nil, errors.New(fmt.Sprintf("Invalid plugin type provided %v", typ))
}
return p, nil
}
func getContext(timeout time.Duration) context.Context {
ctxTimeout, _ := context.WithTimeout(context.Background(), timeout)
return ctxTimeout
}
func (g *grpcClient) Ping() error {
_, err := g.plugin.Ping(getContext(g.timeout), &rpc.Empty{})
if err != nil {
return err
}
return nil
}
func (g *grpcClient) SetKey() error {
// Added to conform to interface but not needed by grpc
return nil
}
func (g *grpcClient) Kill(reason string) error {
_, err := g.plugin.Kill(getContext(g.timeout), &rpc.KillArg{Reason: reason})
g.conn.Close()
if err != nil {
return err
}
return nil
}
func (g *grpcClient) Publish(metrics []core.Metric, config map[string]ctypes.ConfigValue) error {
arg := &rpc.PubProcArg{
Metrics: NewMetrics(metrics),
Config: ToConfigMap(config),
}
_, err := g.publisher.Publish(getContext(g.timeout), arg)
if err != nil {
return err
}
return nil
}
func (g *grpcClient) Process(metrics []core.Metric, config map[string]ctypes.ConfigValue) ([]core.Metric, error) {
arg := &rpc.PubProcArg{
Metrics: NewMetrics(metrics),
Config: ToConfigMap(config),
}
reply, err := g.processor.Process(getContext(g.timeout), arg)
if err != nil {
return nil, err
}
if reply.Error != "" {
return nil, errors.New(reply.Error)
}
mts := ToCoreMetrics(reply.Metrics)
for _, mt := range mts {
log.Debug(mt.Namespace())
}
return mts, nil
}
func (g *grpcClient) CollectMetrics(mts []core.Metric) ([]core.Metric, error) {
arg := &rpc.MetricsArg{
Metrics: NewMetrics(mts),
}
reply, err := g.collector.CollectMetrics(getContext(g.timeout), arg)
if err != nil {
return nil, err
}
if reply.Error != "" {
return nil, errors.New(reply.Error)
}
metrics := ToCoreMetrics(reply.Metrics)
return metrics, nil
}
func (g *grpcClient) GetMetricTypes(config plugin.ConfigType) ([]core.Metric, error) {
arg := &rpc.GetMetricTypesArg{
Config: ToConfigMap(config.Table()),
}
reply, err := g.collector.GetMetricTypes(getContext(g.timeout), arg)
if err != nil {
return nil, err
}
if reply.Error != "" {
return nil, errors.New(reply.Error)
}
for _, metric := range reply.Metrics {
metric.LastAdvertisedTime = ToTime(time.Now())
}
results := ToCoreMetrics(reply.Metrics)
return results, nil
}
func (g *grpcClient) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) {
reply, err := g.plugin.GetConfigPolicy(getContext(g.timeout), &rpc.Empty{})
if err != nil {
return nil, err
}
if reply.Error != "" {
return nil, errors.New(reply.Error)
}
return rpc.ToConfigPolicy(reply), nil
}
type metric struct {
namespace core.Namespace
version int
config *cdata.ConfigDataNode
lastAdvertisedTime time.Time
timeStamp time.Time
data interface{}
tags map[string]string
description string
unit string
}
func (m *metric) Namespace() core.Namespace { return m.namespace }
func (m *metric) Config() *cdata.ConfigDataNode { return m.config }
func (m *metric) Version() int { return m.version }
func (m *metric) Data() interface{} { return m.data }
func (m *metric) Tags() map[string]string { return m.tags }
func (m *metric) LastAdvertisedTime() time.Time { return m.lastAdvertisedTime }
func (m *metric) Timestamp() time.Time { return m.timeStamp }
func (m *metric) Description() string { return m.description }
func (m *metric) Unit() string { return m.unit }
func ToCoreMetrics(mts []*rpc.Metric) []core.Metric {
metrics := make([]core.Metric, len(mts))
for i, mt := range mts {
metrics[i] = ToCoreMetric(mt)
}
return metrics
}
func ToCoreMetric(mt *rpc.Metric) core.Metric {
ret := &metric{
namespace: ToCoreNamespace(mt.Namespace),
version: int(mt.Version),
tags: mt.Tags,
timeStamp: time.Unix(mt.Timestamp.Sec, mt.Timestamp.Nsec),
lastAdvertisedTime: time.Unix(mt.LastAdvertisedTime.Sec, mt.LastAdvertisedTime.Nsec),
config: ConfigMapToConfig(mt.Config),
description: mt.Description,
unit: mt.Unit,
}
switch mt.Data.(type) {
case *rpc.Metric_BytesData:
ret.data = mt.GetBytesData()
case *rpc.Metric_StringData:
ret.data = mt.GetStringData()
case *rpc.Metric_Float32Data:
ret.data = mt.GetFloat32Data()
case *rpc.Metric_Float64Data:
ret.data = mt.GetFloat64Data()
case *rpc.Metric_Int32Data:
ret.data = mt.GetInt32Data()
case *rpc.Metric_Int64Data:
ret.data = mt.GetInt64Data()
case *rpc.Metric_BoolData:
ret.data = mt.GetBoolData()
}
return ret
}
func NewMetrics(ms []core.Metric) []*rpc.Metric {
metrics := make([]*rpc.Metric, len(ms))
for i, m := range ms {
metrics[i] = ToMetric(m)
}
return metrics
}
func ToMetric(co core.Metric) *rpc.Metric {
cm := &rpc.Metric{
Namespace: ToNamespace(co.Namespace()),
Version: int64(co.Version()),
Tags: co.Tags(),
Timestamp: &rpc.Time{
Sec: co.Timestamp().Unix(),
Nsec: int64(co.Timestamp().Nanosecond()),
},
LastAdvertisedTime: &rpc.Time{
Sec: co.LastAdvertisedTime().Unix(),
Nsec: int64(co.Timestamp().Nanosecond()),
},
}
if co.Config() != nil {
cm.Config = ConfigToConfigMap(co.Config())
}
switch t := co.Data().(type) {
case string:
cm.Data = &rpc.Metric_StringData{t}
case float64:
cm.Data = &rpc.Metric_Float64Data{t}
case float32:
cm.Data = &rpc.Metric_Float32Data{t}
case int32:
cm.Data = &rpc.Metric_Int32Data{t}
case int:
cm.Data = &rpc.Metric_Int64Data{int64(t)}
case int64:
cm.Data = &rpc.Metric_Int64Data{t}
case []byte:
cm.Data = &rpc.Metric_BytesData{t}
case bool:
cm.Data = &rpc.Metric_BoolData{t}
case nil:
cm.Data = nil
default:
log.Error(fmt.Sprintf("unsupported type: %s", t))
}
return cm
}
func ToCoreNamespace(n []*rpc.NamespaceElement) core.Namespace {
var namespace core.Namespace
for _, val := range n {
ele := core.NamespaceElement{
Value: val.Value,
Description: val.Description,
Name: val.Name,
}
namespace = append(namespace, ele)
}
return namespace
}
func ConfigMapToConfig(cfg *rpc.ConfigMap) *cdata.ConfigDataNode {
if cfg == nil {
return nil
}
config := cdata.FromTable(ParseConfig(cfg))
return config
}
func ToConfigMap(cv map[string]ctypes.ConfigValue) *rpc.ConfigMap {
newConfig := &rpc.ConfigMap{
IntMap: make(map[string]int64),
FloatMap: make(map[string]float64),
StringMap: make(map[string]string),
BoolMap: make(map[string]bool),
}
for k, v := range cv {
switch v.Type() {
case "integer":
newConfig.IntMap[k] = int64(v.(ctypes.ConfigValueInt).Value)
case "float":
newConfig.FloatMap[k] = v.(ctypes.ConfigValueFloat).Value
case "string":
newConfig.StringMap[k] = v.(ctypes.ConfigValueStr).Value
case "bool":
newConfig.BoolMap[k] = v.(ctypes.ConfigValueBool).Value
}
}
return newConfig
}
func ToNamespace(n core.Namespace) []*rpc.NamespaceElement {
elements := make([]*rpc.NamespaceElement, 0, len(n))
for _, value := range n {
ne := &rpc.NamespaceElement{
Value: value.Value,
Description: value.Description,
Name: value.Name,
}
elements = append(elements, ne)
}
return elements
}
func ConfigToConfigMap(cd *cdata.ConfigDataNode) *rpc.ConfigMap {
if cd == nil {
return nil
}
return ToConfigMap(cd.Table())
}
func ParseConfig(config *rpc.ConfigMap) map[string]ctypes.ConfigValue {
c := make(map[string]ctypes.ConfigValue)
for k, v := range config.IntMap {
ival := ctypes.ConfigValueInt{Value: int(v)}
c[k] = ival
}
for k, v := range config.FloatMap {
fval := ctypes.ConfigValueFloat{Value: v}
c[k] = fval
}
for k, v := range config.StringMap {
sval := ctypes.ConfigValueStr{Value: v}
c[k] = sval
}
for k, v := range config.BoolMap {
bval := ctypes.ConfigValueBool{Value: v}
c[k] = bval
}
return c
}
func ToTime(t time.Time) *rpc.Time {
return &rpc.Time{
Nsec: t.Unix(),
Sec: int64(t.Second()),
}
}