-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmetrics.go
1577 lines (1241 loc) · 40 KB
/
metrics.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
package speed
import (
"fmt"
"math"
"strconv"
"sync"
"time"
histogram "github.com/HdrHistogram/hdrhistogram-go"
"github.com/pkg/errors"
"github.com/performancecopilot/speed/v4/bytewriter"
)
// MetricType is an enumerated type representing all valid types for a metric.
type MetricType int32
// Possible values for a MetricType.
const (
Int32Type MetricType = iota
Uint32Type
Int64Type
Uint64Type
FloatType
DoubleType
StringType
)
//go:generate stringer -type=MetricType
func (m MetricType) isCompatibleInt(val int) bool {
v := int64(val)
switch m {
case Int32Type:
return v >= math.MinInt32 && v <= math.MaxInt32
case Int64Type:
return true
case Uint32Type:
return v >= 0 && v <= math.MaxUint32
case Uint64Type:
return v >= 0
}
return false
}
func (m MetricType) isCompatibleUint(val uint) bool {
switch {
case val <= math.MaxUint32:
return m == Uint32Type || m == Uint64Type
default:
return m == Uint64Type
}
}
func (m MetricType) isCompatibleFloat(val float64) bool {
switch {
case val >= -math.MaxFloat32 && val <= math.MaxFloat32:
return m == FloatType || m == DoubleType
default:
return m == DoubleType
}
}
// IsCompatible checks if the passed value is compatible with the current MetricType.
func (m MetricType) IsCompatible(val interface{}) bool {
switch v := val.(type) {
case int:
return m.isCompatibleInt(v)
case int32:
return m == Int32Type
case int64:
return m == Int64Type
case uint:
return m.isCompatibleUint(v)
case uint32:
return m == Uint32Type
case uint64:
return m == Uint64Type
case float32:
return m == FloatType
case float64:
return m.isCompatibleFloat(v)
case string:
return m == StringType
}
return false
}
// resolveInt will resolve an int to one of the 4 compatible types.
func (m MetricType) resolveInt(val interface{}) interface{} {
if vi, isInt := val.(int); isInt {
switch m {
case Int64Type:
return int64(vi)
case Uint32Type:
return uint32(vi)
case Uint64Type:
return uint64(vi)
}
return int32(val.(int))
}
if vui, isUint := val.(uint); isUint {
if m == Uint64Type {
return uint64(vui)
}
return uint32(vui)
}
return val
}
// resolveFloat will resolve a float64 to one of the 2 compatible types.
func (m MetricType) resolveFloat(val interface{}) interface{} {
_, isFloat64 := val.(float64)
if isFloat64 && m == FloatType {
return float32(val.(float64))
}
return val
}
func (m MetricType) resolve(val interface{}) interface{} {
val = m.resolveInt(val)
val = m.resolveFloat(val)
return val
}
///////////////////////////////////////////////////////////////////////////////
// MetricUnit defines the interface for a unit type for speed.
type MetricUnit interface {
fmt.Stringer
// return 32 bit PMAPI representation for the unit
// see: https://github.com/performancecopilot/pcp/blob/main/src/include/pcp/pmapi.h#L61-L101
PMAPI() uint32
// add a space unit to the current unit at a specific dimension
Space(SpaceUnit, int8) MetricUnit
// add a time unit to the current unit at a specific dimension
Time(TimeUnit, int8) MetricUnit
// add a count unit to the current unit at a specific dimension
Count(CountUnit, int8) MetricUnit
}
// internal struct for supporting composite units,
// based on the implementation inside hornet
//
// https://docs.rs/hornet/0.1.0/src/hornet/client/metric/mod.rs.html#327
type metricUnit struct {
repr uint32
}
// NewMetricUnit returns a new object for initialization
func NewMetricUnit() MetricUnit {
return &metricUnit{}
}
func (m *metricUnit) PMAPI() uint32 { return m.repr }
// https://docs.rs/hornet/0.1.0/src/hornet/client/metric/mod.rs.html#375
func (m *metricUnit) Space(s SpaceUnit, dimension int8) MetricUnit {
if dimension < -8 || dimension > 7 {
panic("dimension has to be between -8 and 7 inclusive")
}
m.repr |= uint32(s)
m.repr |= (uint32(dimension) & 0xF) << 28
return m
}
// https://docs.rs/hornet/0.1.0/src/hornet/client/metric/mod.rs.html#383
func (m *metricUnit) Time(t TimeUnit, dimension int8) MetricUnit {
if dimension < -8 || dimension > 7 {
panic("dimension has to be between -8 and 7 inclusive")
}
m.repr |= uint32(t)
m.repr |= (uint32(dimension) & 0xF) << 24
return m
}
// https://docs.rs/hornet/0.1.0/src/hornet/client/metric/mod.rs.html#391
func (m *metricUnit) Count(c CountUnit, dimension int8) MetricUnit {
if dimension < -8 || dimension > 7 {
panic("dimension has to be between -8 and 7 inclusive")
}
m.repr |= uint32(c)
m.repr |= (uint32(dimension) & 0xF) << 20
return m
}
// https://docs.rs/hornet/0.1.0/src/hornet/client/metric/mod.rs.html#410
func (m *metricUnit) SpaceDim() int8 {
return int8(int32(m.repr) >> 28)
}
// https://docs.rs/hornet/0.1.0/src/hornet/client/metric/mod.rs.html#398
func (m *metricUnit) SpaceScale() SpaceUnit {
d := m.SpaceDim()
if d == 0 {
panic("no space scale on unit")
}
return SpaceUnit(1<<28 | (uint32((m.repr>>16)&0xF))<<16)
}
// https://docs.rs/hornet/0.1.0/src/hornet/client/metric/mod.rs.html#410
func (m *metricUnit) TimeDim() int8 {
return int8(int32(m.repr<<4) >> 28)
}
// https://docs.rs/hornet/0.1.0/src/hornet/client/metric/mod.rs.html#398
func (m *metricUnit) TimeScale() TimeUnit {
d := m.TimeDim()
if d == 0 {
panic("no time scale on unit")
}
return TimeUnit(1<<24 | (uint32((m.repr>>12)&0xF))<<12)
}
// https://docs.rs/hornet/0.1.0/src/hornet/client/metric/mod.rs.html#410
func (m *metricUnit) CountDim() int8 {
return int8(int32(m.repr<<8) >> 28)
}
// https://docs.rs/hornet/0.1.0/src/hornet/client/metric/mod.rs.html#398
func (m *metricUnit) CountScale() CountUnit {
d := m.CountDim()
if d == 0 {
panic("no count scale on unit")
}
return CountUnit(1<<20 | (uint32((m.repr>>8)&0xF))>>8)
}
func (m *metricUnit) String() string {
sd, td, cd := m.SpaceDim(), m.TimeDim(), m.CountDim()
ans := ""
if sd != 0 {
ans = ans + m.SpaceScale().String() + "^" + strconv.Itoa(int(m.SpaceDim()))
}
if td != 0 {
ans = ans + m.TimeScale().String() + "^" + strconv.Itoa(int(m.TimeDim()))
}
if cd != 0 {
ans = ans + m.CountScale().String() + "^" + strconv.Itoa(int(m.CountDim()))
}
return ans
}
// SpaceUnit is an enumerated type representing all units for space.
type SpaceUnit uint32
// Possible values for SpaceUnit.
const (
ByteUnit SpaceUnit = 1<<28 | iota<<16
KilobyteUnit
MegabyteUnit
GigabyteUnit
TerabyteUnit
PetabyteUnit
ExabyteUnit
)
//go:generate stringer -type=SpaceUnit
// PMAPI returns the PMAPI representation for a SpaceUnit
// for space units bits 0-3 are 1 and bits 13-16 are scale
func (s SpaceUnit) PMAPI() uint32 {
return uint32(s)
}
// Space adds a space unit to the current unit at a specific dimension
func (s SpaceUnit) Space(SpaceUnit, int8) MetricUnit {
panic("Cannot add another space unit")
}
// Time adds a time unit to the current unit at a specific dimension
func (s SpaceUnit) Time(t TimeUnit, dimension int8) MetricUnit {
return (&metricUnit{uint32(s)}).Time(t, dimension)
}
// Count adds a count unit to the current unit at a specific dimension
func (s SpaceUnit) Count(c CountUnit, dimension int8) MetricUnit {
return (&metricUnit{uint32(s)}).Count(c, dimension)
}
// TimeUnit is an enumerated type representing all possible units for representing time.
type TimeUnit uint32
// Possible Values for TimeUnit.
// for time units bits 4-7 are 1 and bits 17-20 are scale.
const (
NanosecondUnit TimeUnit = 1<<24 | iota<<12
MicrosecondUnit
MillisecondUnit
SecondUnit
MinuteUnit
HourUnit
)
//go:generate stringer -type=TimeUnit
// PMAPI returns the PMAPI representation for a TimeUnit.
func (t TimeUnit) PMAPI() uint32 {
return uint32(t)
}
// Space adds a space unit to the current unit at a specific dimension
func (t TimeUnit) Space(s SpaceUnit, dimension int8) MetricUnit {
return (&metricUnit{uint32(t)}).Space(s, dimension)
}
// Time adds a time unit to the current unit at a specific dimension
func (t TimeUnit) Time(TimeUnit, int8) MetricUnit {
panic("Cannot add another time unit")
}
// Count adds a count unit to the current unit at a specific dimension
func (t TimeUnit) Count(c CountUnit, dimension int8) MetricUnit {
return (&metricUnit{uint32(t)}).Count(c, dimension)
}
// CountUnit is a type representing a counted quantity.
type CountUnit uint32
// OneUnit represents the only CountUnit.
// For count units bits 8-11 are 1 and bits 21-24 are scale.
const OneUnit CountUnit = 1<<20 | iota<<8
//go:generate stringer -type=CountUnit
// PMAPI returns the PMAPI representation for a CountUnit.
func (c CountUnit) PMAPI() uint32 {
return uint32(c)
}
// Space adds a space unit to the current unit at a specific dimension
func (c CountUnit) Space(s SpaceUnit, dimension int8) MetricUnit {
return (&metricUnit{uint32(c)}).Space(s, dimension)
}
// Time adds a time unit to the current unit at a specific dimension
func (c CountUnit) Time(t TimeUnit, dimension int8) MetricUnit {
return (&metricUnit{uint32(c)}).Time(t, dimension)
}
// Count adds a count unit to the current unit at a specific dimension
func (c CountUnit) Count(CountUnit, int8) MetricUnit {
panic("Cannot add another time unit")
}
///////////////////////////////////////////////////////////////////////////////
// MetricSemantics represents an enumerated type representing the possible
// values for the semantics of a metric.
type MetricSemantics int32
// Possible values for MetricSemantics.
const (
NoSemantics MetricSemantics = iota
CounterSemantics
_
InstantSemantics
DiscreteSemantics
)
//go:generate stringer -type=MetricSemantics
///////////////////////////////////////////////////////////////////////////////
// Metric defines the general interface a type needs to implement to qualify
// as a valid PCP metric.
type Metric interface {
// gets the unique id generated for this metric
ID() uint32
// gets the name for the metric
Name() string
// gets the type of a metric
Type() MetricType
// gets the unit of a metric
Unit() MetricUnit
// gets the semantics for a metric
Semantics() MetricSemantics
// gets the description of a metric
Description() string
}
///////////////////////////////////////////////////////////////////////////////
// SingletonMetric defines the interface for a metric that stores only one value.
type SingletonMetric interface {
Metric
// gets the value of the metric
Val() interface{}
// sets the value of the metric to a value, optionally returns an error on failure
Set(interface{}) error
// tries to set and panics on error
MustSet(interface{})
}
///////////////////////////////////////////////////////////////////////////////
// InstanceMetric defines the interface for a metric that stores multiple values
// in instances and instance domains.
type InstanceMetric interface {
Metric
// gets the value of a particular instance
ValInstance(string) (interface{}, error)
// sets the value of a particular instance
SetInstance(interface{}, string) error
// tries to set the value of a particular instance and panics on error
MustSetInstance(interface{}, string)
// returns a slice containing all instances in the metric
Instances() []string
}
///////////////////////////////////////////////////////////////////////////////
// PCPMetric defines the interface for a metric that is compatible with PCP.
type PCPMetric interface {
Metric
// a PCPMetric will always have an instance domain, even if it is nil
Indom() *PCPInstanceDomain
ShortDescription() string
LongDescription() string
}
///////////////////////////////////////////////////////////////////////////////
// PCPMetricItemBitLength is the maximum bit size of a PCP Metric id.
//
// see: https://github.com/performancecopilot/pcp/blob/main/src/include/pcp/impl.h#L102-L121
const PCPMetricItemBitLength = 10
// pcpMetricDesc is a metric metadata wrapper
// each metric type can wrap its metadata by containing a pcpMetricDesc type and
// only define its own specific properties assuming pcpMetricDesc will handle the rest.
//
// when writing, this type is supposed to map directly to the pmDesc struct as defined in PCP core.
type pcpMetricDesc struct {
id uint32 // unique metric id
name string // the name
t MetricType // the type of a metric
sem MetricSemantics // the semantics
u MetricUnit // the unit
shortDescription, longDescription string
}
// newpcpMetricDesc creates a new Metric Description wrapper type.
func newpcpMetricDesc(n string, t MetricType, s MetricSemantics, u MetricUnit, desc ...string) (*pcpMetricDesc, error) {
if n == "" {
return nil, errors.New("Metric name cannot be empty")
}
if len(n) > StringLength {
return nil, errors.New("metric name is too long")
}
if len(desc) > 2 {
return nil, errors.New("only 2 optional strings allowed, short and long descriptions")
}
shortdesc, longdesc := "", ""
if len(desc) > 0 {
shortdesc = desc[0]
}
if len(desc) > 1 {
longdesc = desc[1]
}
return &pcpMetricDesc{
hash(n, PCPMetricItemBitLength),
n, t, s, u,
shortdesc, longdesc,
}, nil
}
// ID returns the generated id for PCPMetric.
func (md *pcpMetricDesc) ID() uint32 { return md.id }
// Name returns the generated id for PCPMetric.
func (md *pcpMetricDesc) Name() string {
return md.name
}
// Semantics returns the current stored value for PCPMetric.
func (md *pcpMetricDesc) Semantics() MetricSemantics { return md.sem }
// Unit returns the unit for PCPMetric.
func (md *pcpMetricDesc) Unit() MetricUnit { return md.u }
// Type returns the type for PCPMetric.
func (md *pcpMetricDesc) Type() MetricType { return md.t }
// ShortDescription returns the shortdesc value.
func (md *pcpMetricDesc) ShortDescription() string { return md.shortDescription }
// LongDescription returns the longdesc value.
func (md *pcpMetricDesc) LongDescription() string { return md.longDescription }
// Description returns the description for PCPMetric.
func (md *pcpMetricDesc) Description() string {
return md.shortDescription + "\n" + md.longDescription
}
///////////////////////////////////////////////////////////////////////////////
// updateClosure is a closure that will write the modified value of a metric on disk.
type updateClosure func(interface{}) error
// newupdateClosure creates a new update closure for an offset, type and buffer.
func newupdateClosure(offset int, writer bytewriter.Writer) updateClosure {
return func(val interface{}) error {
if _, isString := val.(string); isString {
writer.MustWrite(make([]byte, StringLength), offset)
}
_, err := writer.WriteVal(val, offset)
return err
}
}
///////////////////////////////////////////////////////////////////////////////
// pcpSingletonMetric defines an embeddable base singleton metric.
type pcpSingletonMetric struct {
*pcpMetricDesc
val interface{}
update updateClosure
}
// newpcpSingletonMetric creates a new instance of pcpSingletonMetric.
func newpcpSingletonMetric(val interface{}, desc *pcpMetricDesc) (*pcpSingletonMetric, error) {
if !desc.t.IsCompatible(val) {
return nil, errors.Errorf("type %v is not compatible with value %v(%T)", desc.t, val, val)
}
val = desc.t.resolve(val)
return &pcpSingletonMetric{desc, val, nil}, nil
}
// set Sets the current value of pcpSingletonMetric.
func (m *pcpSingletonMetric) set(val interface{}) error {
if !m.t.IsCompatible(val) {
return errors.Errorf("value %v is incompatible with MetricType %v", val, m.t)
}
val = m.t.resolve(val)
if val != m.val {
if m.update != nil {
err := m.update(val)
if err != nil {
return err
}
}
m.val = val
}
return nil
}
func (m *pcpSingletonMetric) Indom() *PCPInstanceDomain { return nil }
///////////////////////////////////////////////////////////////////////////////
// PCPSingletonMetric defines a singleton metric with no instance domain
// only a value and a valueoffset.
type PCPSingletonMetric struct {
*pcpSingletonMetric
mutex sync.RWMutex
}
// NewPCPSingletonMetric creates a new instance of PCPSingletonMetric
// it takes 2 extra optional strings as short and long description parameters,
// which on not being present are set to blank strings.
func NewPCPSingletonMetric(val interface{}, name string, t MetricType, s MetricSemantics, u MetricUnit, desc ...string) (*PCPSingletonMetric, error) {
d, err := newpcpMetricDesc(name, t, s, u, desc...)
if err != nil {
return nil, err
}
sm, err := newpcpSingletonMetric(val, d)
if err != nil {
return nil, err
}
return &PCPSingletonMetric{sm, sync.RWMutex{}}, nil
}
// Val returns the current Set value of PCPSingletonMetric.
func (m *PCPSingletonMetric) Val() interface{} {
m.mutex.RLock()
defer m.mutex.RUnlock()
return m.val
}
// Set Sets the current value of PCPSingletonMetric.
func (m *PCPSingletonMetric) Set(val interface{}) error {
m.mutex.Lock()
defer m.mutex.Unlock()
return m.set(val)
}
// MustSet is a Set that panics on failure.
func (m *PCPSingletonMetric) MustSet(val interface{}) {
if err := m.Set(val); err != nil {
panic(err)
}
}
func (m *PCPSingletonMetric) String() string {
return fmt.Sprintf("Val: %v\n%v", m.val, m.Description())
}
///////////////////////////////////////////////////////////////////////////////
// Counter defines a metric that holds a single value that can only be incremented.
type Counter interface {
Metric
Val() int64
Set(int64) error
Inc(int64) error
MustInc(int64)
Up() // same as MustInc(1)
}
///////////////////////////////////////////////////////////////////////////////
// PCPCounter implements a PCP compatible Counter Metric.
type PCPCounter struct {
*pcpSingletonMetric
mutex sync.RWMutex
}
// NewPCPCounter creates a new PCPCounter instance.
// It requires an initial int64 value and a metric name for construction.
// optionally it can also take a couple of description strings that are used as
// short and long descriptions respectively.
// Internally it creates a PCP SingletonMetric with Int64Type, CounterSemantics
// and CountUnit.
func NewPCPCounter(val int64, name string, desc ...string) (*PCPCounter, error) {
d, err := newpcpMetricDesc(name, Int64Type, CounterSemantics, OneUnit, desc...)
if err != nil {
return nil, err
}
sm, err := newpcpSingletonMetric(val, d)
if err != nil {
return nil, err
}
return &PCPCounter{sm, sync.RWMutex{}}, nil
}
// Val returns the current value of the counter.
func (c *PCPCounter) Val() int64 {
c.mutex.RLock()
defer c.mutex.RUnlock()
return c.val.(int64)
}
// Set sets the value of the counter.
func (c *PCPCounter) Set(val int64) error {
c.mutex.Lock()
defer c.mutex.Unlock()
v := c.val.(int64)
if val < v {
return errors.Errorf("cannot set counter to %v, current value is %v and PCP counters cannot go backwards", val, v)
}
return c.set(val)
}
// Inc increases the stored counter's value by the passed increment.
func (c *PCPCounter) Inc(val int64) error {
c.mutex.Lock()
defer c.mutex.Unlock()
if val < 0 {
return errors.New("cannot decrement a counter")
}
if val == 0 {
return nil
}
v := c.val.(int64)
v += val
return c.set(v)
}
// MustInc is Inc that panics on failure.
func (c *PCPCounter) MustInc(val int64) {
if err := c.Inc(val); err != nil {
panic(err)
}
}
// Up increases the counter by 1.
func (c *PCPCounter) Up() { c.MustInc(1) }
///////////////////////////////////////////////////////////////////////////////
// Gauge defines a metric that holds a single double value that can be
// incremented or decremented.
type Gauge interface {
Metric
Val() float64
Set(float64) error
MustSet(float64)
Inc(float64) error
Dec(float64) error
MustInc(float64)
MustDec(float64)
}
///////////////////////////////////////////////////////////////////////////////
// PCPGauge defines a PCP compatible Gauge metric
type PCPGauge struct {
*pcpSingletonMetric
mutex sync.RWMutex
}
// NewPCPGauge creates a new PCPGauge instance.
// Tt requires an initial float64 value and a metric name for construction.
// Optionally it can also take a couple of description strings that are used as
// short and long descriptions respectively.
// Internally it creates a PCP SingletonMetric with DoubleType, InstantSemantics
// and CountUnit.
func NewPCPGauge(val float64, name string, desc ...string) (*PCPGauge, error) {
d, err := newpcpMetricDesc(name, DoubleType, InstantSemantics, OneUnit, desc...)
if err != nil {
return nil, err
}
sm, err := newpcpSingletonMetric(val, d)
if err != nil {
return nil, err
}
return &PCPGauge{sm, sync.RWMutex{}}, nil
}
// Val returns the current value of the Gauge.
func (g *PCPGauge) Val() float64 {
g.mutex.RLock()
defer g.mutex.RUnlock()
return g.val.(float64)
}
// Set sets the current value of the Gauge.
func (g *PCPGauge) Set(val float64) error {
g.mutex.Lock()
defer g.mutex.Unlock()
return g.set(val)
}
// MustSet will panic if Set fails.
func (g *PCPGauge) MustSet(val float64) {
if err := g.Set(val); err != nil {
panic(err)
}
}
// Inc adds a value to the existing Gauge value.
func (g *PCPGauge) Inc(val float64) error {
g.mutex.Lock()
defer g.mutex.Unlock()
if val == 0 {
return nil
}
v := g.val.(float64)
return g.set(v + val)
}
// MustInc will panic if Inc fails.
func (g *PCPGauge) MustInc(val float64) {
if err := g.Inc(val); err != nil {
panic(err)
}
}
// Dec adds a value to the existing Gauge value.
func (g *PCPGauge) Dec(val float64) error {
return g.Inc(-val)
}
// MustDec will panic if Dec fails.
func (g *PCPGauge) MustDec(val float64) {
if err := g.Dec(val); err != nil {
panic(err)
}
}
///////////////////////////////////////////////////////////////////////////////
// Timer defines a metric that accumulates time periods
// Start signals the beginning of monitoring.
// End signals the end of monitoring and adding the elapsed time to the
// accumulated time, and returning it.
type Timer interface {
Metric
Start() error
Stop() (float64, error)
}
///////////////////////////////////////////////////////////////////////////////
// PCPTimer implements a PCP compatible Timer
// It also functionally implements a metric with elapsed type from PCP
type PCPTimer struct {
*pcpSingletonMetric
mutex sync.Mutex
started bool
since time.Time
}
// NewPCPTimer creates a new PCPTimer instance of the specified unit.
// It requires a metric name and a TimeUnit for construction.
// It can optionally take a couple of description strings.
// Internally it uses a PCP SingletonMetric.
func NewPCPTimer(name string, unit TimeUnit, desc ...string) (*PCPTimer, error) {
d, err := newpcpMetricDesc(name, DoubleType, DiscreteSemantics, unit, desc...)
if err != nil {
return nil, err
}
sm, err := newpcpSingletonMetric(float64(0), d)
if err != nil {
return nil, err
}
return &PCPTimer{sm, sync.Mutex{}, false, time.Time{}}, nil
}
// Reset resets the timer to 0
func (t *PCPTimer) Reset() error {
t.mutex.Lock()
defer t.mutex.Unlock()
if t.started {
return errors.New("trying to reset an already started timer")
}
return t.set(float64(0))
}
// Start signals the timer to start monitoring.
func (t *PCPTimer) Start() error {
t.mutex.Lock()
defer t.mutex.Unlock()
if t.started {
return errors.New("trying to start an already started timer")
}
t.since = time.Now()
t.started = true
return nil
}
// Stop signals the timer to end monitoring and return elapsed time so far.
func (t *PCPTimer) Stop() (float64, error) {
t.mutex.Lock()
defer t.mutex.Unlock()
if !t.started {
return 0, errors.New("trying to stop a stopped timer")
}
d := time.Since(t.since)
var inc float64
switch t.pcpMetricDesc.Unit() {
case NanosecondUnit:
inc = float64(d.Nanoseconds())
case MicrosecondUnit:
inc = float64(d.Nanoseconds()) * 1e-3
case MillisecondUnit:
inc = float64(d.Nanoseconds()) * 1e-6
case SecondUnit:
inc = d.Seconds()
case MinuteUnit:
inc = d.Minutes()
case HourUnit:
inc = d.Hours()
}
v := t.val.(float64)
err := t.set(v + inc)
if err != nil {
return -1, err
}
t.started = false
return v + inc, nil
}
///////////////////////////////////////////////////////////////////////////////
type instanceValue struct {
val interface{}
update updateClosure
}
func newinstanceValue(val interface{}) *instanceValue {
return &instanceValue{val, nil}
}
// pcpInstanceMetric represents a PCPMetric that can have multiple values
// over multiple instances in an instance domain.
type pcpInstanceMetric struct {
*pcpMetricDesc
indom *PCPInstanceDomain
vals map[string]*instanceValue
}
// newpcpInstanceMetric creates a new instance of PCPSingletonMetric.
func newpcpInstanceMetric(vals Instances, indom *PCPInstanceDomain, desc *pcpMetricDesc) (*pcpInstanceMetric, error) {
if len(vals) != indom.InstanceCount() {
return nil, errors.New("values for all instances in the instance domain only should be passed")
}
mvals := make(map[string]*instanceValue)
for name := range indom.instances {
val, present := vals[name]
if !present {
return nil, errors.Errorf("Instance %v not initialized", name)
}
if !desc.t.IsCompatible(val) {
return nil, errors.Errorf("value %v is incompatible with type %v for Instance %v", val, desc.t, name)
}
val = desc.t.resolve(val)
mvals[name] = newinstanceValue(val)
}
return &pcpInstanceMetric{desc, indom, mvals}, nil
}
func (m *pcpInstanceMetric) valInstance(instance string) (interface{}, error) {
if !m.indom.HasInstance(instance) {
return nil, errors.Errorf("%v is not an instance of this metric", instance)
}
return m.vals[instance].val, nil
}
// setInstance sets the value for a particular instance of the metric.