Example #1
0
func TestWrite(t *testing.T) {
	var wg sync.WaitGroup
	wg.Add(1)
	go TCPServer(t, &wg)
	// Give the fake TCP server some time to start:
	time.Sleep(time.Millisecond * 100)

	i := Instrumental{
		Host:     "127.0.0.1",
		ApiToken: "abc123token",
		Prefix:   "my.prefix",
	}
	i.Connect()

	// Default to gauge
	m1, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1"},
		map[string]interface{}{"myfield": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	m2, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1", "metric_type": "set"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)

	// Simulate a connection close and reconnect.
	metrics := []telegraf.Metric{m1, m2}
	i.Write(metrics)
	i.Close()

	// Counter and Histogram are increments
	m3, _ := telegraf.NewMetric(
		"my_histogram",
		map[string]string{"host": "192.168.0.1", "metric_type": "histogram"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	// We will drop metrics that simply won't be accepted by Instrumental
	m4, _ := telegraf.NewMetric(
		"bad_values",
		map[string]string{"host": "192.168.0.1", "metric_type": "counter"},
		map[string]interface{}{"value": "\" 3:30\""},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	m5, _ := telegraf.NewMetric(
		"my_counter",
		map[string]string{"host": "192.168.0.1", "metric_type": "counter"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)

	metrics = []telegraf.Metric{m3, m4, m5}
	i.Write(metrics)

	wg.Wait()
	i.Close()
}
Example #2
0
func TestGraphiteTags(t *testing.T) {
	m1, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	m2, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1", "afoo": "first", "bfoo": "second"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	m3, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"afoo": "first", "bfoo": "second"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)

	tags1 := buildTags(m1)
	tags2 := buildTags(m2)
	tags3 := buildTags(m3)

	assert.Equal(t, "192_168_0_1", tags1)
	assert.Equal(t, "192_168_0_1.first.second", tags2)
	assert.Equal(t, "first.second", tags3)
}
Example #3
0
func TestBuildGaugeWithSource(t *testing.T) {
	pt1, _ := telegraf.NewMetric(
		"test1",
		map[string]string{"hostname": "192.168.0.1"},
		map[string]interface{}{"value": 0.0},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	pt2, _ := telegraf.NewMetric(
		"test2",
		map[string]string{"hostnam": "192.168.0.1"},
		map[string]interface{}{"value": 1.0},
		time.Date(2010, time.December, 10, 23, 0, 0, 0, time.UTC),
	)
	var gaugeTests = []struct {
		ptIn     telegraf.Metric
		outGauge *Gauge
		err      error
	}{

		{
			pt1,
			&Gauge{
				Name:        "test1",
				MeasureTime: time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC).Unix(),
				Value:       0.0,
				Source:      "192.168.0.1",
			},
			nil,
		},
		{
			pt2,
			&Gauge{
				Name:        "test2",
				MeasureTime: time.Date(2010, time.December, 10, 23, 0, 0, 0, time.UTC).Unix(),
				Value:       1.0,
			},
			fmt.Errorf("undeterminable Source type from Field, hostname"),
		},
	}

	l := NewLibrato(fakeUrl)
	l.SourceTag = "hostname"
	for _, gt := range gaugeTests {
		gauges, err := l.buildGauges(gt.ptIn)
		if err != nil && gt.err == nil {
			t.Errorf("%s: unexpected error, %+v\n", gt.ptIn.Name(), err)
		}
		if gt.err != nil && err == nil {
			t.Errorf("%s: expected an error (%s) but none returned", gt.ptIn.Name(), gt.err.Error())
		}
		if len(gauges) == 0 {
			continue
		}
		if gt.err == nil && !reflect.DeepEqual(gauges[0], gt.outGauge) {
			t.Errorf("%s: \nexpected %+v\ngot %+v\n", gt.ptIn.Name(), gt.outGauge, gauges[0])
		}
	}
}
func TestSerializeMetricPrefix(t *testing.T) {
	now := time.Now()
	tags := map[string]string{
		"host":       "localhost",
		"cpu":        "cpu0",
		"datacenter": "us-west-2",
	}
	fields := map[string]interface{}{
		"usage_idle": float64(91.5),
		"usage_busy": float64(8.5),
	}
	m, err := telegraf.NewMetric("cpu", tags, fields, now)
	assert.NoError(t, err)

	s := GraphiteSerializer{Prefix: "prefix"}
	mS, err := s.Serialize(m)
	assert.NoError(t, err)

	expS := []string{
		fmt.Sprintf("prefix.localhost.cpu0.us-west-2.cpu.usage_idle 91.5 %d", now.Unix()),
		fmt.Sprintf("prefix.localhost.cpu0.us-west-2.cpu.usage_busy 8.5 %d", now.Unix()),
	}
	sort.Strings(mS)
	sort.Strings(expS)
	assert.Equal(t, expS, mS)
}
Example #5
0
// AddMetric adds a metric to the output. This function can also write cached
// points if FlushBufferWhenFull is true.
func (ro *RunningOutput) AddMetric(metric telegraf.Metric) {
	if ro.Config.Filter.IsActive {
		if !ro.Config.Filter.ShouldMetricPass(metric) {
			return
		}
	}

	// Filter any tagexclude/taginclude parameters before adding metric
	if len(ro.Config.Filter.TagExclude) != 0 || len(ro.Config.Filter.TagInclude) != 0 {
		// In order to filter out tags, we need to create a new metric, since
		// metrics are immutable once created.
		tags := metric.Tags()
		fields := metric.Fields()
		t := metric.Time()
		name := metric.Name()
		ro.Config.Filter.FilterTags(tags)
		// error is not possible if creating from another metric, so ignore.
		metric, _ = telegraf.NewMetric(name, tags, fields, t)
	}

	ro.metrics.Add(metric)
	if ro.metrics.Len() == ro.MetricBatchSize {
		batch := ro.metrics.Batch(ro.MetricBatchSize)
		err := ro.write(batch)
		if err != nil {
			ro.failMetrics.Add(batch...)
		}
	}
}
func (s PullRequestReviewCommentEvent) NewMetric() telegraf.Metric {
	event := "pull_request_review_comment"
	t := map[string]string{
		"event":      event,
		"repository": s.Repository.Repository,
		"private":    fmt.Sprintf("%v", s.Repository.Private),
		"user":       s.Sender.User,
		"admin":      fmt.Sprintf("%v", s.Sender.Admin),
		"prNumber":   fmt.Sprintf("%v", s.PullRequest.Number),
	}
	f := map[string]interface{}{
		"stars":        s.Repository.Stars,
		"forks":        s.Repository.Forks,
		"issues":       s.Repository.Issues,
		"state":        s.PullRequest.State,
		"title":        s.PullRequest.Title,
		"comments":     s.PullRequest.Comments,
		"commits":      s.PullRequest.Commits,
		"additions":    s.PullRequest.Additions,
		"deletions":    s.PullRequest.Deletions,
		"changedFiles": s.PullRequest.ChangedFiles,
		"commentFile":  s.Comment.File,
		"comment":      s.Comment.Comment,
	}
	m, err := telegraf.NewMetric(meas, t, f, time.Now())
	if err != nil {
		log.Fatalf("Failed to create %v event", event)
	}
	return m
}
func (s DeploymentStatusEvent) NewMetric() telegraf.Metric {
	event := "delete"
	t := map[string]string{
		"event":      event,
		"repository": s.Repository.Repository,
		"private":    fmt.Sprintf("%v", s.Repository.Private),
		"user":       s.Sender.User,
		"admin":      fmt.Sprintf("%v", s.Sender.Admin),
	}
	f := map[string]interface{}{
		"stars":          s.Repository.Stars,
		"forks":          s.Repository.Forks,
		"issues":         s.Repository.Issues,
		"commit":         s.Deployment.Commit,
		"task":           s.Deployment.Task,
		"environment":    s.Deployment.Environment,
		"description":    s.Deployment.Description,
		"depState":       s.DeploymentStatus.State,
		"depDescription": s.DeploymentStatus.Description,
	}
	m, err := telegraf.NewMetric(meas, t, f, time.Now())
	if err != nil {
		log.Fatalf("Failed to create %v event", event)
	}
	return m
}
Example #8
0
func (v *ValueParser) Parse(buf []byte) ([]telegraf.Metric, error) {
	// separate out any fields in the buffer, ignore anything but the last.
	values := bytes.Fields(buf)
	if len(values) < 1 {
		return []telegraf.Metric{}, nil
	}
	valueStr := string(values[len(values)-1])

	var value interface{}
	var err error
	switch v.DataType {
	case "", "int", "integer":
		value, err = strconv.Atoi(valueStr)
	case "float", "long":
		value, err = strconv.ParseFloat(valueStr, 64)
	case "str", "string":
		value = valueStr
	case "bool", "boolean":
		value, err = strconv.ParseBool(valueStr)
	}
	if err != nil {
		return nil, err
	}

	fields := map[string]interface{}{"value": value}
	metric, err := telegraf.NewMetric(v.MetricName, v.DefaultTags,
		fields, time.Now().UTC())
	if err != nil {
		return nil, err
	}

	return []telegraf.Metric{metric}, nil
}
Example #9
0
func TestGraphiteOK(t *testing.T) {
	var wg sync.WaitGroup
	// Init plugin
	g := Graphite{
		Prefix: "my.prefix",
	}
	// Init metrics
	pt1, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1"},
		map[string]interface{}{"mymeasurement": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	pt2, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	pt3, _ := telegraf.NewMetric(
		"my_measurement",
		map[string]string{"host": "192.168.0.1"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	// Prepare point list
	var metrics []telegraf.Metric
	metrics = append(metrics, pt1)
	metrics = append(metrics, pt2)
	metrics = append(metrics, pt3)
	// Start TCP server
	wg.Add(1)
	go TCPServer(t, &wg)
	wg.Wait()
	// Connect
	wg.Add(1)
	err1 := g.Connect()
	wg.Wait()
	require.NoError(t, err1)
	// Send Data
	err2 := g.Write(metrics)
	require.NoError(t, err2)
	wg.Add(1)
	// Waiting TCPserver
	wg.Wait()
	g.Close()
}
Example #10
0
// Parse performs Graphite parsing of a single line.
func (p *GraphiteParser) ParseLine(line string) (telegraf.Metric, error) {
	// Break into 3 fields (name, value, timestamp).
	fields := strings.Fields(line)
	if len(fields) != 2 && len(fields) != 3 {
		return nil, fmt.Errorf("received %q which doesn't have required fields", line)
	}

	// decode the name and tags
	template := p.matcher.Match(fields[0])
	measurement, tags, field, err := template.Apply(fields[0])
	if err != nil {
		return nil, err
	}

	// Could not extract measurement, use the raw value
	if measurement == "" {
		measurement = fields[0]
	}

	// Parse value.
	v, err := strconv.ParseFloat(fields[1], 64)
	if err != nil {
		return nil, fmt.Errorf(`field "%s" value: %s`, fields[0], err)
	}

	if math.IsNaN(v) || math.IsInf(v, 0) {
		return nil, &UnsupposedValueError{Field: fields[0], Value: v}
	}

	fieldValues := map[string]interface{}{}
	if field != "" {
		fieldValues[field] = v
	} else {
		fieldValues["value"] = v
	}

	// If no 3rd field, use now as timestamp
	timestamp := time.Now().UTC()

	if len(fields) == 3 {
		// Parse timestamp.
		unixTime, err := strconv.ParseFloat(fields[2], 64)
		if err != nil {
			return nil, fmt.Errorf(`field "%s" time: %s`, fields[0], err)
		}

		// -1 is a special value that gets converted to current UTC time
		// See https://github.com/graphite-project/carbon/issues/54
		if unixTime != float64(-1) {
			// Check if we have fractional seconds
			timestamp = time.Unix(int64(unixTime), int64((unixTime-math.Floor(unixTime))*float64(time.Second)))
			if timestamp.Before(MinDate) || timestamp.After(MaxDate) {
				return nil, fmt.Errorf("timestamp out of range")
			}
		}
	}

	return telegraf.NewMetric(measurement, tags, fieldValues, timestamp)
}
Example #11
0
// AddMetric adds a metric to the output. This function can also write cached
// points if FlushBufferWhenFull is true.
func (ro *RunningOutput) AddMetric(metric telegraf.Metric) {
	if ro.Config.Filter.IsActive {
		if !ro.Config.Filter.ShouldMetricPass(metric) {
			return
		}
	}
	ro.Lock()
	defer ro.Unlock()

	// Filter any tagexclude/taginclude parameters before adding metric
	if len(ro.Config.Filter.TagExclude) != 0 || len(ro.Config.Filter.TagInclude) != 0 {
		// In order to filter out tags, we need to create a new metric, since
		// metrics are immutable once created.
		tags := metric.Tags()
		fields := metric.Fields()
		t := metric.Time()
		name := metric.Name()
		ro.Config.Filter.FilterTags(tags)
		// error is not possible if creating from another metric, so ignore.
		metric, _ = telegraf.NewMetric(name, tags, fields, t)
	}

	if len(ro.metrics) < ro.MetricBufferLimit {
		ro.metrics = append(ro.metrics, metric)
	} else {
		if ro.FlushBufferWhenFull {
			ro.metrics = append(ro.metrics, metric)
			tmpmetrics := make([]telegraf.Metric, len(ro.metrics))
			copy(tmpmetrics, ro.metrics)
			ro.metrics = make([]telegraf.Metric, 0)
			err := ro.write(tmpmetrics)
			if err != nil {
				log.Printf("ERROR writing full metric buffer to output %s, %s",
					ro.Name, err)
				if len(ro.tmpmetrics) == FULL_METRIC_BUFFERS_LIMIT {
					ro.mapI = 0
					// overwrite one
					ro.tmpmetrics[ro.mapI] = tmpmetrics
					ro.mapI++
				} else {
					ro.tmpmetrics[ro.mapI] = tmpmetrics
					ro.mapI++
				}
			}
		} else {
			if ro.overwriteI == 0 {
				log.Printf("WARNING: overwriting cached metrics, you may want to " +
					"increase the metric_buffer_limit setting in your [agent] " +
					"config if you do not wish to overwrite metrics.\n")
			}
			if ro.overwriteI == len(ro.metrics) {
				ro.overwriteI = 0
			}
			ro.metrics[ro.overwriteI] = metric
			ro.overwriteI++
		}
	}
}
Example #12
0
func newHostMetric(value interface{}, name, host string) (metric telegraf.Metric) {
	metric, _ = telegraf.NewMetric(
		name,
		map[string]string{"host": host},
		map[string]interface{}{"value": value},
		time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	return
}
Example #13
0
func TestGraphiteOK(t *testing.T) {
	var wg sync.WaitGroup
	// Start TCP server
	wg.Add(1)
	go TCPServer(t, &wg)
	// Give the fake graphite TCP server some time to start:
	time.Sleep(time.Millisecond * 100)

	// Init plugin
	g := Graphite{
		Prefix: "my.prefix",
	}
	// Init metrics
	m1, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1"},
		map[string]interface{}{"mymeasurement": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	m2, _ := telegraf.NewMetric(
		"mymeasurement",
		map[string]string{"host": "192.168.0.1"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	m3, _ := telegraf.NewMetric(
		"my_measurement",
		map[string]string{"host": "192.168.0.1"},
		map[string]interface{}{"value": float64(3.14)},
		time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
	)

	// Prepare point list
	metrics := []telegraf.Metric{m1, m2, m3}
	err1 := g.Connect()
	require.NoError(t, err1)
	// Send Data
	err2 := g.Write(metrics)
	require.NoError(t, err2)

	// Waiting TCPserver
	wg.Wait()
	g.Close()
}
func TestPrometheusWritePointTag(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping integration test in short mode")
	}

	p := &prometheus.Prometheus{
		Urls: []string{"http://localhost:9126/metrics"},
	}
	tags := make(map[string]string)
	tags["testtag"] = "testvalue"
	pt1, _ := telegraf.NewMetric(
		"test_point_3",
		tags,
		map[string]interface{}{"value": 0.0})
	pt2, _ := telegraf.NewMetric(
		"test_point_4",
		tags,
		map[string]interface{}{"value": 1.0})
	var metrics = []telegraf.Metric{
		pt1,
		pt2,
	}
	require.NoError(t, pTesting.Write(metrics))

	expected := []struct {
		name  string
		value float64
	}{
		{"test_point_3", 0.0},
		{"test_point_4", 1.0},
	}

	var acc testutil.Accumulator

	require.NoError(t, p.Gather(&acc))
	for _, e := range expected {
		acc.AssertContainsFields(t, "prometheus_"+e.name,
			map[string]interface{}{"value": e.value})
	}
}
Example #15
0
func TestTemplate6(t *testing.T) {
	now := time.Now()
	fields := map[string]interface{}{
		"usage_idle": float64(91.5),
	}
	m, err := telegraf.NewMetric("cpu", defaultTags, fields, now)
	assert.NoError(t, err)

	mS := SerializeBucketName(m.Name(), m.Tags(), template6, "")

	expS := "localhost.cpu0.us-west-2.cpu.FIELDNAME"
	assert.Equal(t, expS, mS)
}
Example #16
0
func TestSerializeBucketNamePrefix(t *testing.T) {
	now := time.Now()
	fields := map[string]interface{}{
		"usage_idle": float64(91.5),
	}
	m, err := telegraf.NewMetric("cpu", defaultTags, fields, now)
	assert.NoError(t, err)

	s := GraphiteSerializer{Prefix: "prefix"}
	mS := s.SerializeBucketName(m.Name(), m.Tags())

	expS := "prefix.localhost.cpu0.us-west-2.cpu.FIELDNAME"
	assert.Equal(t, expS, mS)
}
Example #17
0
func copyMetric(m telegraf.Metric) telegraf.Metric {
	t := time.Time(m.Time())

	tags := make(map[string]string)
	fields := make(map[string]interface{})
	for k, v := range m.Tags() {
		tags[k] = v
	}
	for k, v := range m.Fields() {
		fields[k] = v
	}

	out, _ := telegraf.NewMetric(m.Name(), tags, fields, t)
	return out
}
Example #18
0
func TestFilterMatchSingle(t *testing.T) {
	p, err := NewGraphiteParser("", []string{"servers.localhost .host.measurement*"}, nil)
	if err != nil {
		t.Fatalf("unexpected error creating parser, got %v", err)
	}

	exp, err := telegraf.NewMetric("cpu_load",
		map[string]string{"host": "localhost"},
		map[string]interface{}{"value": float64(11)},
		time.Unix(1435077219, 0))

	m, err := p.ParseLine("servers.localhost.cpu_load 11 1435077219")
	assert.NoError(t, err)

	assert.Equal(t, exp.String(), m.String())
}
Example #19
0
func TestParseNoMatch(t *testing.T) {
	p, err := NewGraphiteParser("", []string{"servers.*.cpu .host.measurement.cpu.measurement"}, nil)
	if err != nil {
		t.Fatalf("unexpected error creating parser, got %v", err)
	}

	exp, err := telegraf.NewMetric("servers.localhost.memory.VmallocChunk",
		map[string]string{},
		map[string]interface{}{"value": float64(11)},
		time.Unix(1435077219, 0))
	assert.NoError(t, err)

	m, err := p.ParseLine("servers.localhost.memory.VmallocChunk 11 1435077219")
	assert.NoError(t, err)

	assert.Equal(t, exp.String(), m.String())
}
Example #20
0
func TestSerializeBucketNameNoHost(t *testing.T) {
	now := time.Now()
	tags := map[string]string{
		"cpu":        "cpu0",
		"datacenter": "us-west-2",
	}
	fields := map[string]interface{}{
		"usage_idle": float64(91.5),
	}
	m, err := telegraf.NewMetric("cpu", tags, fields, now)
	assert.NoError(t, err)

	mS := SerializeBucketName(m.Name(), m.Tags(), "", "")

	expS := "cpu0.us-west-2.cpu.FIELDNAME"
	assert.Equal(t, expS, mS)
}
Example #21
0
func TestSerializeMetricFloat(t *testing.T) {
	now := time.Now()
	tags := map[string]string{
		"cpu": "cpu0",
	}
	fields := map[string]interface{}{
		"usage_idle": float64(91.5),
	}
	m, err := telegraf.NewMetric("cpu", tags, fields, now)
	assert.NoError(t, err)

	s := JsonSerializer{}
	mS, err := s.Serialize(m)
	assert.NoError(t, err)
	expS := []string{fmt.Sprintf("{\"fields\":{\"usage_idle\":91.5},\"name\":\"cpu\",\"tags\":{\"cpu\":\"cpu0\"},\"timestamp\":%d}", now.Unix())}
	assert.Equal(t, expS, mS)
}
Example #22
0
// TestMetric Returns a simple test point:
//     measurement -> "test1" or name
//     tags -> "tag1":"value1"
//     value -> value
//     time -> time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
func TestMetric(value interface{}, name ...string) telegraf.Metric {
	if value == nil {
		panic("Cannot use a nil value")
	}
	measurement := "test1"
	if len(name) > 0 {
		measurement = name[0]
	}
	tags := map[string]string{"tag1": "value1"}
	pt, _ := telegraf.NewMetric(
		measurement,
		tags,
		map[string]interface{}{"value": value},
		time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
	)
	return pt
}
Example #23
0
func TestSerializeBucketNameNoHost(t *testing.T) {
	now := time.Now()
	tags := map[string]string{
		"cpu":        "cpu0",
		"datacenter": "us-west-2",
	}
	fields := map[string]interface{}{
		"usage_idle": float64(91.5),
	}
	m, err := telegraf.NewMetric("cpu", tags, fields, now)
	assert.NoError(t, err)

	s := GraphiteSerializer{}
	mS := s.SerializeBucketName(m, "usage_idle")

	expS := fmt.Sprintf("cpu0.us-west-2.cpu.usage_idle")
	assert.Equal(t, expS, mS)
}
Example #24
0
// Add applies the given metric to the aggregator.
// Before applying to the plugin, it will run any defined filters on the metric.
// Apply returns true if the original metric should be dropped.
func (r *RunningAggregator) Add(in telegraf.Metric) bool {
	if r.Config.Filter.IsActive() {
		// check if the aggregator should apply this metric
		name := in.Name()
		fields := in.Fields()
		tags := in.Tags()
		t := in.Time()
		if ok := r.Config.Filter.Apply(name, fields, tags); !ok {
			// aggregator should not apply this metric
			return false
		}

		in, _ = telegraf.NewMetric(name, tags, fields, t)
	}

	r.metrics <- in
	return r.Config.DropOriginal
}
Example #25
0
func TestSerializeMetricString(t *testing.T) {
	now := time.Now()
	tags := map[string]string{
		"cpu": "cpu0",
	}
	fields := map[string]interface{}{
		"usage_idle": "foobar",
	}
	m, err := telegraf.NewMetric("cpu", tags, fields, now)
	assert.NoError(t, err)

	s := InfluxSerializer{}
	mS, err := s.Serialize(m)
	assert.NoError(t, err)

	expS := []string{fmt.Sprintf("cpu,cpu=cpu0 usage_idle=\"foobar\" %d", now.UnixNano())}
	assert.Equal(t, expS, mS)
}
func (s MembershipEvent) NewMetric() telegraf.Metric {
	event := "membership"
	t := map[string]string{
		"event":  event,
		"user":   s.Sender.User,
		"admin":  fmt.Sprintf("%v", s.Sender.Admin),
		"action": s.Action,
	}
	f := map[string]interface{}{
		"newMember":       s.Member.User,
		"newMemberStatus": s.Member.Admin,
	}
	m, err := telegraf.NewMetric(meas, t, f, time.Now())
	if err != nil {
		log.Fatalf("Failed to create %v event", event)
	}
	return m
}
Example #27
0
func TestFilterMatchMultipleMeasurementSeparator(t *testing.T) {
	p, err := NewGraphiteParser("_",
		[]string{"servers.localhost .host.measurement.measurement*"},
		nil,
	)
	assert.NoError(t, err)

	exp, err := telegraf.NewMetric("cpu_cpu_load_10",
		map[string]string{"host": "localhost"},
		map[string]interface{}{"value": float64(11)},
		time.Unix(1435077219, 0))
	assert.NoError(t, err)

	m, err := p.ParseLine("servers.localhost.cpu.cpu_load.10 11 1435077219")
	assert.NoError(t, err)

	assert.Equal(t, exp.String(), m.String())
}
func (s WatchEvent) NewMetric() telegraf.Metric {
	event := "delete"
	t := map[string]string{
		"event":      event,
		"repository": s.Repository.Repository,
		"private":    fmt.Sprintf("%v", s.Repository.Private),
		"user":       s.Sender.User,
		"admin":      fmt.Sprintf("%v", s.Sender.Admin),
	}
	f := map[string]interface{}{
		"stars":  s.Repository.Stars,
		"forks":  s.Repository.Forks,
		"issues": s.Repository.Issues,
	}
	m, err := telegraf.NewMetric(meas, t, f, time.Now())
	if err != nil {
		log.Fatalf("Failed to create %v event", event)
	}
	return m
}
Example #29
0
func TestParseDefaultTemplateTagsOverridGlobal(t *testing.T) {
	p, err := NewGraphiteParser("", []string{"servers.localhost .host.measurement* zone=1c,region=us-east"}, map[string]string{
		"region": "shot not be set",
		"host":   "should not set",
	})
	if err != nil {
		t.Fatalf("unexpected error creating parser, got %v", err)
	}

	exp, err := telegraf.NewMetric("cpu_load",
		map[string]string{"host": "localhost", "region": "us-east", "zone": "1c"},
		map[string]interface{}{"value": float64(11)},
		time.Unix(1435077219, 0))
	assert.NoError(t, err)

	m, err := p.ParseLine("servers.localhost.cpu_load 11 1435077219")
	assert.NoError(t, err)

	assert.Equal(t, exp.String(), m.String())
}
Example #30
0
// Parse returns a slice of Metrics from a text representation of a
// metric (in line-protocol format)
// with each metric separated by newlines. If any metrics fail to parse,
// a non-nil error will be returned in addition to the metrics that parsed
// successfully.
func (p *InfluxParser) Parse(buf []byte) ([]telegraf.Metric, error) {
	// parse even if the buffer begins with a newline
	buf = bytes.TrimPrefix(buf, []byte("\n"))
	points, err := models.ParsePoints(buf)
	metrics := make([]telegraf.Metric, len(points))
	for i, point := range points {
		tags := point.Tags()
		for k, v := range p.DefaultTags {
			// Only set tags not in parsed metric
			if _, ok := tags[k]; !ok {
				tags[k] = v
			}
		}
		// Ignore error here because it's impossible that a model.Point
		// wouldn't parse into client.Point properly
		metrics[i], _ = telegraf.NewMetric(point.Name(), tags,
			point.Fields(), point.Time())
	}
	return metrics, err
}