File: promparse_test.go

package info (click to toggle)
prometheus 2.7.1%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 4,912 kB
  • sloc: lex: 171; sh: 155; makefile: 78
file content (496 lines) | stat: -rw-r--r-- 12,132 bytes parent folder | download
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
// Copyright 2017 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package textparse

import (
	"bytes"
	"compress/gzip"
	"io"
	"io/ioutil"
	"os"
	"testing"

	"github.com/prometheus/common/expfmt"
	"github.com/prometheus/common/model"
	"github.com/prometheus/prometheus/pkg/labels"
	"github.com/stretchr/testify/require"
)

func TestPromParse(t *testing.T) {
	input := `# HELP go_gc_duration_seconds A summary of the GC invocation durations.
# 	TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 4.9351e-05
go_gc_duration_seconds{quantile="0.25",} 7.424100000000001e-05
go_gc_duration_seconds{quantile="0.5",a="b"} 8.3835e-05
go_gc_duration_seconds{quantile="0.8", a="b"} 8.3835e-05
go_gc_duration_seconds{ quantile="0.9", a="b"} 8.3835e-05
# Hrandom comment starting with prefix of HELP
#
# comment with escaped \n newline
# comment with escaped \ escape character
# HELP nohelp1
# HELP nohelp2 
go_gc_duration_seconds{ quantile="1.0", a="b" } 8.3835e-05
go_gc_duration_seconds { quantile="1.0", a="b" } 8.3835e-05
go_gc_duration_seconds { quantile= "1.0", a= "b", } 8.3835e-05
go_gc_duration_seconds { quantile = "1.0", a = "b" } 8.3835e-05
go_gc_duration_seconds_count 99
some:aggregate:rate5m{a_b="c"}	1
# HELP go_goroutines Number of goroutines that currently exist.
# TYPE go_goroutines gauge
go_goroutines 33  	123123
_metric_starting_with_underscore 1
testmetric{_label_starting_with_underscore="foo"} 1
testmetric{label="\"bar\""} 1`
	input += "\n# HELP metric foo\x00bar"
	input += "\nnull_byte_metric{a=\"abc\x00\"} 1"

	int64p := func(x int64) *int64 { return &x }

	exp := []struct {
		lset    labels.Labels
		m       string
		t       *int64
		v       float64
		typ     MetricType
		help    string
		comment string
	}{
		{
			m:    "go_gc_duration_seconds",
			help: "A summary of the GC invocation durations.",
		}, {
			m:   "go_gc_duration_seconds",
			typ: MetricTypeSummary,
		}, {
			m:    `go_gc_duration_seconds{quantile="0"}`,
			v:    4.9351e-05,
			lset: labels.FromStrings("__name__", "go_gc_duration_seconds", "quantile", "0"),
		}, {
			m:    `go_gc_duration_seconds{quantile="0.25",}`,
			v:    7.424100000000001e-05,
			lset: labels.FromStrings("__name__", "go_gc_duration_seconds", "quantile", "0.25"),
		}, {
			m:    `go_gc_duration_seconds{quantile="0.5",a="b"}`,
			v:    8.3835e-05,
			lset: labels.FromStrings("__name__", "go_gc_duration_seconds", "quantile", "0.5", "a", "b"),
		}, {
			m:    `go_gc_duration_seconds{quantile="0.8", a="b"}`,
			v:    8.3835e-05,
			lset: labels.FromStrings("__name__", "go_gc_duration_seconds", "quantile", "0.8", "a", "b"),
		}, {
			m:    `go_gc_duration_seconds{ quantile="0.9", a="b"}`,
			v:    8.3835e-05,
			lset: labels.FromStrings("__name__", "go_gc_duration_seconds", "quantile", "0.9", "a", "b"),
		}, {
			comment: "# Hrandom comment starting with prefix of HELP",
		}, {
			comment: "#",
		}, {
			comment: "# comment with escaped \\n newline",
		}, {
			comment: "# comment with escaped \\ escape character",
		}, {
			m:    "nohelp1",
			help: "",
		}, {
			m:    "nohelp2",
			help: "",
		}, {
			m:    `go_gc_duration_seconds{ quantile="1.0", a="b" }`,
			v:    8.3835e-05,
			lset: labels.FromStrings("__name__", "go_gc_duration_seconds", "quantile", "1.0", "a", "b"),
		}, {
			m:    `go_gc_duration_seconds { quantile="1.0", a="b" }`,
			v:    8.3835e-05,
			lset: labels.FromStrings("__name__", "go_gc_duration_seconds", "quantile", "1.0", "a", "b"),
		}, {
			m:    `go_gc_duration_seconds { quantile= "1.0", a= "b", }`,
			v:    8.3835e-05,
			lset: labels.FromStrings("__name__", "go_gc_duration_seconds", "quantile", "1.0", "a", "b"),
		}, {
			m:    `go_gc_duration_seconds { quantile = "1.0", a = "b" }`,
			v:    8.3835e-05,
			lset: labels.FromStrings("__name__", "go_gc_duration_seconds", "quantile", "1.0", "a", "b"),
		}, {
			m:    `go_gc_duration_seconds_count`,
			v:    99,
			lset: labels.FromStrings("__name__", "go_gc_duration_seconds_count"),
		}, {
			m:    `some:aggregate:rate5m{a_b="c"}`,
			v:    1,
			lset: labels.FromStrings("__name__", "some:aggregate:rate5m", "a_b", "c"),
		}, {
			m:    "go_goroutines",
			help: "Number of goroutines that currently exist.",
		}, {
			m:   "go_goroutines",
			typ: MetricTypeGauge,
		}, {
			m:    `go_goroutines`,
			v:    33,
			t:    int64p(123123),
			lset: labels.FromStrings("__name__", "go_goroutines"),
		}, {
			m:    "_metric_starting_with_underscore",
			v:    1,
			lset: labels.FromStrings("__name__", "_metric_starting_with_underscore"),
		}, {
			m:    "testmetric{_label_starting_with_underscore=\"foo\"}",
			v:    1,
			lset: labels.FromStrings("__name__", "testmetric", "_label_starting_with_underscore", "foo"),
		}, {
			m:    "testmetric{label=\"\\\"bar\\\"\"}",
			v:    1,
			lset: labels.FromStrings("__name__", "testmetric", "label", `"bar"`),
		}, {
			m:    "metric",
			help: "foo\x00bar",
		}, {
			m:    "null_byte_metric{a=\"abc\x00\"}",
			v:    1,
			lset: labels.FromStrings("__name__", "null_byte_metric", "a", "abc\x00"),
		},
	}

	p := NewPromParser([]byte(input))
	i := 0

	var res labels.Labels

	for {
		et, err := p.Next()
		if err == io.EOF {
			break
		}
		require.NoError(t, err)

		switch et {
		case EntrySeries:
			m, ts, v := p.Series()

			p.Metric(&res)

			require.Equal(t, exp[i].m, string(m))
			require.Equal(t, exp[i].t, ts)
			require.Equal(t, exp[i].v, v)
			require.Equal(t, exp[i].lset, res)
			res = res[:0]

		case EntryType:
			m, typ := p.Type()
			require.Equal(t, exp[i].m, string(m))
			require.Equal(t, exp[i].typ, typ)

		case EntryHelp:
			m, h := p.Help()
			require.Equal(t, exp[i].m, string(m))
			require.Equal(t, exp[i].help, string(h))

		case EntryComment:
			require.Equal(t, exp[i].comment, string(p.Comment()))
		}

		i++
	}
	require.Equal(t, len(exp), i)
}

func TestPromParseErrors(t *testing.T) {
	cases := []struct {
		input string
		err   string
	}{
		{
			input: "a",
			err:   "expected value after metric, got \"MNAME\"",
		},
		{
			input: "a{b='c'} 1\n",
			err:   "expected label value, got \"INVALID\"",
		},
		{
			input: "a{b=\n",
			err:   "expected label value, got \"INVALID\"",
		},
		{
			input: "a{\xff=\"foo\"} 1\n",
			err:   "expected label name, got \"INVALID\"",
		},
		{
			input: "a{b=\"\xff\"} 1\n",
			err:   "invalid UTF-8 label value",
		},
		{
			input: "a true\n",
			err:   "strconv.ParseFloat: parsing \"true\": invalid syntax",
		},
		{
			input: "something_weird{problem=\"",
			err:   "expected label value, got \"INVALID\"",
		},
		{
			input: "empty_label_name{=\"\"} 0",
			err:   "expected label name, got \"EQUAL\"",
		},
	}

	for i, c := range cases {
		p := NewPromParser([]byte(c.input))
		var err error
		for err == nil {
			_, err = p.Next()
		}
		require.NotNil(t, err)
		require.Equal(t, c.err, err.Error(), "test %d", i)
	}
}

func TestPromNullByteHandling(t *testing.T) {
	cases := []struct {
		input string
		err   string
	}{
		{
			input: "null_byte_metric{a=\"abc\x00\"} 1",
			err:   "",
		},
		{
			input: "a{b=\"\x00ss\"} 1\n",
			err:   "",
		},
		{
			input: "a{b=\"\x00\"} 1\n",
			err:   "",
		},
		{
			input: "a{b=\"\x00\"} 1\n",
			err:   "",
		},
		{
			input: "a{b=\x00\"ssss\"} 1\n",
			err:   "expected label value, got \"INVALID\"",
		},
		{
			input: "a{b=\"\x00",
			err:   "expected label value, got \"INVALID\"",
		},
		{
			input: "a{b\x00=\"hiih\"}	1",
			err: "expected equal, got \"INVALID\"",
		},
		{
			input: "a\x00{b=\"ddd\"} 1",
			err:   "expected value after metric, got \"MNAME\"",
		},
	}

	for i, c := range cases {
		p := NewPromParser([]byte(c.input))
		var err error
		for err == nil {
			_, err = p.Next()
		}

		if c.err == "" {
			require.Equal(t, io.EOF, err, "test %d", i)
			continue
		}

		require.Error(t, err)
		require.Equal(t, c.err, err.Error(), "test %d", i)
	}
}

const (
	promtestdataSampleCount = 410
)

func BenchmarkParse(b *testing.B) {
	for parserName, parser := range map[string]func([]byte) Parser{
		"prometheus":  NewPromParser,
		"openmetrics": NewOpenMetricsParser,
	} {

		for _, fn := range []string{"promtestdata.txt", "promtestdata.nometa.txt"} {
			f, err := os.Open(fn)
			require.NoError(b, err)
			defer f.Close()

			buf, err := ioutil.ReadAll(f)
			require.NoError(b, err)

			b.Run(parserName+"/no-decode-metric/"+fn, func(b *testing.B) {
				total := 0

				b.SetBytes(int64(len(buf) * (b.N / promtestdataSampleCount)))
				b.ReportAllocs()
				b.ResetTimer()

				for i := 0; i < b.N; i += promtestdataSampleCount {
					p := parser(buf)

				Outer:
					for i < b.N {
						t, err := p.Next()
						switch t {
						case EntryInvalid:
							if err == io.EOF {
								break Outer
							}
							b.Fatal(err)
						case EntrySeries:
							m, _, _ := p.Series()
							total += len(m)
							i++
						}
					}
				}
				_ = total
			})
			b.Run(parserName+"/decode-metric/"+fn, func(b *testing.B) {
				total := 0

				b.SetBytes(int64(len(buf) * (b.N / promtestdataSampleCount)))
				b.ReportAllocs()
				b.ResetTimer()

				for i := 0; i < b.N; i += promtestdataSampleCount {
					p := parser(buf)

				Outer:
					for i < b.N {
						t, err := p.Next()
						switch t {
						case EntryInvalid:
							if err == io.EOF {
								break Outer
							}
							b.Fatal(err)
						case EntrySeries:
							m, _, _ := p.Series()

							res := make(labels.Labels, 0, 5)
							p.Metric(&res)

							total += len(m)
							i++
						}
					}
				}
				_ = total
			})
			b.Run(parserName+"/decode-metric-reuse/"+fn, func(b *testing.B) {
				total := 0
				res := make(labels.Labels, 0, 5)

				b.SetBytes(int64(len(buf) * (b.N / promtestdataSampleCount)))
				b.ReportAllocs()
				b.ResetTimer()

				for i := 0; i < b.N; i += promtestdataSampleCount {
					p := parser(buf)

				Outer:
					for i < b.N {
						t, err := p.Next()
						switch t {
						case EntryInvalid:
							if err == io.EOF {
								break Outer
							}
							b.Fatal(err)
						case EntrySeries:
							m, _, _ := p.Series()

							p.Metric(&res)

							total += len(m)
							i++
							res = res[:0]
						}
					}
				}
				_ = total
			})
			b.Run("expfmt-text/"+fn, func(b *testing.B) {
				b.SetBytes(int64(len(buf) * (b.N / promtestdataSampleCount)))
				b.ReportAllocs()
				b.ResetTimer()

				total := 0

				for i := 0; i < b.N; i += promtestdataSampleCount {
					var (
						decSamples = make(model.Vector, 0, 50)
					)
					sdec := expfmt.SampleDecoder{
						Dec: expfmt.NewDecoder(bytes.NewReader(buf), expfmt.FmtText),
						Opts: &expfmt.DecodeOptions{
							Timestamp: model.TimeFromUnixNano(0),
						},
					}

					for {
						if err = sdec.Decode(&decSamples); err != nil {
							break
						}
						total += len(decSamples)
						decSamples = decSamples[:0]
					}
				}
				_ = total
			})
		}
	}
}
func BenchmarkGzip(b *testing.B) {
	for _, fn := range []string{"promtestdata.txt", "promtestdata.nometa.txt"} {
		b.Run(fn, func(b *testing.B) {
			f, err := os.Open(fn)
			require.NoError(b, err)
			defer f.Close()

			var buf bytes.Buffer
			gw := gzip.NewWriter(&buf)

			n, err := io.Copy(gw, f)
			require.NoError(b, err)
			require.NoError(b, gw.Close())

			gbuf, err := ioutil.ReadAll(&buf)
			require.NoError(b, err)

			k := b.N / promtestdataSampleCount

			b.ReportAllocs()
			b.SetBytes(int64(k) * int64(n))
			b.ResetTimer()

			total := 0

			for i := 0; i < k; i++ {
				gr, err := gzip.NewReader(bytes.NewReader(gbuf))
				require.NoError(b, err)

				d, err := ioutil.ReadAll(gr)
				require.NoError(b, err)
				require.NoError(b, gr.Close())

				total += len(d)
			}
			_ = total
		})
	}
}