-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathzapiperf.go
1794 lines (1553 loc) · 50.1 KB
/
zapiperf.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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright NetApp Inc, 2021 All rights reserved
ZapiPerf collects and processes metrics from the "perf" APIs of the
ZAPI protocol. This collector inherits some methods and fields of
the Zapi collector (as they use the same protocol). However,
ZapiPerf calculates final metric values from the deltas of two
consecutive polls.
The exact formula of doing these calculations, depends on the property
of each counter and some counters require a "base-counter" additionally.
Counter properties and other metadata are fetched from the target system
during PollCounter() making the collector ONTAP-version independent.
The collector maintains a cache of instances, updated periodically as well,
during PollInstance().
The source code prioritizes performance over simplicity/readability.
Additionally, some objects (e.g. workloads) come with twists that
force the collector to do acrobatics. Don't expect to easily
comprehend what comes below.
*/
package zapiperf
import (
"context"
"errors"
"github.com/netapp/harvest/v2/cmd/collectors/zapiperf/plugins/disk"
"github.com/netapp/harvest/v2/cmd/collectors/zapiperf/plugins/externalserviceoperation"
"github.com/netapp/harvest/v2/cmd/collectors/zapiperf/plugins/fabricpool"
"github.com/netapp/harvest/v2/cmd/collectors/zapiperf/plugins/fcp"
"github.com/netapp/harvest/v2/cmd/collectors/zapiperf/plugins/fcvi"
"github.com/netapp/harvest/v2/cmd/collectors/zapiperf/plugins/flexcache"
"github.com/netapp/harvest/v2/cmd/collectors/zapiperf/plugins/headroom"
"github.com/netapp/harvest/v2/cmd/collectors/zapiperf/plugins/nic"
"github.com/netapp/harvest/v2/cmd/collectors/zapiperf/plugins/volume"
"github.com/netapp/harvest/v2/cmd/collectors/zapiperf/plugins/volumetag"
"github.com/netapp/harvest/v2/cmd/collectors/zapiperf/plugins/vscan"
"github.com/netapp/harvest/v2/cmd/poller/collector"
"github.com/netapp/harvest/v2/cmd/poller/plugin"
"github.com/netapp/harvest/v2/pkg/conf"
"github.com/netapp/harvest/v2/pkg/errs"
"github.com/netapp/harvest/v2/pkg/matrix"
"github.com/netapp/harvest/v2/pkg/set"
"github.com/netapp/harvest/v2/pkg/slogx"
"github.com/netapp/harvest/v2/pkg/tree/node"
"log/slog"
"maps"
"slices"
"strconv"
"strings"
"time"
zapi "github.com/netapp/harvest/v2/cmd/collectors/zapi/collector"
)
const (
// default parameter values
instanceKey = "uuid"
batchSize = 500
latencyIoReqd = 10
keyToken = "?#"
// objects that need special handling
objWorkload = "workload"
objWorkloadDetail = "workload_detail"
objWorkloadVolume = "workload_volume"
objWorkloadDetailVolume = "workload_detail_volume"
objWorkloadClass = "user_defined|system_defined"
objWorkloadVolumeClass = "autovolume"
BILLION = 1_000_000_000
timestampMetricName = "timestamp"
)
var workloadDetailMetrics = []string{"resource_latency"}
type ZapiPerf struct {
*zapi.Zapi // provides: AbstractCollector, Client, Object, Query, TemplateFn, TemplateType
object string
filter string
batchSize int
latencyIoReqd int
instanceKeys []string
instanceLabels map[string]string
histogramLabels map[string][]string
scalarCounters []string
qosLabels map[string]string
isCacheEmpty bool
keyName string
keyNameIndex int
testFilePath string // Used only from unit test
recordsToSave int // Number of records to save when using the recorder
pollDataCalls int
pollInstanceCalls int
}
func init() {
plugin.RegisterModule(&ZapiPerf{})
}
func (z *ZapiPerf) HarvestModule() plugin.ModuleInfo {
return plugin.ModuleInfo{
ID: "harvest.collector.zapiperf",
New: func() plugin.Module { return new(ZapiPerf) },
}
}
func (z *ZapiPerf) Init(a *collector.AbstractCollector) error {
z.Zapi = &zapi.Zapi{AbstractCollector: a}
if err := z.InitVars(); err != nil {
return err
}
// Invoke generic initializer
// this will load Schedule, initialize data and metadata Matrices
if err := collector.Init(z); err != nil {
return err
}
if err := z.InitMatrix(); err != nil {
return err
}
if err := z.InitCache(); err != nil {
return err
}
z.InitQOS()
z.recordsToSave = collector.RecordKeepLast(z.Params, z.Logger)
z.Logger.Debug("initialized")
return nil
}
func (z *ZapiPerf) InitQOS() {
counters := z.Params.GetChildS("counters")
if counters != nil {
refine := counters.GetChildS("refine")
if refine != nil {
withServiceLatency := refine.GetChildContentS("with_service_latency")
if withServiceLatency != "false" {
workloadDetailMetrics = append(workloadDetailMetrics, "service_time_latency")
}
}
}
}
func (z *ZapiPerf) LoadPlugin(kind string, abc *plugin.AbstractPlugin) plugin.Plugin {
switch kind {
case "Nic":
return nic.New(abc)
case "Fcp":
return fcp.New(abc)
case "FabricPool":
return fabricpool.New(abc)
case "Headroom":
return headroom.New(abc)
case "Volume":
return volume.New(abc)
case "VolumeTag":
return volumetag.New(abc)
case "Vscan":
return vscan.New(abc)
case "Disk":
return disk.New(abc)
case "ExternalServiceOperation":
return externalserviceoperation.New(abc)
case "FCVI":
return fcvi.New(abc)
case "FlexCache":
return flexcache.New(abc)
default:
z.Logger.Info("no zapiPerf plugin found for %s", slog.String("kind", kind))
}
return nil
}
func (z *ZapiPerf) InitCache() error {
z.histogramLabels = make(map[string][]string)
z.instanceLabels = make(map[string]string)
z.instanceKeys = z.loadParamArray("instance_key", instanceKey)
z.filter = z.loadFilter()
z.batchSize = z.loadParamInt("batch_size", batchSize)
z.latencyIoReqd = z.loadParamInt("latency_io_reqd", latencyIoReqd)
z.isCacheEmpty = true
z.object = z.loadParamStr("object", "")
z.keyName, z.keyNameIndex = z.initKeyName()
// hack to override from AbstractCollector
// @TODO need cleaner solution
if z.object == "" {
z.object = z.Object
}
z.Matrix[z.Object].Object = z.object
z.Logger.Debug("->", slog.String("z.Object", z.object), slog.String("z.object", z.object))
// Add metadata metric for skips/numPartials
_, _ = z.Metadata.NewMetricUint64("skips")
_, _ = z.Metadata.NewMetricUint64("numPartials")
return nil
}
func (z *ZapiPerf) initKeyName() (string, int) {
// determine what will serve as instance key (either "uuid" or "instance")
keyName := "instance-uuid"
keyNameIndex := 0
// either instance-uuid or instance can be passed as key not both
for i, k := range z.instanceKeys {
if k == "uuid" {
keyName = "instance-uuid"
keyNameIndex = i
break
} else if k == "name" {
keyName = "instance"
keyNameIndex = i
break
}
}
return keyName, keyNameIndex
}
// load a string parameter or use defaultValue
func (z *ZapiPerf) loadParamStr(name, defaultValue string) string {
var x string
if x = z.Params.GetChildContentS(name); x != "" {
z.Logger.Debug("using", slog.String(name, x))
return x
}
z.Logger.Debug("using", slog.String(name, defaultValue))
return defaultValue
}
func (z *ZapiPerf) loadFilter() string {
counters := z.Params.GetChildS("counters")
if counters != nil {
if x := counters.GetChildS("filter"); x != nil {
filter := strings.Join(x.GetAllChildContentS(), ",")
return filter
}
}
return ""
}
// load a string parameter or use defaultValue
func (z *ZapiPerf) loadParamArray(name, defaultValue string) []string {
if v := z.Params.GetChildContentS(name); v != "" {
z.Logger.Debug("", slog.String("name", name), slog.String("value", v))
return []string{v}
}
p := z.Params.GetChildS(name)
if p != nil {
if v := p.GetAllChildContentS(); v != nil {
z.Logger.Debug("", slog.String("name", name), slog.Any("values", v))
return v
}
}
z.Logger.Debug("", slog.String("name", name), slog.String("defaultValue", defaultValue))
return []string{defaultValue}
}
// load workload_class or use defaultValue
func (z *ZapiPerf) loadWorkloadClassQuery(defaultValue string) string {
var x *node.Node
name := "workload_class"
if x = z.Params.GetChildS(name); x != nil {
v := x.GetAllChildContentS()
if len(v) == 0 {
z.Logger.Debug(
"",
slog.String("name", name),
slog.String("defaultValue", defaultValue),
)
return defaultValue
}
s := strings.Join(v, "|")
z.Logger.Debug("", slog.String("name", name), slog.String("value", s))
return s
}
z.Logger.Debug("", slog.String("name", name), slog.String("defaultValue", defaultValue))
return defaultValue
}
func (z *ZapiPerf) updateWorkloadQuery(query *node.Node) {
// filter -> workload-class takes precedence over workload_class param at root level
// filter -> is-constituent takes precedence over refine -> with_constituents
workloadClass := ""
isConstituent := ""
counters := z.Params.GetChildS("counters")
if counters != nil {
filter := counters.GetChildS("filter")
if filter != nil {
for _, n := range filter.GetChildren() {
name := n.GetNameS()
content := n.GetContentS()
query.NewChildS(name, content)
if name == "workload-class" {
workloadClass = content
}
if name == "is-constituent" {
isConstituent = content
}
}
}
}
if workloadClass == "" {
var workloadClassQuery string
if z.Query == objWorkloadVolume || z.Query == objWorkloadDetailVolume {
workloadClassQuery = z.loadWorkloadClassQuery(objWorkloadVolumeClass)
} else {
workloadClassQuery = z.loadWorkloadClassQuery(objWorkloadClass)
}
query.NewChildS("workload-class", workloadClassQuery)
}
if isConstituent == "" {
if counters != nil {
refine := counters.GetChildS("refine")
if refine != nil {
isConstituent = refine.GetChildContentS("with_constituents")
if isConstituent == "false" {
query.NewChildS("is-constituent", isConstituent)
}
}
}
}
}
// load an int parameter or use defaultValue
func (z *ZapiPerf) loadParamInt(name string, defaultValue int) int {
var (
x string
n int
e error
)
if x = z.Params.GetChildContentS(name); x != "" {
if n, e = strconv.Atoi(x); e == nil {
z.Logger.Debug("using", slog.String("name", name), slog.Int("value", n))
return n
}
z.Logger.Warn("invalid parameter (expected integer)", slog.String("name", name), slog.String("value", x))
}
z.Logger.Debug("using", slog.String("name", name), slog.Int("value", defaultValue))
return defaultValue
}
func (z *ZapiPerf) isPartialAggregation(instance *node.Node) bool {
aggregation := instance.GetChildS("aggregation")
if aggregation != nil {
aggregationData := aggregation.GetChildS("aggregation-data")
if aggregationData != nil {
result := aggregationData.GetChildS("result")
if result != nil {
r := result.GetContentS()
return r == "partial_aggregation"
}
}
}
return false
}
// PollData updates the data cache of the collector. During first poll, no data will
// be emitted. Afterward, final metric values will be calculated from previous poll.
func (z *ZapiPerf) PollData() (map[string]*matrix.Matrix, error) {
var (
instanceKeys []string
err error
skips int
numPartials uint64
apiT time.Duration
parseT time.Duration
)
prevMat := z.Matrix[z.Object]
z.Client.Metadata.Reset()
// clone matrix without numeric data and non-exportable all instances
curMat := prevMat.Clone(matrix.With{Data: false, Metrics: true, Instances: true, ExportInstances: false})
curMat.Reset()
timestamp := curMat.GetMetric(timestampMetricName)
if timestamp == nil {
return nil, errs.New(errs.ErrConfig, "missing timestamp metric") // @TODO errconfig??
}
// for updating metadata
count := uint64(0)
batchCount := 0
// list of instance keys (instance names or uuids) for which
// we will request counter data
if z.Query == objWorkloadDetail || z.Query == objWorkloadDetailVolume {
resourceMap := z.Params.GetChildS("resource_map")
if resourceMap == nil {
return nil, errs.New(errs.ErrMissingParam, "resource_map")
}
instanceKeys = make([]string, 0)
for _, layer := range resourceMap.GetAllChildNamesS() {
for key := range prevMat.GetInstances() {
instanceKeys = append(instanceKeys, key+"."+layer)
}
}
} else {
instanceKeys = curMat.GetInstanceKeys()
}
// build ZAPI request
request := node.NewXMLS("perf-object-get-instances")
request.NewChildS("objectname", z.Query)
// load requested counters (metrics + labels)
requestCounters := request.NewChildS("counters", "")
// load scalar metrics
// Sort the counters and instanceKeys so they are deterministic
for _, key := range z.scalarCounters {
requestCounters.NewChildS("counter", key)
}
// load histograms
sortedHistogramKeys := slices.Sorted(maps.Keys(z.histogramLabels))
for _, key := range sortedHistogramKeys {
requestCounters.NewChildS("counter", key)
}
// load instance labels
sortedLabels := slices.Sorted(maps.Keys(z.instanceLabels))
for _, key := range sortedLabels {
requestCounters.NewChildS("counter", key)
}
slices.Sort(instanceKeys)
// batch indices
startIndex := 0
endIndex := 0
for endIndex < len(instanceKeys) {
// update batch indices
endIndex += z.batchSize
// In case of unit test, for loop should run once
if z.testFilePath != "" {
endIndex = len(instanceKeys)
}
if endIndex > len(instanceKeys) {
endIndex = len(instanceKeys)
}
request.PopChildS(z.keyName + "s")
requestInstances := request.NewChildS(z.keyName+"s", "")
addedKeys := make(map[string]bool)
for _, key := range instanceKeys[startIndex:endIndex] {
if len(z.instanceKeys) == 1 {
requestInstances.NewChildS(z.keyName, key)
} else {
if strings.Contains(key, keyToken) {
v := strings.Split(key, keyToken)
if z.keyNameIndex < len(v) {
key = v[z.keyNameIndex]
}
}
// Avoid adding duplicate keys. It can happen for flex-cache case
if !addedKeys[key] {
requestInstances.NewChildS(z.keyName, key)
addedKeys[key] = true
}
}
}
startIndex = endIndex
if err = z.Client.BuildRequest(request); err != nil {
z.Logger.Error("Build request", slogx.Err(err), slog.String("objectname", z.Query))
return nil, err
}
z.pollDataCalls++
if z.pollDataCalls >= z.recordsToSave {
z.pollDataCalls = 0
}
var headers map[string]string
poller, err := conf.PollerNamed(z.Options.Poller)
if err != nil {
slog.Error("failed to find poller", slogx.Err(err), slog.String("poller", z.Options.Poller))
}
if poller.IsRecording() {
headers = map[string]string{
"From": strconv.Itoa(z.pollDataCalls),
}
}
response, rd, pd, err := z.Client.InvokeWithTimers(z.testFilePath, headers)
if err != nil {
errMsg := strings.ToLower(err.Error())
// if ONTAP complains about batch size, use a smaller batch size
if strings.Contains(errMsg, "resource limit exceeded") && z.batchSize > 100 {
z.Logger.Error(
"Changed batch_size",
slogx.Err(err),
slog.Int("oldBatchSize", z.batchSize),
slog.Int("newBatchSize", z.batchSize-100),
)
z.batchSize -= 100
return nil, nil
} else if strings.Contains(errMsg, "timeout: operation") && z.batchSize > 100 {
z.Logger.Error(
"ONTAP timeout, reducing batch size",
slogx.Err(err),
slog.Int("oldBatchSize", z.batchSize),
slog.Int("newBatchSize", z.batchSize-100),
)
z.batchSize -= 100
return nil, nil
}
return nil, err
}
apiT += rd
parseT += pd
batchCount++
// fetch instances
instances := response.GetChildS("instances")
if instances == nil || len(instances.GetChildren()) == 0 {
break
}
// timestamp for batch instances
// ignore timestamp from ZAPI which is always integer
// we want float, since our poll interval can be a float
ts := float64(time.Now().UnixNano()) / BILLION
for instIndex, i := range instances.GetChildren() {
key := z.buildKeyValue(i, z.instanceKeys)
var layer = "" // latency layer (resource) for workloads
// special case for these two objects
// we need to process each latency layer for each instance/counter
if z.Query == objWorkloadDetail || z.Query == objWorkloadDetailVolume {
if x := strings.Split(key, "."); len(x) == 2 {
key = x[0]
layer = x[1]
} else {
z.Logger.Warn("Instance key has unexpected format", slog.String("key", key))
continue
}
for _, wm := range workloadDetailMetrics {
mLayer := layer + wm
if l := curMat.GetMetric(mLayer); l == nil {
z.Logger.Warn("metric missing in cache", slog.String("layer", mLayer))
continue
}
}
}
if key == "" {
if z.Logger.Enabled(context.Background(), slog.LevelDebug) {
z.Logger.Debug(
"Skip instance, key is empty",
slog.Any("instanceKey", z.instanceKeys),
slog.String("name", i.GetChildContentS("name")),
slog.String("uuid", i.GetChildContentS("uuid")),
)
}
continue
}
instance := curMat.GetInstance(key)
if instance == nil {
z.Logger.Debug("Skip instance key, not found in cache", slog.String("key", key))
continue
}
if z.isPartialAggregation(i) {
instance.SetPartial(true)
instance.SetExportable(false)
numPartials++
} else {
instance.SetPartial(false)
instance.SetExportable(true)
}
counters := i.GetChildS("counters")
if counters == nil {
z.Logger.Debug("Skip instance key, no data counters", slog.String("key", key))
continue
}
// add batch timestamp as custom counter
if err := timestamp.SetValueFloat64(instance, ts); err != nil {
z.Logger.Error("set timestamp value", slogx.Err(err))
}
for _, cnt := range counters.GetChildren() {
name := cnt.GetChildContentS("name")
value := cnt.GetChildContentS("value")
// validation
if name == "" || value == "" {
// skip counters with empty value or name
continue
}
// ZAPI counter for us is either instance label (string)
// or numeric metric (scalar or histogram)
// store as instance label
if display, has := z.instanceLabels[name]; has {
instance.SetLabel(display, value)
continue
}
// store as array counter / histogram
if labels, has := z.histogramLabels[name]; has {
values := strings.Split(value, ",")
if len(labels) != len(values) {
// warn & skip
z.Logger.Error(
"Histogram labels don't match parsed values",
slog.String("labels", name),
slog.String("value", value),
slog.Int("instIndex", instIndex),
)
continue
}
for i, label := range labels {
if metric := curMat.GetMetric(name + "." + label); metric != nil {
if err = metric.SetValueString(instance, values[i]); err != nil {
z.Logger.Error(
"Set histogram value failed",
slogx.Err(err),
slog.String("name", name),
slog.String("label", label),
slog.String("value", values[i]),
slog.Int("instIndex", instIndex),
)
} else {
count++
}
} else {
z.Logger.Warn(
"Histogram name. Label not in cache",
slog.String("name", name),
slog.String("label", label),
slog.String("value", value),
slog.Int("instIndex", instIndex),
)
}
}
continue
}
// special case for workload_detail
if z.Query == objWorkloadDetail || z.Query == objWorkloadDetailVolume {
for _, wm := range workloadDetailMetrics {
wMetric := curMat.GetMetric(layer + wm)
switch {
case wm == "resource_latency" && (name == "wait_time" || name == "service_time"):
if err := wMetric.AddValueString(instance, value); err != nil {
z.Logger.Error(
"Add resource_latency failed",
slogx.Err(err),
slog.String("name", name),
slog.String("value", value),
slog.Int("instIndex", instIndex),
)
} else {
count++
}
continue
case wm == "service_time_latency" && name == "service_time":
if err = wMetric.SetValueString(instance, value); err != nil {
z.Logger.Error(
"Add service_time_latency failed",
slogx.Err(err),
slog.String("name", name),
slog.String("value", value),
slog.Int("instIndex", instIndex),
)
} else {
count++
}
case wm == "wait_time_latency" && name == "wait_time":
if err = wMetric.SetValueString(instance, value); err != nil {
z.Logger.Error(
"Add wait_time_latency failed",
slogx.Err(err),
slog.String("name", name),
slog.String("value", value),
slog.Int("instIndex", instIndex),
)
} else {
count++
}
}
}
continue
}
// store as scalar metric
if metric := curMat.GetMetric(name); metric != nil {
if err = metric.SetValueString(instance, value); err != nil {
z.Logger.Error(
"Set metric failed",
slogx.Err(err),
slog.String("name", name),
slog.String("value", value),
slog.Int("instIndex", instIndex),
)
} else {
count++
}
continue
}
z.Logger.Warn(
"Counter not in cache",
slog.Int("instIndex", instIndex),
slog.String("name", name),
slog.String("value", value),
)
} // end loop over counters
} // end loop over instances
} // end batch request
if z.Query == objWorkloadDetail || z.Query == objWorkloadDetailVolume {
if rd, pd, err := z.getParentOpsCounters(curMat, z.keyName); err == nil {
apiT += rd
parseT += pd
} else {
// no point to continue as we can't calculate the other counters
return nil, err
}
}
// update metadata
_ = z.Metadata.LazySetValueInt64("api_time", "data", apiT.Microseconds())
_ = z.Metadata.LazySetValueInt64("parse_time", "data", parseT.Microseconds())
_ = z.Metadata.LazySetValueUint64("metrics", "data", count)
_ = z.Metadata.LazySetValueUint64("instances", "data", uint64(len(instanceKeys)))
_ = z.Metadata.LazySetValueUint64("bytesRx", "data", z.Client.Metadata.BytesRx)
_ = z.Metadata.LazySetValueUint64("numCalls", "data", z.Client.Metadata.NumCalls)
_ = z.Metadata.LazySetValueUint64("numPartials", "data", numPartials)
z.AddCollectCount(count)
// skip calculating from delta if no data from previous poll
if z.isCacheEmpty {
z.Logger.Debug("skip postprocessing until next poll (previous cache empty)")
z.Matrix[z.Object] = curMat
z.isCacheEmpty = false
return nil, nil
}
calcStart := time.Now()
// cache raw data for next poll
cachedData := curMat.Clone(matrix.With{Data: true, Metrics: true, Instances: true, ExportInstances: true, PartialInstances: true}) // @TODO implement copy data
// order metrics, such that those requiring base counters are processed last
orderedMetrics := make([]*matrix.Metric, 0, len(curMat.GetMetrics()))
orderedKeys := make([]string, 0, len(orderedMetrics))
for key, metric := range curMat.GetMetrics() {
if metric.GetComment() == "" && metric.Buckets() == nil { // does not require base counter
orderedMetrics = append(orderedMetrics, metric)
orderedKeys = append(orderedKeys, key)
}
}
for key, metric := range curMat.GetMetrics() {
if metric.GetComment() != "" && metric.Buckets() == nil { // requires base counter
orderedMetrics = append(orderedMetrics, metric)
orderedKeys = append(orderedKeys, key)
}
}
// calculate timestamp delta first since many counters require it for postprocessing.
// Timestamp has "raw" property, so it isn't post-processed automatically
if _, err = curMat.Delta(timestampMetricName, prevMat, cachedData, z.Logger); err != nil {
z.Logger.Error("(timestamp) calculate delta:", slogx.Err(err))
// @TODO terminate since other counters will be incorrect
}
var base *matrix.Metric
var totalSkips int
for i, metric := range orderedMetrics {
property := metric.GetProperty()
key := orderedKeys[i]
// RAW - submit without post-processing
if property == "raw" {
continue
}
// all other properties - first calculate delta
if skips, err = curMat.Delta(key, prevMat, cachedData, z.Logger); err != nil {
z.Logger.Error("Calculate delta", slogx.Err(err), slog.String("key", key))
continue
}
totalSkips += skips
// DELTA - subtract previous value from current
if property == "delta" {
// already done
continue
}
// RATE - delta, normalized by elapsed time
if property == "rate" {
// defer calculation, so we can first calculate averages/percents
// Note: calculating rate before averages are averages/percentages are calculated
// used to be a bug in Harvest 2.0 (Alpha, RC1, RC2) resulting in very high latency values
continue
}
// For the next two properties we need base counters
// We assume that delta of base counters is already calculated
// (name of base counter is stored as Comment)
if base = curMat.GetMetric(metric.GetComment()); base == nil {
if z.Query == objWorkloadDetail || z.Query == objWorkloadDetailVolume {
// The workload detail generates metrics at the resource level. The 'service_time' and 'wait_time' metrics are used as raw values for these resource-level metrics. Their denominator, 'visits', is not collected; therefore, a check is added here to prevent warnings.
// There is no need to cook these metrics further.
if key == "service_time" || key == "wait_time" {
continue
}
}
z.Logger.Warn(
"Base counter missing",
slog.String("key", key),
slog.String("property", property),
slog.String("comment", metric.GetComment()),
)
continue
}
// remaining properties: average and percent
//
// AVERAGE - delta, divided by base-counter delta
//
// PERCENT - average * 100
// special case for latency counter: apply minimum number of iops as threshold
if property == "average" || property == "percent" {
if strings.HasSuffix(metric.GetName(), "latency") {
skips, err = curMat.DivideWithThreshold(key, metric.GetComment(), z.latencyIoReqd, cachedData, prevMat, timestampMetricName, z.Logger)
} else {
skips, err = curMat.Divide(key, metric.GetComment())
}
if err != nil {
z.Logger.Error("Division by base", slogx.Err(err), slog.String("key", key))
}
totalSkips += skips
if property == "average" {
continue
}
}
if property == "percent" {
if skips, err = curMat.MultiplyByScalar(key, 100); err != nil {
z.Logger.Error("Multiply by scalar", slogx.Err(err), slog.String("key", key))
} else {
totalSkips += skips
}
continue
}
z.Logger.Error(
"Unknown property",
slogx.Err(err),
slog.String("key", key),
slog.String("property", property),
)
}
// calculate rates (which we deferred to calculate averages/percents first)
for i, metric := range orderedMetrics {
if metric.GetProperty() == "rate" {
if skips, err = curMat.Divide(orderedKeys[i], timestampMetricName); err != nil {
z.Logger.Error(
"Calculate rate",
slogx.Err(err),
slog.Int("i", i),
slog.String("key", orderedKeys[i]),
)
continue
}
totalSkips += skips
}
}
calcD := time.Since(calcStart)
_ = z.Metadata.LazySetValueInt64("calc_time", "data", calcD.Microseconds())
_ = z.Metadata.LazySetValueUint64("skips", "data", uint64(totalSkips)) //nolint:gosec
// store cache for next poll
z.Matrix[z.Object] = cachedData
newDataMap := make(map[string]*matrix.Matrix)
newDataMap[z.Object] = curMat
return newDataMap, nil
}
// Poll counter "ops" of the related/parent object, required for objects
// workload_detail and workload_detail_volume. This counter is already
// collected by the other ZapiPerf collectors, so this poll is redundant
// (until we implement some sort of inter-collector communication).
func (z *ZapiPerf) getParentOpsCounters(data *matrix.Matrix, keyAttr string) (time.Duration, time.Duration, error) {
var (
ops *matrix.Metric
object string
instanceKeys []string
apiT, parseT time.Duration
)
if z.Query == objWorkloadDetail {
object = objWorkload
} else {
object = objWorkloadVolume
}
z.Logger.Debug(
"starting redundancy poll for ops from parent object",
slog.String("query", z.Query),
slog.String("object", object),
)
apiT = 0 * time.Second
parseT = 0 * time.Second
if ops = data.GetMetric("ops"); ops == nil {
z.Logger.Error("ops counter not found in cache")
return apiT, parseT, errs.New(errs.ErrMissingParam, "counter ops")
}
instanceKeys = data.GetInstanceKeys()
slices.Sort(instanceKeys)
// build ZAPI request
request := node.NewXMLS("perf-object-get-instances")
request.NewChildS("objectname", object)
requestCounters := request.NewChildS("counters", "")
requestCounters.NewChildS("counter", "ops")
// batch indices
startIndex := 0
endIndex := 0
count := 0
for endIndex < len(instanceKeys) {
// update batch indices
endIndex += z.batchSize
if endIndex > len(instanceKeys) {
endIndex = len(instanceKeys)
}
z.Logger.Debug(
"starting batch poll for instances",
slog.Int("startIndex", startIndex),
slog.Int("endIndex", endIndex),
)
request.PopChildS(keyAttr + "s")
requestInstances := request.NewChildS(keyAttr+"s", "")
for _, key := range instanceKeys[startIndex:endIndex] {