-
Notifications
You must be signed in to change notification settings - Fork 18
/
aci-api.go
756 lines (631 loc) · 22.2 KB
/
aci-api.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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"time"
"github.com/umisama/go-regexpcache"
"github.com/Knetic/govaluate"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"github.com/tidwall/gjson"
)
var arrayExtension = regexpcache.MustCompile("^(?P<stage_1>.*)\\.\\[(?P<child_name>.*)\\](?P<stage_2>.*)")
func newAciAPI(ctx context.Context, fabricConfig *Fabric, configQueries AllQueries, queryArray []string, node *string) *aciAPI {
executeQueries := queriesToExecute(configQueries, queryArray)
api := &aciAPI{
ctx: ctx,
connection: newAciConnection(fabricConfig, node),
metricPrefix: viper.GetString("prefix"),
configQueries: executeQueries.ClassQueries,
configCompoundQueries: executeQueries.CompoundClassQueries,
configGroupQueries: executeQueries.GroupClassQueries,
configBuiltInQueries: BuiltinQueries{},
}
// Make sure all built in queries are handled
if queryArray != nil {
// If query parameter queries is used
for _, v := range queryArray {
if v == "faults" {
api.configBuiltInQueries["faults"] = api.faults
}
// Add all other builtin with if statements
}
} else {
// If query parameter queries is NOT used, include all
api.configBuiltInQueries["faults"] = api.faults
}
return api
}
type aciAPI struct {
ctx context.Context
connection *AciConnection
metricPrefix string
configQueries ClassQueries
configCompoundQueries CompoundClassQueries
configGroupQueries GroupClassQueries
configBuiltInQueries BuiltinQueries
}
func queriesToExecute(configQueries AllQueries, queryArray []string) AllQueries {
if queryArray == nil {
// Default is all configured queries to execute
return configQueries
}
executeQueries := AllQueries{}
executeQueries.ClassQueries = ClassQueries{}
executeQueries.CompoundClassQueries = CompoundClassQueries{}
executeQueries.GroupClassQueries = GroupClassQueries{}
// Find the named queries for the different type
for _, queryName := range queryArray {
for configQueryName := range configQueries.ClassQueries {
if queryName == configQueryName {
executeQueries.ClassQueries[configQueryName] = configQueries.ClassQueries[configQueryName]
}
}
for k := range configQueries.CompoundClassQueries {
if queryName == k {
executeQueries.CompoundClassQueries[k] = configQueries.CompoundClassQueries[k]
}
}
for k := range configQueries.GroupClassQueries {
if queryName == k {
executeQueries.GroupClassQueries[k] = configQueries.GroupClassQueries[k]
}
}
}
return executeQueries
}
// CollectMetrics Gather all aci metrics and return name of the aci fabric, slice of metrics and status of
// successful login
func (p aciAPI) CollectMetrics() (string, []MetricDefinition, error) {
var metrics []MetricDefinition
start := time.Now()
err := p.connection.login(p.ctx)
// defer p.connection.logout()
if err != nil {
metrics = append(metrics, *p.up(0.0))
return "", metrics, err
}
aciName, err := p.getAciName()
if err != nil {
metrics = append(metrics, *p.up(0.0))
return "", metrics, err
}
// Hold all metrics created during the session
ch := make(chan []MetricDefinition)
// Built-in
go p.configuredBuiltInMetrics(ch)
// Execute all configured class queries
go p.configuredClassMetrics(ch)
// Execute all configured compound queries
go p.configuredCompoundsMetrics(ch)
// Execute all configured group queries
go p.configuredGroupMetrics(ch)
for i := 0; i < 4; i++ {
metrics = append(metrics, <-ch...)
}
end := time.Since(start)
if metrics == nil {
// if no metrics are returned the apic or node may be down
metrics = append(metrics, *p.up(0.0))
} else {
metrics = append(metrics, *p.up(1.0))
}
metrics = append(metrics, *p.scrape(end.Seconds()))
log.WithFields(log.Fields{
LogFieldRequestID: p.ctx.Value(LogFieldRequestID),
LogFieldExecTime: end.Microseconds(),
LogFieldFabric: fmt.Sprintf("%v", p.ctx.Value(LogFieldFabric)),
}).Info("total scrape time ")
return aciName, metrics, nil
}
func (p aciAPI) scrape(seconds float64) *MetricDefinition {
metricDefinition := MetricDefinition{}
metricDefinition.Name = "scrape_duration"
metricDefinition.Description = MetricDesc{
Help: "The duration, in seconds, of the last scrape of the fabric",
Type: "gauge",
Unit: "seconds",
}
metricDefinition.Metrics = []Metric{}
metric := Metric{}
metric.Labels = make(map[string]string)
metric.Value = seconds
metricDefinition.Metrics = append(metricDefinition.Metrics, metric)
return &metricDefinition
}
func (p aciAPI) up(state float64) *MetricDefinition {
metricDefinition := MetricDefinition{}
metricDefinition.Name = "up"
metricDefinition.Description = MetricDesc{
Help: "The connection state 1=UP, 0=DOWN",
Type: "gauge",
}
metricDefinition.Metrics = []Metric{}
metric := Metric{}
metric.Labels = make(map[string]string)
metric.Value = state
metricDefinition.Metrics = append(metricDefinition.Metrics, metric)
return &metricDefinition
}
func (p aciAPI) configuredBuiltInMetrics(chall chan []MetricDefinition) {
var metricDefinitions []MetricDefinition
ch := make(chan []MetricDefinition)
for _, fun := range p.configBuiltInQueries {
go fun(ch)
}
for range p.configBuiltInQueries {
metricDefinitions = append(metricDefinitions, <-ch...)
}
chall <- metricDefinitions
}
func (p aciAPI) faults(ch chan []MetricDefinition) {
data, err := p.connection.GetByQuery(p.ctx, "faults")
if err != nil {
log.WithFields(log.Fields{
LogFieldRequestID: p.ctx.Value(LogFieldRequestID),
LogFieldFabric: fmt.Sprintf("%v", p.ctx.Value(LogFieldFabric)),
}).Error("faults not supported", err)
ch <- nil
return
}
metricDefinitionFaults := MetricDefinition{}
metricDefinitionFaults.Name = "faults"
metricDefinitionFaults.Description = MetricDesc{
Help: "Returns the total number of faults by type",
Type: "gauge",
Unit: "",
}
var metrics []Metric
children := gjson.Get(data, "imdata.0.faultCountsWithDetails.children.#.faultTypeCounts")
children.ForEach(func(key, value gjson.Result) bool {
metric := Metric{}
metric.Labels = make(map[string]string)
metric.Labels["type"] = gjson.Get(value.String(), "attributes.type").Str
metric.Labels["severity"] = "crit"
metric.Value = p.toFloat(gjson.Get(value.String(), "attributes.crit").Str)
metrics = append(metrics, metric)
metric = Metric{}
metric.Labels = make(map[string]string)
metric.Labels["type"] = gjson.Get(value.String(), "attributes.type").Str
metric.Labels["severity"] = "maj"
metric.Value = p.toFloat(gjson.Get(value.String(), "attributes.maj").Str)
metrics = append(metrics, metric)
metric = Metric{}
metric.Labels = make(map[string]string)
metric.Labels["type"] = gjson.Get(value.String(), "attributes.type").Str
metric.Labels["severity"] = "minor"
metric.Value = p.toFloat(gjson.Get(value.String(), "attributes.minor").Str)
metrics = append(metrics, metric)
metric = Metric{}
metric.Labels = make(map[string]string)
metric.Labels["type"] = gjson.Get(value.String(), "attributes.type").Str
metric.Labels["severity"] = "warn"
metric.Value = p.toFloat(gjson.Get(value.String(), "attributes.warn").Str)
metrics = append(metrics, metric)
return true // keep iterating
})
metricDefinitionFaults.Metrics = metrics
metrics = []Metric{}
metricDefinitionAcked := MetricDefinition{}
metricDefinitionAcked.Name = "faults_acked"
metricDefinitionAcked.Description = MetricDesc{
Help: "Returns the total number of acknowledged faults by type",
Type: "gauge",
Unit: "",
}
children.ForEach(func(key, value gjson.Result) bool {
metric := Metric{}
metric.Labels = make(map[string]string)
metric.Labels["type"] = gjson.Get(value.String(), "attributes.type").Str
metric.Labels["severity"] = "crit"
metric.Value = p.toFloat(gjson.Get(value.String(), "attributes.critAcked").Str)
metrics = append(metrics, metric)
metric = Metric{}
metric.Labels = make(map[string]string)
metric.Labels["type"] = gjson.Get(value.String(), "attributes.type").Str
metric.Labels["severity"] = "maj"
metric.Value = p.toFloat(gjson.Get(value.String(), "attributes.majAcked").Str)
metrics = append(metrics, metric)
metric = Metric{}
metric.Labels = make(map[string]string)
metric.Labels["type"] = gjson.Get(value.String(), "attributes.type").Str
metric.Labels["severity"] = "minor"
metric.Value = p.toFloat(gjson.Get(value.String(), "attributes.minorAcked").Str)
metrics = append(metrics, metric)
metric = Metric{}
metric.Labels = make(map[string]string)
metric.Labels["type"] = gjson.Get(value.String(), "attributes.type").Str
metric.Labels["severity"] = "warn"
metric.Value = p.toFloat(gjson.Get(value.String(), "attributes.warnAcked").Str)
metrics = append(metrics, metric)
return true // keep iterating
})
metricDefinitionAcked.Metrics = metrics
ch <- []MetricDefinition{metricDefinitionFaults, metricDefinitionAcked}
}
func (p aciAPI) getAciName() (string, error) {
// Do not query aci name when query a node
if p.connection.Node != nil {
return "", nil
}
if p.connection.fabricConfig.AciName != "" {
return p.connection.fabricConfig.AciName, nil
}
data, err := p.connection.GetByClassQuery(p.ctx, "infraCont", "?query-target=self")
if err != nil {
return "", err
}
p.connection.fabricConfig.AciName = gjson.Get(data, "imdata.#.infraCont.attributes.fbDmNm").Array()[0].Str
if p.connection.fabricConfig.AciName != "" {
return p.connection.fabricConfig.AciName, nil
}
return "", fmt.Errorf("could not determine ACI name")
}
func (p aciAPI) configuredCompoundsMetrics(chall chan []MetricDefinition) {
var metricDefinitions []MetricDefinition
ch := make(chan []MetricDefinition)
for _, v := range p.configCompoundQueries {
go p.getCompoundMetrics(ch, v)
}
for range p.configCompoundQueries {
metricDefinitions = append(metricDefinitions, <-ch...)
}
chall <- metricDefinitions
}
func (p aciAPI) getCompoundMetrics(ch chan []MetricDefinition, v *CompoundClassQuery) {
var metricDefinitions []MetricDefinition
metricDefinition := MetricDefinition{}
metricDefinition.Name = v.Metrics[0].Name
metricDefinition.Description.Help = v.Metrics[0].Help
metricDefinition.Description.Type = v.Metrics[0].Type
metricDefinition.Description.Unit = v.Metrics[0].Unit
var metrics []Metric
for _, classLabel := range v.ClassNames {
metric := Metric{}
data, _ := p.connection.GetByClassQuery(p.ctx, classLabel.Class, classLabel.QueryParameter)
if classLabel.ValueName == "" {
metric.Value = p.toFloat(gjson.Get(data, fmt.Sprintf("imdata.0.%s", v.Metrics[0].ValueName)).Str)
} else {
metric.Value = p.toFloat(gjson.Get(data, fmt.Sprintf("imdata.0.%s", classLabel.ValueName)).Str)
}
metric.Labels = make(map[string]string)
metric.Labels[v.LabelName] = classLabel.Label
metrics = append(metrics, metric)
}
metricDefinition.Metrics = metrics
metricDefinitions = append(metricDefinitions, metricDefinition)
ch <- metricDefinitions
}
func (p aciAPI) configuredGroupMetrics(chall chan []MetricDefinition) {
var metricDefinitions []MetricDefinition
ch := make(chan []MetricDefinition)
for _, v := range p.configGroupQueries {
go p.getGroupClassMetrics(ch, *v)
}
for range p.configGroupQueries {
metricDefinitions = append(metricDefinitions, <-ch...)
}
chall <- metricDefinitions
}
func (p aciAPI) configuredClassMetrics(chall chan []MetricDefinition) {
var metricDefinitions []MetricDefinition
ch := make(chan []MetricDefinition)
for _, v := range p.configQueries {
go p.getClassMetrics(ch, v)
}
for range p.configQueries {
metricDefinitions = append(metricDefinitions, <-ch...)
}
chall <- metricDefinitions
}
func (p aciAPI) getGroupClassMetrics(ch chan []MetricDefinition, v GroupClassQuery) {
var metricDefinitions []MetricDefinition
metricDefinition := MetricDefinition{}
metricDefinition.Name = v.Name
metricDefinition.Description.Help = v.Help
metricDefinition.Description.Type = v.Type
metricDefinition.Description.Unit = v.Unit
var metrics []Metric
metricDefinition.Metrics = metrics
chsub := make(chan []MetricDefinition)
for _, query := range v.Queries {
// Need copy by value
queryValue := ClassQuery{
ClassName: query.ClassName,
QueryParameter: query.QueryParameter,
Metrics: query.Metrics,
Labels: query.Labels,
StaticLabels: query.StaticLabels,
}
go p.getClassMetrics(chsub, &queryValue)
}
for range v.Queries {
md := <-chsub
for _, vx := range md {
for _, vy := range vx.Metrics {
// Add any static labels
for _, v := range v.StaticLabels {
vy.Labels[v.Key] = v.Value
}
}
metricDefinition.Metrics = append(metricDefinition.Metrics, vx.Metrics...)
}
}
metricDefinitions = append(metricDefinitions, metricDefinition)
ch <- metricDefinitions
}
func (p aciAPI) getClassMetrics(ch chan []MetricDefinition, v *ClassQuery) {
var metricDefinitions []MetricDefinition
data, err := p.connection.GetByClassQuery(p.ctx, v.ClassName, v.QueryParameter)
if err != nil {
log.WithFields(log.Fields{
LogFieldRequestID: p.ctx.Value(LogFieldRequestID),
LogFieldFabric: fmt.Sprintf("%v", p.ctx.Value(LogFieldFabric)),
}).Error(fmt.Sprintf("%s not supported", v.ClassName), err)
ch <- nil
return
}
// For each metrics in the config
for _, mv := range v.Metrics {
metricDefinition := MetricDefinition{}
metricDefinition.Name = mv.Name
metricDefinition.Description.Help = mv.Help
metricDefinition.Description.Type = mv.Type
metricDefinition.Description.Unit = mv.Unit
var metrics []Metric
metrics = p.extractClassQueriesData(data, v, mv, metrics)
metricDefinition.Metrics = metrics
metricDefinitions = append(metricDefinitions, metricDefinition)
}
ch <- metricDefinitions
}
func (p aciAPI) extractClassQueriesData(data string, classQuery *ClassQuery, mv ConfigMetric, metrics []Metric) []Metric {
result := gjson.Get(data, "imdata")
result.ForEach(func(key, value gjson.Result) bool {
// Check if the value_name is in the format of fvAEPg.children.[healthInst].attributes.cur
match := arrayExtension.FindStringSubmatch(mv.ValueName)
if len(match) > 0 {
// match is a string array of parsed if the .[regexp]. is part of the string
// 0: the original string
// 1: stage1 all before .[
// 2: the child_name between []
// 3: stage2 - the rest after ].
var allChildren []map[string]interface{}
allChildrenJSON := gjson.Get(value.Raw, match[1])
err := json.Unmarshal([]byte(allChildrenJSON.Raw), &allChildren)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Info("Unmarshal json failed")
return false
}
for childIndex, child := range allChildren {
for childKey, childValue := range child {
// add a check if the childKey match the regexp of match[2]
re := regexpcache.MustCompile(match[2])
_, ok := childValue.(map[string]interface{})
if ok && re.Match([]byte(childKey)) {
metric := Metric{}
metric.Labels = make(map[string]string)
mvLocal := ConfigMetric{
Name: mv.Name,
ValueName: childKey + match[3],
ValueCalculation: mv.ValueCalculation,
Unit: mv.Unit,
Type: mv.Type,
Help: mv.Help,
ValueTransform: mv.ValueTransform,
ValueRegexTransform: mv.ValueRegexTransform,
}
// Add all high level labels
addLabels(classQuery.Labels, classQuery.StaticLabels, value.String(), metric)
// Add all [*] labels that will be relative to the child key
// Rewrite them from the relative path and add them as Config labels
var childLabels []ConfigLabels
for _, configLabel := range classQuery.Labels {
matchLabels := arrayExtension.FindStringSubmatch(configLabel.PropertyName)
//if len(matchLabels) >0 && matchLabels[2] == "*" {
if len(matchLabels) > 0 && re.Match([]byte(childKey)) {
re := regexpcache.MustCompile(matchLabels[2])
if re.Match([]byte(childKey)) {
localLabel := ConfigLabels{}
localLabel.PropertyName = childKey + matchLabels[3]
localLabel.Regex = configLabel.Regex
childLabels = append(childLabels, localLabel)
}
}
}
childJSON, _ := json.Marshal(allChildren[childIndex])
addLabels(childLabels, nil, string(childJSON), metric)
// Extract labels from child
for _, keyLabel := range childLabels {
if keyLabel.PropertyName == childKey {
re := regexpcache.MustCompile(keyLabel.Regex)
match := re.FindStringSubmatch(childKey)
if len(match) != 0 {
for i, expName := range re.SubexpNames() {
if i != 0 && expName != "" {
metric.Labels[expName] = match[i]
}
}
}
}
}
// extract the metrics value
value, err := p.toFloatTransform(gjson.Get(string(childJSON), mvLocal.ValueName).Str, mvLocal)
if err != nil {
continue
}
metric.Value = value
metrics = append(metrics, metric)
}
}
}
} else {
// Just plain Gjson without any [] expressions
metric := Metric{}
// find and parse all labels
metric.Labels = make(map[string]string)
addLabels(classQuery.Labels, classQuery.StaticLabels, value.String(), metric)
// get the metrics value
value, err := p.toFloatTransform(gjson.Get(value.String(), mv.ValueName).Str, mv)
if err != nil {
return false
}
metric.Value = value
metrics = append(metrics, metric)
}
return true
})
return metrics
}
func addLabels(v []ConfigLabels, sv []StaticLabels, json string, metric Metric) {
for _, lv := range v {
re := regexpcache.MustCompile(lv.Regex)
match := re.FindStringSubmatch(gjson.Get(json, lv.PropertyName).Str)
if len(match) != 0 {
for i, expName := range re.SubexpNames() {
if i != 0 && expName != "" {
metric.Labels[expName] = match[i]
}
}
}
}
// Add static labels
for _, slv := range sv {
metric.Labels[slv.Key] = slv.Value
}
}
func dumpMap(space string, m map[string]interface{}) {
for k, v := range m {
if mv, ok := v.(map[string]interface{}); ok {
fmt.Printf("{ \"%v\": \n", k)
dumpMap(space+"\t", mv)
fmt.Printf("}\n")
} else {
fmt.Printf("%v %v : %v\n", space, k, v)
}
}
}
func (p aciAPI) toRatio(value string) float64 {
rate, _ := strconv.ParseFloat(value, 64)
return rate / 100.0
}
func (p aciAPI) toFloat(value string) float64 {
rate, err := strconv.ParseFloat(value, 64)
if err != nil {
// if the value is a date time convert to timestamp
t, err := time.Parse(time.RFC3339, value)
if err != nil {
log.WithFields(log.Fields{
"value": value,
}).Info("could not convert value to float, will return 0.0 ")
return 0.0
}
rate = float64(t.Unix())
}
return rate
}
func (p aciAPI) toFloatTransform(value string, mv ConfigMetric) (float64, error) {
allValues := make([]string, 1)
allValueNames := make([]string, 1)
if len(mv.ValueRegexTransform) != 0 {
re, err := regexpcache.Compile(mv.ValueRegexTransform)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"name": mv.Name,
"value_name": mv.ValueName,
"value_regex_transformation": mv.ValueRegexTransform,
"value_calculation": mv.ValueCalculation,
}).Error("value_regex_transformation")
return 0.0, err
}
match := re.FindStringSubmatch(value)
if match == nil {
log.WithFields(log.Fields{
"error": "expected regex did not return any values",
"name": mv.Name,
"value_name": mv.ValueName,
"value_regex_transformation": mv.ValueRegexTransform,
"value_calculation": mv.ValueCalculation,
}).Error("value_regex_transformation")
return 0.0, errors.New("expected regex did not return any values")
}
allValues = make([]string, len(match)-1)
allValueNames = make([]string, len(match)-1)
if len(match) != 0 {
// Get all regex named groups names
for index, expName := range re.SubexpNames() {
if index != 0 {
allValueNames[index-1] = expName
}
}
// Get all group values
for index, entry := range match {
if index != 0 {
allValues[index-1] = entry
}
}
}
} else {
allValues[0] = value
}
// Do value transformations
if len(mv.ValueTransform) != 0 && len(allValues) != 0 {
for index, valueEntry := range allValues {
if val, ok := mv.ValueTransform[valueEntry]; ok {
allValues[index] = fmt.Sprintf("%f", val)
}
}
}
allFloats := make([]float64, len(allValues))
for index, entry := range allValues {
allFloats[index] = p.toFloat(entry)
}
if mv.ValueCalculation != "" && len(allValues) != 0 {
expression, _ := govaluate.NewEvaluableExpression(mv.ValueCalculation)
parameters := make(map[string]interface{}, len(allFloats))
if len(allFloats) == 1 && allValueNames[0] == "" {
// Manage single group where not a named group
parameters["value"] = allFloats[0]
} else {
// Manage multi groups
for index, valueEntry := range allFloats {
if allValueNames[index] == "" {
// If not a named group default to "value" postfix with group index
parameters[fmt.Sprintf("value%d", index+1)] = valueEntry
} else {
// If a named group
parameters[fmt.Sprintf("%s", allValueNames[index])] = valueEntry
}
}
}
result, err := expression.Evaluate(parameters)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"name": mv.Name,
"value_name": mv.ValueName,
"value_regex_transformation": mv.ValueRegexTransform,
"value_calculation": mv.ValueCalculation,
}).Error("value_calculation")
return 0.0, err
}
allFloats[0] = result.(float64)
}
return allFloats[0], nil
}