text_parse.go 25 KB

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