forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
96 lines (83 loc) · 2.47 KB
/
server.go
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
package server
import (
"github.com/pkg/errors"
"github.com/elastic/beats/libbeat/common/cfgwarn"
"github.com/elastic/beats/libbeat/logp"
serverhelper "github.com/elastic/beats/metricbeat/helper/server"
"github.com/elastic/beats/metricbeat/helper/server/tcp"
"github.com/elastic/beats/metricbeat/helper/server/udp"
"github.com/elastic/beats/metricbeat/mb"
)
// init registers the MetricSet with the central registry.
// The New method will be called after the setup of the module and before starting to fetch data
func init() {
if err := mb.Registry.AddMetricSet("graphite", "server", New); err != nil {
panic(err)
}
}
// MetricSet type defines all fields of the MetricSet
// As a minimum it must inherit the mb.BaseMetricSet fields, but can be extended with
// additional entries. These variables can be used to persist data or configuration between
// multiple fetch calls.
type MetricSet struct {
mb.BaseMetricSet
server serverhelper.Server
processor *metricProcessor
}
// New create a new instance of the MetricSet
// Part of new is also setting up the configuration by processing additional
// configuration entries if needed.
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
cfgwarn.Beta("The graphite server metricset is beta")
config := DefaultGraphiteCollectorConfig()
if err := base.Module().UnpackConfig(&config); err != nil {
return nil, err
}
var s serverhelper.Server
var err error
if config.Protocol == "tcp" {
s, err = tcp.NewTcpServer(base)
} else {
s, err = udp.NewUdpServer(base)
}
if err != nil {
return nil, err
}
processor := NewMetricProcessor(config.Templates, config.DefaultTemplate)
return &MetricSet{
BaseMetricSet: base,
server: s,
processor: processor,
}, nil
}
// Run method provides the Graphite server with a reporter with which events can be reported.
func (m *MetricSet) Run(reporter mb.PushReporter) {
// Start event watcher
if err := m.server.Start(); err != nil {
err = errors.Wrap(err, "failed to start graphite server")
logp.Err("%v", err)
reporter.Error(err)
return
}
for {
select {
case <-reporter.Done():
m.server.Stop()
return
case msg := <-m.server.GetEvents():
input := msg.GetEvent()
bytesRaw, ok := input[serverhelper.EventDataKey]
if ok {
bytes, ok := bytesRaw.([]byte)
if ok && len(bytes) != 0 {
event, err := m.processor.Process(string(bytes))
if err != nil {
reporter.Error(err)
} else {
reporter.Event(event)
}
}
}
}
}
}