...

Source file src/github.com/go-kit/kit/metrics/teststat/buffers.go

Documentation: github.com/go-kit/kit/metrics/teststat

     1  package teststat
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"io"
     7  	"regexp"
     8  	"strconv"
     9  
    10  	"github.com/go-kit/kit/metrics/generic"
    11  )
    12  
    13  // SumLines expects a regex whose first capture group can be parsed as a
    14  // float64. It will dump the WriterTo and parse each line, expecting to find a
    15  // match. It returns the sum of all captured floats.
    16  func SumLines(w io.WriterTo, regex string) func() float64 {
    17  	return func() float64 {
    18  		sum, _ := stats(w, regex, nil)
    19  		return sum
    20  	}
    21  }
    22  
    23  // LastLine expects a regex whose first capture group can be parsed as a
    24  // float64. It will dump the WriterTo and parse each line, expecting to find a
    25  // match. It returns the final captured float.
    26  func LastLine(w io.WriterTo, regex string) func() []float64 {
    27  	return func() []float64 {
    28  		_, final := stats(w, regex, nil)
    29  		return []float64{final}
    30  	}
    31  }
    32  
    33  // Quantiles expects a regex whose first capture group can be parsed as a
    34  // float64. It will dump the WriterTo and parse each line, expecting to find a
    35  // match. It observes all captured floats into a generic.Histogram with the
    36  // given number of buckets, and returns the 50th, 90th, 95th, and 99th quantiles
    37  // from that histogram.
    38  func Quantiles(w io.WriterTo, regex string, buckets int) func() (float64, float64, float64, float64) {
    39  	return func() (float64, float64, float64, float64) {
    40  		h := generic.NewHistogram("quantile-test", buckets)
    41  		stats(w, regex, h)
    42  		return h.Quantile(0.50), h.Quantile(0.90), h.Quantile(0.95), h.Quantile(0.99)
    43  	}
    44  }
    45  
    46  func stats(w io.WriterTo, regex string, h *generic.Histogram) (sum, final float64) {
    47  	re := regexp.MustCompile(regex)
    48  	buf := &bytes.Buffer{}
    49  	w.WriteTo(buf)
    50  	s := bufio.NewScanner(buf)
    51  	for s.Scan() {
    52  		match := re.FindStringSubmatch(s.Text())
    53  		f, err := strconv.ParseFloat(match[1], 64)
    54  		if err != nil {
    55  			panic(err)
    56  		}
    57  		sum += f
    58  		final = f
    59  		if h != nil {
    60  			h.Observe(f)
    61  		}
    62  	}
    63  	return sum, final
    64  }
    65  

View as plain text