cubefs
775 строк · 25.3 Кб
1// Copyright 2014 The Prometheus Authors
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14package expfmt
15
16import (
17"bufio"
18"bytes"
19"fmt"
20"io"
21"math"
22"strconv"
23"strings"
24
25dto "github.com/prometheus/client_model/go"
26
27"github.com/golang/protobuf/proto" //nolint:staticcheck // Ignore SA1019. Need to keep deprecated package for compatibility.
28"github.com/prometheus/common/model"
29)
30
31// A stateFn is a function that represents a state in a state machine. By
32// executing it, the state is progressed to the next state. The stateFn returns
33// another stateFn, which represents the new state. The end state is represented
34// by nil.
35type stateFn func() stateFn
36
37// ParseError signals errors while parsing the simple and flat text-based
38// exchange format.
39type ParseError struct {
40Line int
41Msg string
42}
43
44// Error implements the error interface.
45func (e ParseError) Error() string {
46return fmt.Sprintf("text format parsing error in line %d: %s", e.Line, e.Msg)
47}
48
49// TextParser is used to parse the simple and flat text-based exchange format. Its
50// zero value is ready to use.
51type TextParser struct {
52metricFamiliesByName map[string]*dto.MetricFamily
53buf *bufio.Reader // Where the parsed input is read through.
54err error // Most recent error.
55lineCount int // Tracks the line count for error messages.
56currentByte byte // The most recent byte read.
57currentToken bytes.Buffer // Re-used each time a token has to be gathered from multiple bytes.
58currentMF *dto.MetricFamily
59currentMetric *dto.Metric
60currentLabelPair *dto.LabelPair
61
62// The remaining member variables are only used for summaries/histograms.
63currentLabels map[string]string // All labels including '__name__' but excluding 'quantile'/'le'
64// Summary specific.
65summaries map[uint64]*dto.Metric // Key is created with LabelsToSignature.
66currentQuantile float64
67// Histogram specific.
68histograms map[uint64]*dto.Metric // Key is created with LabelsToSignature.
69currentBucket float64
70// These tell us if the currently processed line ends on '_count' or
71// '_sum' respectively and belong to a summary/histogram, representing the sample
72// count and sum of that summary/histogram.
73currentIsSummaryCount, currentIsSummarySum bool
74currentIsHistogramCount, currentIsHistogramSum bool
75}
76
77// TextToMetricFamilies reads 'in' as the simple and flat text-based exchange
78// format and creates MetricFamily proto messages. It returns the MetricFamily
79// proto messages in a map where the metric names are the keys, along with any
80// error encountered.
81//
82// If the input contains duplicate metrics (i.e. lines with the same metric name
83// and exactly the same label set), the resulting MetricFamily will contain
84// duplicate Metric proto messages. Similar is true for duplicate label
85// names. Checks for duplicates have to be performed separately, if required.
86// Also note that neither the metrics within each MetricFamily are sorted nor
87// the label pairs within each Metric. Sorting is not required for the most
88// frequent use of this method, which is sample ingestion in the Prometheus
89// server. However, for presentation purposes, you might want to sort the
90// metrics, and in some cases, you must sort the labels, e.g. for consumption by
91// the metric family injection hook of the Prometheus registry.
92//
93// Summaries and histograms are rather special beasts. You would probably not
94// use them in the simple text format anyway. This method can deal with
95// summaries and histograms if they are presented in exactly the way the
96// text.Create function creates them.
97//
98// This method must not be called concurrently. If you want to parse different
99// input concurrently, instantiate a separate Parser for each goroutine.
100func (p *TextParser) TextToMetricFamilies(in io.Reader) (map[string]*dto.MetricFamily, error) {
101p.reset(in)
102for nextState := p.startOfLine; nextState != nil; nextState = nextState() {
103// Magic happens here...
104}
105// Get rid of empty metric families.
106for k, mf := range p.metricFamiliesByName {
107if len(mf.GetMetric()) == 0 {
108delete(p.metricFamiliesByName, k)
109}
110}
111// If p.err is io.EOF now, we have run into a premature end of the input
112// stream. Turn this error into something nicer and more
113// meaningful. (io.EOF is often used as a signal for the legitimate end
114// of an input stream.)
115if p.err == io.EOF {
116p.parseError("unexpected end of input stream")
117}
118return p.metricFamiliesByName, p.err
119}
120
121func (p *TextParser) reset(in io.Reader) {
122p.metricFamiliesByName = map[string]*dto.MetricFamily{}
123if p.buf == nil {
124p.buf = bufio.NewReader(in)
125} else {
126p.buf.Reset(in)
127}
128p.err = nil
129p.lineCount = 0
130if p.summaries == nil || len(p.summaries) > 0 {
131p.summaries = map[uint64]*dto.Metric{}
132}
133if p.histograms == nil || len(p.histograms) > 0 {
134p.histograms = map[uint64]*dto.Metric{}
135}
136p.currentQuantile = math.NaN()
137p.currentBucket = math.NaN()
138}
139
140// startOfLine represents the state where the next byte read from p.buf is the
141// start of a line (or whitespace leading up to it).
142func (p *TextParser) startOfLine() stateFn {
143p.lineCount++
144if p.skipBlankTab(); p.err != nil {
145// End of input reached. This is the only case where
146// that is not an error but a signal that we are done.
147p.err = nil
148return nil
149}
150switch p.currentByte {
151case '#':
152return p.startComment
153case '\n':
154return p.startOfLine // Empty line, start the next one.
155}
156return p.readingMetricName
157}
158
159// startComment represents the state where the next byte read from p.buf is the
160// start of a comment (or whitespace leading up to it).
161func (p *TextParser) startComment() stateFn {
162if p.skipBlankTab(); p.err != nil {
163return nil // Unexpected end of input.
164}
165if p.currentByte == '\n' {
166return p.startOfLine
167}
168if p.readTokenUntilWhitespace(); p.err != nil {
169return nil // Unexpected end of input.
170}
171// If we have hit the end of line already, there is nothing left
172// to do. This is not considered a syntax error.
173if p.currentByte == '\n' {
174return p.startOfLine
175}
176keyword := p.currentToken.String()
177if keyword != "HELP" && keyword != "TYPE" {
178// Generic comment, ignore by fast forwarding to end of line.
179for p.currentByte != '\n' {
180if p.currentByte, p.err = p.buf.ReadByte(); p.err != nil {
181return nil // Unexpected end of input.
182}
183}
184return p.startOfLine
185}
186// There is something. Next has to be a metric name.
187if p.skipBlankTab(); p.err != nil {
188return nil // Unexpected end of input.
189}
190if p.readTokenAsMetricName(); p.err != nil {
191return nil // Unexpected end of input.
192}
193if p.currentByte == '\n' {
194// At the end of the line already.
195// Again, this is not considered a syntax error.
196return p.startOfLine
197}
198if !isBlankOrTab(p.currentByte) {
199p.parseError("invalid metric name in comment")
200return nil
201}
202p.setOrCreateCurrentMF()
203if p.skipBlankTab(); p.err != nil {
204return nil // Unexpected end of input.
205}
206if p.currentByte == '\n' {
207// At the end of the line already.
208// Again, this is not considered a syntax error.
209return p.startOfLine
210}
211switch keyword {
212case "HELP":
213return p.readingHelp
214case "TYPE":
215return p.readingType
216}
217panic(fmt.Sprintf("code error: unexpected keyword %q", keyword))
218}
219
220// readingMetricName represents the state where the last byte read (now in
221// p.currentByte) is the first byte of a metric name.
222func (p *TextParser) readingMetricName() stateFn {
223if p.readTokenAsMetricName(); p.err != nil {
224return nil
225}
226if p.currentToken.Len() == 0 {
227p.parseError("invalid metric name")
228return nil
229}
230p.setOrCreateCurrentMF()
231// Now is the time to fix the type if it hasn't happened yet.
232if p.currentMF.Type == nil {
233p.currentMF.Type = dto.MetricType_UNTYPED.Enum()
234}
235p.currentMetric = &dto.Metric{}
236// Do not append the newly created currentMetric to
237// currentMF.Metric right now. First wait if this is a summary,
238// and the metric exists already, which we can only know after
239// having read all the labels.
240if p.skipBlankTabIfCurrentBlankTab(); p.err != nil {
241return nil // Unexpected end of input.
242}
243return p.readingLabels
244}
245
246// readingLabels represents the state where the last byte read (now in
247// p.currentByte) is either the first byte of the label set (i.e. a '{'), or the
248// first byte of the value (otherwise).
249func (p *TextParser) readingLabels() stateFn {
250// Summaries/histograms are special. We have to reset the
251// currentLabels map, currentQuantile and currentBucket before starting to
252// read labels.
253if p.currentMF.GetType() == dto.MetricType_SUMMARY || p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
254p.currentLabels = map[string]string{}
255p.currentLabels[string(model.MetricNameLabel)] = p.currentMF.GetName()
256p.currentQuantile = math.NaN()
257p.currentBucket = math.NaN()
258}
259if p.currentByte != '{' {
260return p.readingValue
261}
262return p.startLabelName
263}
264
265// startLabelName represents the state where the next byte read from p.buf is
266// the start of a label name (or whitespace leading up to it).
267func (p *TextParser) startLabelName() stateFn {
268if p.skipBlankTab(); p.err != nil {
269return nil // Unexpected end of input.
270}
271if p.currentByte == '}' {
272if p.skipBlankTab(); p.err != nil {
273return nil // Unexpected end of input.
274}
275return p.readingValue
276}
277if p.readTokenAsLabelName(); p.err != nil {
278return nil // Unexpected end of input.
279}
280if p.currentToken.Len() == 0 {
281p.parseError(fmt.Sprintf("invalid label name for metric %q", p.currentMF.GetName()))
282return nil
283}
284p.currentLabelPair = &dto.LabelPair{Name: proto.String(p.currentToken.String())}
285if p.currentLabelPair.GetName() == string(model.MetricNameLabel) {
286p.parseError(fmt.Sprintf("label name %q is reserved", model.MetricNameLabel))
287return nil
288}
289// Special summary/histogram treatment. Don't add 'quantile' and 'le'
290// labels to 'real' labels.
291if !(p.currentMF.GetType() == dto.MetricType_SUMMARY && p.currentLabelPair.GetName() == model.QuantileLabel) &&
292!(p.currentMF.GetType() == dto.MetricType_HISTOGRAM && p.currentLabelPair.GetName() == model.BucketLabel) {
293p.currentMetric.Label = append(p.currentMetric.Label, p.currentLabelPair)
294}
295if p.skipBlankTabIfCurrentBlankTab(); p.err != nil {
296return nil // Unexpected end of input.
297}
298if p.currentByte != '=' {
299p.parseError(fmt.Sprintf("expected '=' after label name, found %q", p.currentByte))
300return nil
301}
302// Check for duplicate label names.
303labels := make(map[string]struct{})
304for _, l := range p.currentMetric.Label {
305lName := l.GetName()
306if _, exists := labels[lName]; !exists {
307labels[lName] = struct{}{}
308} else {
309p.parseError(fmt.Sprintf("duplicate label names for metric %q", p.currentMF.GetName()))
310return nil
311}
312}
313return p.startLabelValue
314}
315
316// startLabelValue represents the state where the next byte read from p.buf is
317// the start of a (quoted) label value (or whitespace leading up to it).
318func (p *TextParser) startLabelValue() stateFn {
319if p.skipBlankTab(); p.err != nil {
320return nil // Unexpected end of input.
321}
322if p.currentByte != '"' {
323p.parseError(fmt.Sprintf("expected '\"' at start of label value, found %q", p.currentByte))
324return nil
325}
326if p.readTokenAsLabelValue(); p.err != nil {
327return nil
328}
329if !model.LabelValue(p.currentToken.String()).IsValid() {
330p.parseError(fmt.Sprintf("invalid label value %q", p.currentToken.String()))
331return nil
332}
333p.currentLabelPair.Value = proto.String(p.currentToken.String())
334// Special treatment of summaries:
335// - Quantile labels are special, will result in dto.Quantile later.
336// - Other labels have to be added to currentLabels for signature calculation.
337if p.currentMF.GetType() == dto.MetricType_SUMMARY {
338if p.currentLabelPair.GetName() == model.QuantileLabel {
339if p.currentQuantile, p.err = parseFloat(p.currentLabelPair.GetValue()); p.err != nil {
340// Create a more helpful error message.
341p.parseError(fmt.Sprintf("expected float as value for 'quantile' label, got %q", p.currentLabelPair.GetValue()))
342return nil
343}
344} else {
345p.currentLabels[p.currentLabelPair.GetName()] = p.currentLabelPair.GetValue()
346}
347}
348// Similar special treatment of histograms.
349if p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
350if p.currentLabelPair.GetName() == model.BucketLabel {
351if p.currentBucket, p.err = parseFloat(p.currentLabelPair.GetValue()); p.err != nil {
352// Create a more helpful error message.
353p.parseError(fmt.Sprintf("expected float as value for 'le' label, got %q", p.currentLabelPair.GetValue()))
354return nil
355}
356} else {
357p.currentLabels[p.currentLabelPair.GetName()] = p.currentLabelPair.GetValue()
358}
359}
360if p.skipBlankTab(); p.err != nil {
361return nil // Unexpected end of input.
362}
363switch p.currentByte {
364case ',':
365return p.startLabelName
366
367case '}':
368if p.skipBlankTab(); p.err != nil {
369return nil // Unexpected end of input.
370}
371return p.readingValue
372default:
373p.parseError(fmt.Sprintf("unexpected end of label value %q", p.currentLabelPair.GetValue()))
374return nil
375}
376}
377
378// readingValue represents the state where the last byte read (now in
379// p.currentByte) is the first byte of the sample value (i.e. a float).
380func (p *TextParser) readingValue() stateFn {
381// When we are here, we have read all the labels, so for the
382// special case of a summary/histogram, we can finally find out
383// if the metric already exists.
384if p.currentMF.GetType() == dto.MetricType_SUMMARY {
385signature := model.LabelsToSignature(p.currentLabels)
386if summary := p.summaries[signature]; summary != nil {
387p.currentMetric = summary
388} else {
389p.summaries[signature] = p.currentMetric
390p.currentMF.Metric = append(p.currentMF.Metric, p.currentMetric)
391}
392} else if p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
393signature := model.LabelsToSignature(p.currentLabels)
394if histogram := p.histograms[signature]; histogram != nil {
395p.currentMetric = histogram
396} else {
397p.histograms[signature] = p.currentMetric
398p.currentMF.Metric = append(p.currentMF.Metric, p.currentMetric)
399}
400} else {
401p.currentMF.Metric = append(p.currentMF.Metric, p.currentMetric)
402}
403if p.readTokenUntilWhitespace(); p.err != nil {
404return nil // Unexpected end of input.
405}
406value, err := parseFloat(p.currentToken.String())
407if err != nil {
408// Create a more helpful error message.
409p.parseError(fmt.Sprintf("expected float as value, got %q", p.currentToken.String()))
410return nil
411}
412switch p.currentMF.GetType() {
413case dto.MetricType_COUNTER:
414p.currentMetric.Counter = &dto.Counter{Value: proto.Float64(value)}
415case dto.MetricType_GAUGE:
416p.currentMetric.Gauge = &dto.Gauge{Value: proto.Float64(value)}
417case dto.MetricType_UNTYPED:
418p.currentMetric.Untyped = &dto.Untyped{Value: proto.Float64(value)}
419case dto.MetricType_SUMMARY:
420// *sigh*
421if p.currentMetric.Summary == nil {
422p.currentMetric.Summary = &dto.Summary{}
423}
424switch {
425case p.currentIsSummaryCount:
426p.currentMetric.Summary.SampleCount = proto.Uint64(uint64(value))
427case p.currentIsSummarySum:
428p.currentMetric.Summary.SampleSum = proto.Float64(value)
429case !math.IsNaN(p.currentQuantile):
430p.currentMetric.Summary.Quantile = append(
431p.currentMetric.Summary.Quantile,
432&dto.Quantile{
433Quantile: proto.Float64(p.currentQuantile),
434Value: proto.Float64(value),
435},
436)
437}
438case dto.MetricType_HISTOGRAM:
439// *sigh*
440if p.currentMetric.Histogram == nil {
441p.currentMetric.Histogram = &dto.Histogram{}
442}
443switch {
444case p.currentIsHistogramCount:
445p.currentMetric.Histogram.SampleCount = proto.Uint64(uint64(value))
446case p.currentIsHistogramSum:
447p.currentMetric.Histogram.SampleSum = proto.Float64(value)
448case !math.IsNaN(p.currentBucket):
449p.currentMetric.Histogram.Bucket = append(
450p.currentMetric.Histogram.Bucket,
451&dto.Bucket{
452UpperBound: proto.Float64(p.currentBucket),
453CumulativeCount: proto.Uint64(uint64(value)),
454},
455)
456}
457default:
458p.err = fmt.Errorf("unexpected type for metric name %q", p.currentMF.GetName())
459}
460if p.currentByte == '\n' {
461return p.startOfLine
462}
463return p.startTimestamp
464}
465
466// startTimestamp represents the state where the next byte read from p.buf is
467// the start of the timestamp (or whitespace leading up to it).
468func (p *TextParser) startTimestamp() stateFn {
469if p.skipBlankTab(); p.err != nil {
470return nil // Unexpected end of input.
471}
472if p.readTokenUntilWhitespace(); p.err != nil {
473return nil // Unexpected end of input.
474}
475timestamp, err := strconv.ParseInt(p.currentToken.String(), 10, 64)
476if err != nil {
477// Create a more helpful error message.
478p.parseError(fmt.Sprintf("expected integer as timestamp, got %q", p.currentToken.String()))
479return nil
480}
481p.currentMetric.TimestampMs = proto.Int64(timestamp)
482if p.readTokenUntilNewline(false); p.err != nil {
483return nil // Unexpected end of input.
484}
485if p.currentToken.Len() > 0 {
486p.parseError(fmt.Sprintf("spurious string after timestamp: %q", p.currentToken.String()))
487return nil
488}
489return p.startOfLine
490}
491
492// readingHelp represents the state where the last byte read (now in
493// p.currentByte) is the first byte of the docstring after 'HELP'.
494func (p *TextParser) readingHelp() stateFn {
495if p.currentMF.Help != nil {
496p.parseError(fmt.Sprintf("second HELP line for metric name %q", p.currentMF.GetName()))
497return nil
498}
499// Rest of line is the docstring.
500if p.readTokenUntilNewline(true); p.err != nil {
501return nil // Unexpected end of input.
502}
503p.currentMF.Help = proto.String(p.currentToken.String())
504return p.startOfLine
505}
506
507// readingType represents the state where the last byte read (now in
508// p.currentByte) is the first byte of the type hint after 'HELP'.
509func (p *TextParser) readingType() stateFn {
510if p.currentMF.Type != nil {
511p.parseError(fmt.Sprintf("second TYPE line for metric name %q, or TYPE reported after samples", p.currentMF.GetName()))
512return nil
513}
514// Rest of line is the type.
515if p.readTokenUntilNewline(false); p.err != nil {
516return nil // Unexpected end of input.
517}
518metricType, ok := dto.MetricType_value[strings.ToUpper(p.currentToken.String())]
519if !ok {
520p.parseError(fmt.Sprintf("unknown metric type %q", p.currentToken.String()))
521return nil
522}
523p.currentMF.Type = dto.MetricType(metricType).Enum()
524return p.startOfLine
525}
526
527// parseError sets p.err to a ParseError at the current line with the given
528// message.
529func (p *TextParser) parseError(msg string) {
530p.err = ParseError{
531Line: p.lineCount,
532Msg: msg,
533}
534}
535
536// skipBlankTab reads (and discards) bytes from p.buf until it encounters a byte
537// that is neither ' ' nor '\t'. That byte is left in p.currentByte.
538func (p *TextParser) skipBlankTab() {
539for {
540if p.currentByte, p.err = p.buf.ReadByte(); p.err != nil || !isBlankOrTab(p.currentByte) {
541return
542}
543}
544}
545
546// skipBlankTabIfCurrentBlankTab works exactly as skipBlankTab but doesn't do
547// anything if p.currentByte is neither ' ' nor '\t'.
548func (p *TextParser) skipBlankTabIfCurrentBlankTab() {
549if isBlankOrTab(p.currentByte) {
550p.skipBlankTab()
551}
552}
553
554// readTokenUntilWhitespace copies bytes from p.buf into p.currentToken. The
555// first byte considered is the byte already read (now in p.currentByte). The
556// first whitespace byte encountered is still copied into p.currentByte, but not
557// into p.currentToken.
558func (p *TextParser) readTokenUntilWhitespace() {
559p.currentToken.Reset()
560for p.err == nil && !isBlankOrTab(p.currentByte) && p.currentByte != '\n' {
561p.currentToken.WriteByte(p.currentByte)
562p.currentByte, p.err = p.buf.ReadByte()
563}
564}
565
566// readTokenUntilNewline copies bytes from p.buf into p.currentToken. The first
567// byte considered is the byte already read (now in p.currentByte). The first
568// newline byte encountered is still copied into p.currentByte, but not into
569// p.currentToken. If recognizeEscapeSequence is true, two escape sequences are
570// recognized: '\\' translates into '\', and '\n' into a line-feed character.
571// All other escape sequences are invalid and cause an error.
572func (p *TextParser) readTokenUntilNewline(recognizeEscapeSequence bool) {
573p.currentToken.Reset()
574escaped := false
575for p.err == nil {
576if recognizeEscapeSequence && escaped {
577switch p.currentByte {
578case '\\':
579p.currentToken.WriteByte(p.currentByte)
580case 'n':
581p.currentToken.WriteByte('\n')
582default:
583p.parseError(fmt.Sprintf("invalid escape sequence '\\%c'", p.currentByte))
584return
585}
586escaped = false
587} else {
588switch p.currentByte {
589case '\n':
590return
591case '\\':
592escaped = true
593default:
594p.currentToken.WriteByte(p.currentByte)
595}
596}
597p.currentByte, p.err = p.buf.ReadByte()
598}
599}
600
601// readTokenAsMetricName copies a metric name from p.buf into p.currentToken.
602// The first byte considered is the byte already read (now in p.currentByte).
603// The first byte not part of a metric name is still copied into p.currentByte,
604// but not into p.currentToken.
605func (p *TextParser) readTokenAsMetricName() {
606p.currentToken.Reset()
607if !isValidMetricNameStart(p.currentByte) {
608return
609}
610for {
611p.currentToken.WriteByte(p.currentByte)
612p.currentByte, p.err = p.buf.ReadByte()
613if p.err != nil || !isValidMetricNameContinuation(p.currentByte) {
614return
615}
616}
617}
618
619// readTokenAsLabelName copies a label name from p.buf into p.currentToken.
620// The first byte considered is the byte already read (now in p.currentByte).
621// The first byte not part of a label name is still copied into p.currentByte,
622// but not into p.currentToken.
623func (p *TextParser) readTokenAsLabelName() {
624p.currentToken.Reset()
625if !isValidLabelNameStart(p.currentByte) {
626return
627}
628for {
629p.currentToken.WriteByte(p.currentByte)
630p.currentByte, p.err = p.buf.ReadByte()
631if p.err != nil || !isValidLabelNameContinuation(p.currentByte) {
632return
633}
634}
635}
636
637// readTokenAsLabelValue copies a label value from p.buf into p.currentToken.
638// In contrast to the other 'readTokenAs...' functions, which start with the
639// last read byte in p.currentByte, this method ignores p.currentByte and starts
640// with reading a new byte from p.buf. The first byte not part of a label value
641// is still copied into p.currentByte, but not into p.currentToken.
642func (p *TextParser) readTokenAsLabelValue() {
643p.currentToken.Reset()
644escaped := false
645for {
646if p.currentByte, p.err = p.buf.ReadByte(); p.err != nil {
647return
648}
649if escaped {
650switch p.currentByte {
651case '"', '\\':
652p.currentToken.WriteByte(p.currentByte)
653case 'n':
654p.currentToken.WriteByte('\n')
655default:
656p.parseError(fmt.Sprintf("invalid escape sequence '\\%c'", p.currentByte))
657return
658}
659escaped = false
660continue
661}
662switch p.currentByte {
663case '"':
664return
665case '\n':
666p.parseError(fmt.Sprintf("label value %q contains unescaped new-line", p.currentToken.String()))
667return
668case '\\':
669escaped = true
670default:
671p.currentToken.WriteByte(p.currentByte)
672}
673}
674}
675
676func (p *TextParser) setOrCreateCurrentMF() {
677p.currentIsSummaryCount = false
678p.currentIsSummarySum = false
679p.currentIsHistogramCount = false
680p.currentIsHistogramSum = false
681name := p.currentToken.String()
682if p.currentMF = p.metricFamiliesByName[name]; p.currentMF != nil {
683return
684}
685// Try out if this is a _sum or _count for a summary/histogram.
686summaryName := summaryMetricName(name)
687if p.currentMF = p.metricFamiliesByName[summaryName]; p.currentMF != nil {
688if p.currentMF.GetType() == dto.MetricType_SUMMARY {
689if isCount(name) {
690p.currentIsSummaryCount = true
691}
692if isSum(name) {
693p.currentIsSummarySum = true
694}
695return
696}
697}
698histogramName := histogramMetricName(name)
699if p.currentMF = p.metricFamiliesByName[histogramName]; p.currentMF != nil {
700if p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
701if isCount(name) {
702p.currentIsHistogramCount = true
703}
704if isSum(name) {
705p.currentIsHistogramSum = true
706}
707return
708}
709}
710p.currentMF = &dto.MetricFamily{Name: proto.String(name)}
711p.metricFamiliesByName[name] = p.currentMF
712}
713
714func isValidLabelNameStart(b byte) bool {
715return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_'
716}
717
718func isValidLabelNameContinuation(b byte) bool {
719return isValidLabelNameStart(b) || (b >= '0' && b <= '9')
720}
721
722func isValidMetricNameStart(b byte) bool {
723return isValidLabelNameStart(b) || b == ':'
724}
725
726func isValidMetricNameContinuation(b byte) bool {
727return isValidLabelNameContinuation(b) || b == ':'
728}
729
730func isBlankOrTab(b byte) bool {
731return b == ' ' || b == '\t'
732}
733
734func isCount(name string) bool {
735return len(name) > 6 && name[len(name)-6:] == "_count"
736}
737
738func isSum(name string) bool {
739return len(name) > 4 && name[len(name)-4:] == "_sum"
740}
741
742func isBucket(name string) bool {
743return len(name) > 7 && name[len(name)-7:] == "_bucket"
744}
745
746func summaryMetricName(name string) string {
747switch {
748case isCount(name):
749return name[:len(name)-6]
750case isSum(name):
751return name[:len(name)-4]
752default:
753return name
754}
755}
756
757func histogramMetricName(name string) string {
758switch {
759case isCount(name):
760return name[:len(name)-6]
761case isSum(name):
762return name[:len(name)-4]
763case isBucket(name):
764return name[:len(name)-7]
765default:
766return name
767}
768}
769
770func parseFloat(s string) (float64, error) {
771if strings.ContainsAny(s, "pP_") {
772return 0, fmt.Errorf("unsupported character in float")
773}
774return strconv.ParseFloat(s, 64)
775}
776