forked from BarkingMouseStudio/heka-zeromq
/
input.go
102 lines (83 loc) · 2.13 KB
/
input.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
97
98
99
100
101
102
package heka_websockets
import (
"fmt"
zmq "github.com/alecthomas/gozmq"
"github.com/mozilla-services/heka/pipeline"
)
type ZeroMQInputConfig struct {
Address string `toml:"address"`
Decoder string `toml:"decoder"`
}
type ZeroMQInput struct {
conf *ZeroMQInputConfig
context *zmq.Context
socket *zmq.Socket
}
func (zi *ZeroMQInput) ConfigStruct() interface{} {
return &ZeroMQInputConfig{":4000", ""}
}
func (zi *ZeroMQInput) Init(config interface{}) error {
zi.conf = config.(*ZeroMQInputConfig)
var err error
if zi.context, err = zmq.NewContext(); err != nil {
return fmt.Errorf("creating context – %s", err.Error())
}
if zi.socket, err = zi.context.NewSocket(zmq.PULL); err != nil {
return fmt.Errorf("creating context – %s", err.Error())
}
if err = zi.socket.Bind(zi.conf.Address); err != nil {
return fmt.Errorf("creating context – %s", err.Error())
}
return nil
}
func (zi *ZeroMQInput) Run(ir pipeline.InputRunner, h pipeline.PluginHelper) error {
// Get the InputRunner's chan to receive empty PipelinePacks
packs := ir.InChan()
var decoding chan<- *pipeline.PipelinePack
if zi.conf.Decoder != "" {
// Fetch specified decoder
decoder, ok := h.DecoderSet().ByName(zi.conf.Decoder)
if !ok {
err := fmt.Errorf("Could not find decoder", zi.conf.Decoder)
return err
}
// Get the decoder's receiving chan
decoding = decoder.InChan()
}
var pack *pipeline.PipelinePack
var count int
var b []byte
var err error
// Read data from websocket broadcast chan
for {
b, err = zi.socket.Recv(0)
if err != nil {
ir.LogError(err)
continue
}
// Grab an empty PipelinePack from the InputRunner
pack = <-packs
// Trim the excess empty bytes
count = len(b)
pack.MsgBytes = pack.MsgBytes[:count]
// Copy ws bytes into pack's bytes
copy(pack.MsgBytes, b)
if decoding != nil {
// Send pack onto decoder
decoding <- pack
} else {
// Send pack into Heka pipeline
ir.Inject(pack)
}
}
return nil
}
func (zi *ZeroMQInput) Stop() {
zi.socket.Close()
zi.context.Close()
}
func init() {
pipeline.RegisterPlugin("ZeroMQInput", func() interface{} {
return new(ZeroMQInput)
})
}