Collectd is a Unix daemon that collects, transfers and stores performance
data of computers and network equipment. The acquired data is meant to help
system administrators maintain an overview over available resources to detect
existing or looming bottlenecks.

Collectd provides a long list of
plugins
available
out-of-box. However, if you need to collect additional metrics, one of the
easiest ways to do so is using the exec
plugin
.

In order to use the exec plugin, create an Collectd configuration file:

LoadPlugin exec

<Plugin exec>
  Exec "myuser:mygroup" "/path/to/another/binary" "arg0" "arg1"
</Plugin>

And a sample script “/path/to/another/binary” (extracted from the official
documentation):

HOSTNAME="${COLLECTD_HOSTNAME:-localhost}"
INTERVAL="${COLLECTD_INTERVAL:-60}"

while sleep "$INTERVAL"; do
  VALUE=do_magic()
  echo "PUTVAL \"$HOSTNAME/exec-magic/gauge-magic_level\" interval=$INTERVAL N:$VALUE"
done

The most important bits are contained in the outputted message :

PUTVAL "$HOSTNAME/exec-magic/gauge-magic_level" interval=$INTERVAL N:$VALUE

Where:

  1. exec-magic is the plugin name.
  2. magic_level is the metric name.
  3. gauge is the data source type, according to collectd
    types
    .
  4. N: is the abbreviation for “now” as defined in the exec
    plugin
    .

Sample plugin

Now, let’s create a simple Collectd plugin. In the example that follows I will
use Go
.

The main loop will run the metric collection in a scheduled fashion:

package main

import (
	"flag"
	"time"
)

func main() {
	var (
		interval = flag.Int("interval", 5, "time in seconds between collection")
	)

	ticker := time.NewTicker(time.Duration(*interval) * time.Second)
	for {
		select {
		case <-ticker.C:
			go collectMetric()
		}
	}
}

And the collectMetric code:

hostname, _ := os.Hostname()
value := someWork()

fmt.Printf("PUTVAL %s/my-plugin/gauge-my_metric interval=%d N:%s\n", hostname, interval, value)

Just compile it and use your favorite configuration management tool to upload
the plugin and configuration.

The purpose of this example was to demonstrate how to create a plugin. For
production-ready” plugins I recommend using the official *Go
*library.

Exec plugin is the simplest and fastest way to plug a custom metric collector
into Collectd.