1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
|
// +build go1.5,cgo
/*
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 (
"time"
"collectd.org/api"
"collectd.org/plugin"
)
type ExamplePlugin struct{}
func (*ExamplePlugin) Read() 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(context.Background(), vl); err != nil {
return 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
*/
package plugin // import "collectd.org/plugin"
// #cgo CPPFLAGS: -DHAVE_CONFIG_H
// #cgo LDFLAGS: -ldl
// #include <stdlib.h>
// #include <dlfcn.h>
// #include "plugin.h"
//
// int dispatch_values_wrapper (value_list_t const *vl);
// int register_read_wrapper (char const *group, char const *name,
// plugin_read_cb callback,
// cdtime_t interval,
// user_data_t *ud);
//
// data_source_t *ds_dsrc(data_set_t const *ds, size_t i);
//
// void value_list_add_counter (value_list_t *, counter_t);
// void value_list_add_derive (value_list_t *, derive_t);
// void value_list_add_gauge (value_list_t *, gauge_t);
// counter_t value_list_get_counter (value_list_t *, size_t);
// derive_t value_list_get_derive (value_list_t *, size_t);
// gauge_t value_list_get_gauge (value_list_t *, size_t);
//
// int wrap_read_callback(user_data_t *);
//
// int register_write_wrapper (char const *, plugin_write_cb, user_data_t *);
// int wrap_write_callback(data_set_t *, value_list_t *, user_data_t *);
//
// int register_shutdown_wrapper (char *, plugin_shutdown_cb);
// int wrap_shutdown_callback(void);
import "C"
import (
"context"
"fmt"
"unsafe"
"collectd.org/api"
"collectd.org/cdtime"
)
var (
ctx = context.Background()
)
// Reader defines the interface for read callbacks, i.e. Go functions that are
// called periodically from the collectd daemon.
type Reader interface {
Read() error
}
func strcpy(dst []C.char, src string) {
byteStr := []byte(src)
cStr := make([]C.char, len(byteStr)+1)
for i, b := range byteStr {
cStr[i] = C.char(b)
}
cStr[len(cStr)-1] = C.char(0)
copy(dst, cStr)
}
func newValueListT(vl *api.ValueList) (*C.value_list_t, error) {
ret := &C.value_list_t{}
strcpy(ret.host[:], vl.Host)
strcpy(ret.plugin[:], vl.Plugin)
strcpy(ret.plugin_instance[:], vl.PluginInstance)
strcpy(ret._type[:], vl.Type)
strcpy(ret.type_instance[:], vl.TypeInstance)
ret.interval = C.cdtime_t(cdtime.NewDuration(vl.Interval))
ret.time = C.cdtime_t(cdtime.New(vl.Time))
for _, v := range vl.Values {
switch v := v.(type) {
case api.Counter:
if _, err := C.value_list_add_counter(ret, C.counter_t(v)); err != nil {
return nil, fmt.Errorf("value_list_add_counter: %v", err)
}
case api.Derive:
if _, err := C.value_list_add_derive(ret, C.derive_t(v)); err != nil {
return nil, fmt.Errorf("value_list_add_derive: %v", err)
}
case api.Gauge:
if _, err := C.value_list_add_gauge(ret, C.gauge_t(v)); err != nil {
return nil, fmt.Errorf("value_list_add_gauge: %v", err)
}
default:
return nil, fmt.Errorf("not yet supported: %T", v)
}
}
return ret, nil
}
// writer implements the api.Write interface.
type writer struct{}
// NewWriter returns an object implementing the api.Writer interface for the
// collectd daemon.
func NewWriter() api.Writer {
return writer{}
}
// Write implements the api.Writer interface for the collectd daemon.
func (writer) Write(_ context.Context, vl *api.ValueList) error {
return Write(vl)
}
// Write converts a ValueList and calls the plugin_dispatch_values() function
// of the collectd daemon.
func Write(vl *api.ValueList) error {
vlt, err := newValueListT(vl)
if err != nil {
return err
}
defer C.free(unsafe.Pointer(vlt.values))
status, err := C.dispatch_values_wrapper(vlt)
if err != nil {
return err
} else if status != 0 {
return fmt.Errorf("dispatch_values failed with status %d", status)
}
return nil
}
// readFuncs holds references to all read callbacks, so the garbage collector
// doesn't get any funny ideas.
var readFuncs = make(map[string]Reader)
// RegisterRead registers a new read function with the daemon which is called
// periodically.
func RegisterRead(name string, r Reader) error {
cGroup := C.CString("golang")
defer C.free(unsafe.Pointer(cGroup))
cName := C.CString(name)
ud := C.user_data_t{
data: unsafe.Pointer(cName),
free_func: nil,
}
status, err := C.register_read_wrapper(cGroup, cName,
C.plugin_read_cb(C.wrap_read_callback),
C.cdtime_t(0),
&ud)
if err != nil {
return err
} else if status != 0 {
return fmt.Errorf("register_read_wrapper failed with status %d", status)
}
readFuncs[name] = r
return nil
}
//export wrap_read_callback
func wrap_read_callback(ud *C.user_data_t) C.int {
name := C.GoString((*C.char)(ud.data))
r, ok := readFuncs[name]
if !ok {
return -1
}
if err := r.Read(); err != nil {
Errorf("%s plugin: Read() failed: %v", name, err)
return -1
}
return 0
}
// writeFuncs holds references to all write callbacks, so the garbage collector
// doesn't get any funny ideas.
var writeFuncs = make(map[string]api.Writer)
// 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 RegisterWrite(name string, w api.Writer) error {
cName := C.CString(name)
ud := C.user_data_t{
data: unsafe.Pointer(cName),
free_func: nil,
}
status, err := C.register_write_wrapper(cName, C.plugin_write_cb(C.wrap_write_callback), &ud)
if err != nil {
return err
} else if status != 0 {
return fmt.Errorf("register_write_wrapper failed with status %d", status)
}
writeFuncs[name] = w
return nil
}
//export wrap_write_callback
func wrap_write_callback(ds *C.data_set_t, cvl *C.value_list_t, ud *C.user_data_t) C.int {
name := C.GoString((*C.char)(ud.data))
w, ok := writeFuncs[name]
if !ok {
return -1
}
vl := &api.ValueList{
Identifier: api.Identifier{
Host: C.GoString(&cvl.host[0]),
Plugin: C.GoString(&cvl.plugin[0]),
PluginInstance: C.GoString(&cvl.plugin_instance[0]),
Type: C.GoString(&cvl._type[0]),
TypeInstance: C.GoString(&cvl.type_instance[0]),
},
Time: cdtime.Time(cvl.time).Time(),
Interval: cdtime.Time(cvl.interval).Duration(),
}
// TODO: Remove 'size_t' cast on 'ds_num' upon 5.7 release.
for i := C.size_t(0); i < C.size_t(ds.ds_num); i++ {
dsrc := C.ds_dsrc(ds, i)
switch dsrc._type {
case C.DS_TYPE_COUNTER:
v := C.value_list_get_counter(cvl, i)
vl.Values = append(vl.Values, api.Counter(v))
case C.DS_TYPE_DERIVE:
v := C.value_list_get_derive(cvl, i)
vl.Values = append(vl.Values, api.Derive(v))
case C.DS_TYPE_GAUGE:
v := C.value_list_get_gauge(cvl, i)
vl.Values = append(vl.Values, api.Gauge(v))
default:
Errorf("%s plugin: data source type %d is not supported", name, dsrc._type)
return -1
}
vl.DSNames = append(vl.DSNames, C.GoString(&dsrc.name[0]))
}
if err := w.Write(ctx, vl); err != nil {
Errorf("%s plugin: Write() failed: %v", name, err)
return -1
}
return 0
}
// First declare some types, interfaces, general functions
// Shutters are objects that when called will shut down the plugin gracefully
type Shutter interface {
Shutdown() error
}
// shutdownFuncs holds references to all shutdown callbacks
var shutdownFuncs = make(map[string]Shutter)
//export wrap_shutdown_callback
func wrap_shutdown_callback() C.int {
if len(shutdownFuncs) <= 0 {
return 0
}
for n, s := range shutdownFuncs {
if err := s.Shutdown(); err != nil {
Errorf("%s plugin: Shutdown() failed: %v", n, s)
return -1
}
}
return 0
}
// RegisterShutdown registers a shutdown function with the daemon which is called
// when the plugin is required to shutdown gracefully.
func RegisterShutdown(name string, s Shutter) error {
// Only register a callback the first time one is implemented, subsequent
// callbacks get added to a list and called at the same time
if len(shutdownFuncs) <= 0 {
cName := C.CString(name)
cCallback := C.plugin_shutdown_cb(C.wrap_shutdown_callback)
status, err := C.register_shutdown_wrapper(cName, cCallback)
if err != nil {
Errorf("register_shutdown_wrapper failed with status: %v", status)
return err
}
}
shutdownFuncs[name] = s
return nil
}
//export module_register
func module_register() {
}
|