icingabeat/vendor/github.com/elastic/beats/metricbeat/beater/example_test.go

116 lines
2.8 KiB
Go

// +build !integration
package beater_test
import (
"fmt"
"sync"
"time"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
metricbeat "github.com/elastic/beats/metricbeat/beater"
"github.com/elastic/beats/metricbeat/mb"
)
// ExampleModuleWrapper demonstrates how to create a single ModuleWrapper
// from configuration, start the module, and consume events generated by the
// module.
func ExampleModuleWrapper() {
// Build a configuration object.
config, err := common.NewConfigFrom(map[string]interface{}{
"module": moduleName,
"metricsets": []string{metricSetName},
})
if err != nil {
fmt.Println("Error:", err)
return
}
// Create a new ModuleWrapper based on the configuration.
module, err := metricbeat.NewModuleWrapper(config, mb.Registry)
if err != nil {
fmt.Println("Error:", err)
return
}
// Run the module until done is closed.
done := make(chan struct{})
output := module.Start(done)
// Process events from the output channel until it is closed.
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for event := range output {
// Make rtt a constant so that the output is constant.
event["metricset"].(common.MapStr)["rtt"] = 111
fmt.Println(event.StringToPrint())
}
}()
// Simulate running for a while.
time.Sleep(50 * time.Millisecond)
// When finished with the module, close the done channel. When the Module
// stops it will automatically close its output channel so that the output
// for loop stops.
close(done)
wg.Wait()
// Output:
// {
// "@timestamp": "2016-05-10T23:27:58.485Z",
// "_event_metadata": {
// "Fields": null,
// "FieldsUnderRoot": false,
// "Tags": null
// },
// "fake": {
// "status": {
// "metric": 1
// }
// },
// "metricset": {
// "module": "fake",
// "name": "status",
// "rtt": 111
// },
// "type": "metricsets"
// }
}
// ExampleModuleRunner demonstrates how to use ModuleRunner to start and stop
// a module.
func ExampleModuleRunner() {
// A *beat.Beat is injected into a Beater when it runs and contains the
// Publisher used to publish events. This Beat pointer is created here only
// for demonstration purposes.
var b *beat.Beat
config, err := common.NewConfigFrom(map[string]interface{}{
"module": moduleName,
"metricsets": []string{metricSetName},
})
if err != nil {
return
}
// Create a new ModuleWrapper based on the configuration.
module, err := metricbeat.NewModuleWrapper(config, mb.Registry)
if err != nil {
return
}
// Create the ModuleRunner facade.
runner := metricbeat.NewModuleRunner(b.Publisher.Connect, module)
// Start the module and have it publish to a new publisher.Client.
runner.Start()
// Stop the module. This blocks until all MetricSets in the Module have
// stopped and the publisher.Client is closed.
runner.Stop()
}