Skip to content

Commit 5bcff99

Browse files
committed
Adapt code after withCreated addition, solve residual conflicts
Signed-off-by: Arianna Vespri <[email protected]>
1 parent 89f4253 commit 5bcff99

File tree

4 files changed

+130
-47
lines changed

4 files changed

+130
-47
lines changed

expfmt/encode.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ func NewEncoder(w io.Writer, format Format, options ...EncoderOption) Encoder {
184184
case TypeOpenMetrics:
185185
return encoderCloser{
186186
encode: func(v *dto.MetricFamily) error {
187-
_, err := MetricFamilyToOpenMetrics(w, model.EscapeMetricFamily(v, escapingScheme)) // , options...?
187+
_, err := MetricFamilyToOpenMetrics(w, model.EscapeMetricFamily(v, escapingScheme), options...)
188188
return err
189189
},
190190
close: func() error {

expfmt/encode_test.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -214,10 +214,10 @@ func TestEncode(t *testing.T) {
214214
}
215215

216216
scenarios := []struct {
217-
metric *dto.MetricFamily
218-
format Format
219-
withUnit bool
220-
expOut string
217+
metric *dto.MetricFamily
218+
format Format
219+
options []EncoderOption
220+
expOut string
221221
}{
222222
// 1: Untyped ProtoDelim
223223
{
@@ -260,9 +260,9 @@ foo_metric 1.234
260260
},
261261
// 7: Simple Counter fmtOpenMetrics_0_0_1 unit opted in
262262
{
263-
metric: metric1,
264-
format: fmtOpenMetrics_0_0_1,
265-
withUnit: true,
263+
metric: metric1,
264+
format: fmtOpenMetrics_0_0_1,
265+
options: []EncoderOption{WithUnit()},
266266
expOut: `# TYPE foo_metric_seconds unknown
267267
# UNIT foo_metric_seconds seconds
268268
foo_metric_seconds 1.234
@@ -278,12 +278,12 @@ foo_metric 1.234
278278
},
279279
}
280280
for i, scenario := range scenarios {
281-
opts := []ToOpenMetricsOption{}
282-
if scenario.withUnit {
283-
opts = append(opts, ToOpenMetricsWithUnit())
284-
}
281+
// opts := []EncoderOption{}
282+
// if scenario.withUnit {
283+
// opts = append(opts, WithUnit())
284+
// }
285285
out := bytes.NewBuffer(make([]byte, 0, len(scenario.expOut)))
286-
enc := NewEncoder(out, scenario.format, opts...)
286+
enc := NewEncoder(out, scenario.format, scenario.options...)
287287
err := enc.Encode(scenario.metric)
288288
if err != nil {
289289
t.Errorf("%d. error: %s", i, err)

expfmt/openmetrics_create.go

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ import (
3131

3232
type encoderOption struct {
3333
withCreatedLines bool
34-
withUnit bool
34+
withUnit bool
3535
}
3636

3737
type EncoderOption func(*encoderOption)
@@ -52,24 +52,17 @@ func WithCreatedLines() EncoderOption {
5252
}
5353
}
5454

55-
type ToOpenMetrics struct {
56-
withUnit bool
57-
// withCreated bool can be added in the future.
55+
// WithUnit is an EncoderOption enabling a set unit to be written to the output
56+
// and to be added to the metric name, if it's not there already, as a suffix.
57+
// Without opting in this way, the unit will not be added to the metric name and,
58+
// on top of that, the unit will not be passed onto the output, even if it
59+
// were declared in the *dto.MetricFamily struct, i.e. even if in.Unit !=nil.
60+
func WithUnit() EncoderOption {
61+
return func(t *encoderOption) {
62+
t.withUnit = true
63+
}
5864
}
5965

60-
// type ToOpenMetricsOption = func(*ToOpenMetrics)
61-
62-
// // ToOpenMetricsWithUnit is meant to be called as an optional argument in the MetricFamilyToOpenMetrics
63-
// // function. It enables a set unit to be written to the output and to be added to the metric name, if
64-
// // it's not there already, as a suffix. Without opting in this way, the unit will not be added to the
65-
// // metric name and, on top of that, the unit will not be passed onto the output, even if it were declared
66-
// // in the *dto.MetricFamily struct, i.e. even if in.Unit !=nil.
67-
// func ToOpenMetricsWithUnit() ToOpenMetricsOption {
68-
// return func(om *ToOpenMetrics) {
69-
// om.withUnit = true
70-
// }
71-
// }
72-
7366
// MetricFamilyToOpenMetrics converts a MetricFamily proto message into the
7467
// OpenMetrics text format and writes the resulting lines to 'out'. It returns
7568
// the number of bytes written and any error encountered. The output will have
@@ -113,11 +106,11 @@ type ToOpenMetrics struct {
113106
// However, in order to accommodate any potential scenario where such a change in the
114107
// metric name is not desirable, the users are here given the choice of either explicitly
115108
// opt in, in case they wish for the unit to be included in the output AND in the metric name
116-
// as a suffix (see the description of the ToOpenMetricsWithUnit function below),
109+
// as a suffix (see the description of the WithUnit function above),
117110
// or not to opt in, in case they don't want for any of that to happen.
118111
//
119-
// - No support for the following (optional) features: `_created`,
120-
// info type, stateset type, gaugehistogram type.
112+
// - No support for the following (optional) features: info type,
113+
// stateset type, gaugehistogram type.
121114
//
122115
// - The size of exemplar labels is not checked (i.e. it's possible to create
123116
// exemplars that are larger than allowed by the OpenMetrics specification).
@@ -126,9 +119,9 @@ type ToOpenMetrics struct {
126119
// with a `NaN` value.)
127120
func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...EncoderOption) (written int, err error) {
128121
toOM := encoderOption{}
129-
// for _, option := range options {
130-
// option(&toOM)
131-
// }
122+
for _, option := range options {
123+
option(&toOM)
124+
}
132125

133126
name := in.GetName()
134127
if name == "" {
@@ -245,13 +238,15 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
245238
if err != nil {
246239
return
247240
}
248-
var createdTsBytesWritten int // err = w.WriteByte('\n')
241+
err = w.WriteByte('\n')
249242
written++
250243
if err != nil {
251244
return
252245
}
253246
}
254247

248+
var createdTsBytesWritten int
249+
255250
// Finally the samples, one line for each.
256251
for _, metric := range in.Metric {
257252
switch metricType {
@@ -270,7 +265,7 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
270265
metric.Counter.Exemplar,
271266
)
272267
if toOM.withCreatedLines && metric.Counter.CreatedTimestamp != nil {
273-
createdTsBytesWritten, err = writeOpenMetricsCreated(w, name, "_total", metric, "", 0, metric.Counter.GetCreatedTimestamp())
268+
createdTsBytesWritten, err = writeOpenMetricsCreated(w, compliantName, "_total", metric, "", 0, metric.Counter.GetCreatedTimestamp())
274269
n += createdTsBytesWritten
275270
}
276271
case dto.MetricType_GAUGE:
@@ -328,7 +323,7 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
328323
nil,
329324
)
330325
if toOM.withCreatedLines && metric.Summary.CreatedTimestamp != nil {
331-
createdTsBytesWritten, err = writeOpenMetricsCreated(w, name, "", metric, "", 0, metric.Summary.GetCreatedTimestamp())
326+
createdTsBytesWritten, err = writeOpenMetricsCreated(w, compliantName, "", metric, "", 0, metric.Summary.GetCreatedTimestamp())
332327
n += createdTsBytesWritten
333328
}
334329
case dto.MetricType_HISTOGRAM:
@@ -380,7 +375,7 @@ func MetricFamilyToOpenMetrics(out io.Writer, in *dto.MetricFamily, options ...E
380375
nil,
381376
)
382377
if toOM.withCreatedLines && metric.Histogram.CreatedTimestamp != nil {
383-
createdTsBytesWritten, err = writeOpenMetricsCreated(w, name, "", metric, "", 0, metric.Histogram.GetCreatedTimestamp())
378+
createdTsBytesWritten, err = writeOpenMetricsCreated(w, compliantName, "", metric, "", 0, metric.Histogram.GetCreatedTimestamp())
384379
n += createdTsBytesWritten
385380
}
386381
default:

expfmt/openmetrics_create_test.go

Lines changed: 95 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ func TestCreateOpenMetrics(t *testing.T) {
4242

4343
scenarios := []struct {
4444
in *dto.MetricFamily
45-
options []EncoderOption // withUnit bool
45+
options []EncoderOption
4646
out string
4747
}{
4848
// 0: Counter, timestamp given, no _total suffix.
@@ -399,7 +399,7 @@ summary_name_created{name_1="value 1",name_2="value 2"} 12345.6
399399
},
400400
},
401401
},
402-
options: []EncoderOption{WithCreatedLines()},
402+
options: []EncoderOption{WithCreatedLines(), WithUnit()},
403403
out: `# HELP request_duration_microseconds The response latency.
404404
# TYPE request_duration_microseconds histogram
405405
# UNIT request_duration_microseconds microseconds
@@ -579,7 +579,7 @@ foos_total 42.0
579579
# TYPE name counter
580580
`,
581581
},
582-
// 9: Simple Counter with exemplar that has empty label set:
582+
// 13: Simple Counter with exemplar that has empty label set:
583583
// ignore the exemplar, since OpenMetrics spec requires labels.
584584
{
585585
in: &dto.MetricFamily{
@@ -602,16 +602,104 @@ foos_total 42.0
602602
out: `# HELP foos Number of foos.
603603
# TYPE foos counter
604604
foos_total 42.0
605+
`,
606+
},
607+
// 14: No metric plus unit.
608+
{
609+
in: &dto.MetricFamily{
610+
Name: proto.String("name_seconds_total"),
611+
Help: proto.String("doc string"),
612+
Type: dto.MetricType_COUNTER.Enum(),
613+
Unit: proto.String("seconds"),
614+
Metric: []*dto.Metric{},
615+
},
616+
options: []EncoderOption{WithUnit()},
617+
out: `# HELP name_seconds doc string
618+
# TYPE name_seconds counter
619+
# UNIT name_seconds seconds
620+
`,
621+
},
622+
// 15: Histogram plus unit, but unit not opted in.
623+
{
624+
in: &dto.MetricFamily{
625+
Name: proto.String("request_duration_microseconds"),
626+
Help: proto.String("The response latency."),
627+
Type: dto.MetricType_HISTOGRAM.Enum(),
628+
Unit: proto.String("microseconds"),
629+
Metric: []*dto.Metric{
630+
{
631+
Histogram: &dto.Histogram{
632+
SampleCount: proto.Uint64(2693),
633+
SampleSum: proto.Float64(1756047.3),
634+
Bucket: []*dto.Bucket{
635+
{
636+
UpperBound: proto.Float64(100),
637+
CumulativeCount: proto.Uint64(123),
638+
},
639+
{
640+
UpperBound: proto.Float64(120),
641+
CumulativeCount: proto.Uint64(412),
642+
},
643+
{
644+
UpperBound: proto.Float64(144),
645+
CumulativeCount: proto.Uint64(592),
646+
},
647+
{
648+
UpperBound: proto.Float64(172.8),
649+
CumulativeCount: proto.Uint64(1524),
650+
},
651+
{
652+
UpperBound: proto.Float64(math.Inf(+1)),
653+
CumulativeCount: proto.Uint64(2693),
654+
},
655+
},
656+
},
657+
},
658+
},
659+
},
660+
out: `# HELP request_duration_microseconds The response latency.
661+
# TYPE request_duration_microseconds histogram
662+
request_duration_microseconds_bucket{le="100.0"} 123
663+
request_duration_microseconds_bucket{le="120.0"} 412
664+
request_duration_microseconds_bucket{le="144.0"} 592
665+
request_duration_microseconds_bucket{le="172.8"} 1524
666+
request_duration_microseconds_bucket{le="+Inf"} 2693
667+
request_duration_microseconds_sum 1.7560473e+06
668+
request_duration_microseconds_count 2693
669+
`,
670+
},
671+
// 16: No metric, unit opted in, no unit in name.
672+
{
673+
in: &dto.MetricFamily{
674+
Name: proto.String("name_total"),
675+
Help: proto.String("doc string"),
676+
Type: dto.MetricType_COUNTER.Enum(),
677+
Unit: proto.String("seconds"),
678+
Metric: []*dto.Metric{},
679+
},
680+
options: []EncoderOption{WithUnit()},
681+
out: `# HELP name_seconds doc string
682+
# TYPE name_seconds counter
683+
# UNIT name_seconds seconds
684+
`,
685+
},
686+
// 17: No metric, unit opted in, BUT unit == nil.
687+
{
688+
in: &dto.MetricFamily{
689+
Name: proto.String("name_total"),
690+
Help: proto.String("doc string"),
691+
Type: dto.MetricType_COUNTER.Enum(),
692+
Metric: []*dto.Metric{},
693+
},
694+
options: []EncoderOption{WithUnit()},
695+
out: `# HELP name doc string
696+
# TYPE name counter
605697
`,
606698
},
607699
}
608700

609701
for i, scenario := range scenarios {
610702
out := bytes.NewBuffer(make([]byte, 0, len(scenario.out)))
611-
// opts := []ToOpenMetricsOption{}
612-
// if scenario.withUnit {
613-
// opts = append(opts, ToOpenMetricsWithUnit())
614-
// }
615703
n, err := MetricFamilyToOpenMetrics(out, scenario.in, scenario.options...)
616704
if err != nil {
617705
t.Errorf("%d. error: %s", i, err)

0 commit comments

Comments
 (0)