plugin

package
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 4, 2024 License: ISC Imports: 13 Imported by: 2

README

collectd plugins in Go

About

This is experimental code to write collectd plugins in Go. That means the API is not yet stable. It requires Go 1.13 or later and a recent version of the collectd sources to build.

Build

To set up your build environment, set the CGO_CPPFLAGS environment variable so that cgo can find the required header files:

export COLLECTD_SRC="/path/to/collectd"
export CGO_CPPFLAGS="-I${COLLECTD_SRC}/src/daemon -I${COLLECTD_SRC}/src"

You can then compile your Go plugins with:

go build -buildmode=c-shared -o example.so

More information is available in the documentation of the collectd.org/plugin package.

godoc collectd.org/plugin

Future

Only log, read, write, and shutdown callbacks are currently supported. Based on these implementations it should be possible to implement the remaining callbacks, even with little prior Cgo experience. The init, flush, and missing callbacks are all likely low-hanging fruit. The notification callback is a bit trickier because it requires implementing notifications in the collectd.org/api package and the (un)marshaling of notification_t. The (complex) config callback is currently work in progress, see #30.

If you're willing to give any of this a shot, please ping @octo to avoid duplicate work.

Documentation

Overview

Package plugin exports the functions required to write collectd plugins in Go.

This package provides the abstraction necessary to write plugins for collectd in Go, compile them into a shared object and let the daemon load and use them.

Example plugin

To understand how this module is being used, please consider the following example:

package main

import (
        "context"
        "fmt"
        "time"

        "collectd.org/api"
        "collectd.org/plugin"
)

type examplePlugin struct{}

func (examplePlugin) Read(ctx context.Context) error {
        vl := &api.ValueList{
                Identifier: api.Identifier{
                        Host:   "example.com",
                        Plugin: "goplug",
                        Type:   "gauge",
                },
                Time:     time.Now(),
                Interval: 10 * time.Second,
                Values:   []api.Value{api.Gauge(42)},
                DSNames:  []string{"value"},
        }
        if err := plugin.Write(ctx, vl); err != nil {
                return fmt.Errorf("plugin.Write: %w", err)
        }

        return nil
}

func init() {
        plugin.RegisterRead("example", examplePlugin{})
}

func main() {} // ignored

The first step when writing a new plugin with this package, is to create a new "main" package. Even though it has to have a main() function to make cgo happy, the main() function is ignored. Instead, put your startup code into the init() function which essentially takes on the same role as the module_register() function in C based plugins.

Then, define a type which implements the Reader interface by implementing the "Read() error" function. In the example above, this type is called "examplePlugin". Create an instance of this type and pass it to RegisterRead() in the init() function.

Build flags

To compile your plugin, set up the CGO_CPPFLAGS environment variable and call "go build" with the following options:

export COLLECTD_SRC="/path/to/collectd"
export CGO_CPPFLAGS="-I${COLLECTD_SRC}/src/daemon -I${COLLECTD_SRC}/src"
go build -buildmode=c-shared -o example.so

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

func Debug(v ...interface{}) error

Debug logs a debugging message using plugin_log(). Arguments are handled in the manner of fmt.Print.

func Debugf

func Debugf(format string, v ...interface{}) error

Debugf logs a debugging message using plugin_log(). Arguments are handled in the manner of fmt.Printf.

func Error

func Error(v ...interface{}) error

Error logs an error using plugin_log(). Arguments are handled in the manner of fmt.Print.

func Errorf

func Errorf(format string, v ...interface{}) error

Errorf logs an error using plugin_log(). Arguments are handled in the manner of fmt.Printf.

func Info

func Info(v ...interface{}) error

Info logs a purely informal message using plugin_log(). Arguments are handled in the manner of fmt.Print.

func Infof

func Infof(format string, v ...interface{}) error

Infof logs a purely informal message using plugin_log(). Arguments are handled in the manner of fmt.Printf.

func Interval added in v0.4.0

func Interval() (time.Duration, error)

Interval returns the interval in which read callbacks are being called. May only be called from within a read callback.

func Name added in v0.4.0

func Name(ctx context.Context) (string, bool)

Name returns the name of the plugin / callback.

func Notice

func Notice(v ...interface{}) error

Notice logs a notice using plugin_log(). Arguments are handled in the manner of fmt.Print.

func Noticef

func Noticef(format string, v ...interface{}) error

Noticef logs a notice using plugin_log(). Arguments are handled in the manner of fmt.Printf.

func RegisterConfig added in v0.5.0

func RegisterConfig(name string, c Configurer) error

RegisterConfig registers a configuration-receiving function with the daemon.

c.Configure is called exactly once after the entire configuration has been read. If there are multiple configuration blocks for the plugin, they will be merged into a single block using "collectd.org/config".Block.Merge.

If no configuration is found for "name", c.Configure is still called with a zero-valued config.Block.

func RegisterLog added in v0.4.0

func RegisterLog(name string, l Logger) error

RegisterLog registers a logging function with the daemon which is called whenever a log message is generated.

func RegisterRead

func RegisterRead(name string, r Reader, opts ...ReadOption) error

RegisterRead registers a new read function with the daemon which is called periodically.

func RegisterShutdown added in v0.4.0

func RegisterShutdown(name string, s Shutter) error

RegisterShutdown registers a shutdown function with the daemon which is called when the plugin is required to shutdown gracefully.

func RegisterWrite

func RegisterWrite(name string, w api.Writer) error

RegisterWrite registers a new write function with the daemon which is called for every metric collected by collectd.

Please note that multiple threads may call this function concurrently. If you're accessing shared resources, such as a memory buffer, you have to implement appropriate locking around these accesses.

func Timeout added in v0.4.0

func Timeout() (time.Duration, error)

Timeout returns the duration after which this plugin's metrics are considered stale and are pruned from collectd's internal metrics cache.

func Warning

func Warning(v ...interface{}) error

Warning logs a warning using plugin_log(). Arguments are handled in the manner of fmt.Print.

func Warningf

func Warningf(format string, v ...interface{}) error

Warningf logs a warning using plugin_log(). Arguments are handled in the manner of fmt.Printf.

func Write

func Write(ctx context.Context, vl *api.ValueList) error

Write converts a ValueList and calls the plugin_dispatch_values() function of the collectd daemon.

The following fields are optional and will be filled in if empty / zero:

· vl.Identifier.Host

· vl.Identifier.Plugin

· vl.Time

· vl.Interval

Use api.WriterFunc to pass this function as an api.Writer.

Types

type Configurer added in v0.5.0

type Configurer interface {
	Configure(context.Context, config.Block) error
}

Configurer implements a Configure callback.

type LogWriter added in v0.5.0

type LogWriter Severity

LogWriter implements the io.Writer interface on top of collectd's logging facility.

Example
package main

import (
	"errors"
	"log"
	"net/http"

	"collectd.org/plugin"
)

func main() {
	l := log.New(plugin.LogWriter(plugin.SeverityError), "", log.Lshortfile)

	// Start an HTTP server that logs errors to collectd's logging facility.
	srv := &http.Server{
		ErrorLog: l,
	}
	if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
		l.Println("ListenAndServe:", err)
	}
}
Output:

func (LogWriter) Write added in v0.5.0

func (w LogWriter) Write(p []byte) (n int, err error)

Write converts p to a string and logs it with w's severity.

type Logger added in v0.4.0

type Logger interface {
	Log(context.Context, Severity, string)
}

Logger implements a logging callback.

type ReadOption added in v0.4.0

type ReadOption func(o *readOpt)

ReadOption is an option for the RegisterRead function.

func WithGroup added in v0.4.0

func WithGroup(g string) ReadOption

WithGroup sets the group name of the read callback. If unspecified, "golang" is used. Set to the empty string to clear the group name.

func WithInterval added in v0.4.0

func WithInterval(d time.Duration) ReadOption

WithInterval sets the interval in which the read callback is being called. If unspecified, or when set to zero, collectd's global default is used.

The vast majority of plugins SHOULD NOT set this option explicitly and respect the user's configuration by using the default instead.

type Reader

type Reader interface {
	Read(ctx context.Context) error
}

Reader defines the interface for read callbacks, i.e. Go functions that are called periodically from the collectd daemon. The context passed to the Read() function has a timeout based on collectd's "Timeout" global config option. It defaults to twice the plugin's read interval.

type Severity added in v0.4.0

type Severity int

Severity is the severity of log messages. These are well-known constants within collectd, so don't define your own. Use the constants provided by this package instead.

const (
	SeverityError   Severity = 3
	SeverityWarning Severity = 4
	SeverityNotice  Severity = 5
	SeverityInfo    Severity = 6
	SeverityDebug   Severity = 7
)

Predefined severities for collectd log functions.

type Shutter added in v0.4.0

type Shutter interface {
	Shutdown(context.Context) error
}

Shutter is called to shut down the plugin gracefully.

Directories

Path Synopsis
Package fake implements fake versions of the C functions imported from the collectd daemon for testing.
Package fake implements fake versions of the C functions imported from the collectd daemon for testing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL