-
Notifications
You must be signed in to change notification settings - Fork 0
/
countbeat.go
71 lines (60 loc) · 1.27 KB
/
countbeat.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
package beater
import (
"fmt"
"time"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/jmlrt/countbeat/config"
)
// Countbeat configuration.
type Countbeat struct {
done chan struct{}
config config.Config
client beat.Client
}
// New creates an instance of countbeat.
func New(b *beat.Beat, cfg *common.Config) (beat.Beater, error) {
c := config.DefaultConfig
if err := cfg.Unpack(&c); err != nil {
return nil, fmt.Errorf("Error reading config file: %v", err)
}
bt := &Countbeat{
done: make(chan struct{}),
config: c,
}
return bt, nil
}
// Run starts countbeat.
func (bt *Countbeat) Run(b *beat.Beat) error {
logp.Info("countbeat is running! Hit CTRL-C to stop it.")
var err error
bt.client, err = b.Publisher.Connect()
if err != nil {
return err
}
ticker := time.NewTicker(bt.config.Period)
counter := 1
for {
select {
case <-bt.done:
return nil
case <-ticker.C:
}
event := beat.Event{
Timestamp: time.Now(),
Fields: common.MapStr{
"type": b.Info.Name,
"counter": counter,
},
}
bt.client.Publish(event)
logp.Info("Event sent")
counter++
}
}
// Stop stops countbeat.
func (bt *Countbeat) Stop() {
bt.client.Close()
close(bt.done)
}