/
kafka.go
226 lines (188 loc) · 5.15 KB
/
kafka.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
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
package kafka
import (
"encoding/json"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/Shopify/sarama"
"github.com/gliderlabs/logspout/router"
)
func init() {
router.AdapterFactories.Register(NewKafkaAdapter, "kafka")
}
type KafkaAdapter struct {
route *router.Route
brokers []string
topic string
producer sarama.AsyncProducer
}
func NewKafkaAdapter(route *router.Route) (router.LogAdapter, error) {
brokers := readBrokers(route.Address)
if len(brokers) == 0 {
return nil, errorf("The Kafka broker host:port is missing. Did you specify it as a route address?")
}
topic := readTopic(route.Address, route.Options)
if topic == "" {
return nil, errorf("The Kafka topic is missing. Did you specify it as a route option?")
}
var err error
if os.Getenv("DEBUG") != "" {
log.Printf("Starting Kafka producer for address: %s, topic: %s.\n", brokers, topic)
}
var retries int
retries, err = strconv.Atoi(os.Getenv("KAFKA_CONNECT_RETRIES"))
if err != nil {
retries = 3
}
var producer sarama.AsyncProducer
for i := 0; i < retries; i++ {
config := newConfig()
if err = loadOptions(config, route.Options); err != nil {
return nil, errorf("Route options is invalid. %v", err)
}
producer, err = sarama.NewAsyncProducer(brokers, config)
if err != nil {
if os.Getenv("DEBUG") != "" {
log.Println("Couldn't create Kafka producer. Retrying...", err)
}
if i == retries-1 {
return nil, errorf("Couldn't create Kafka producer. %v", err)
}
} else {
time.Sleep(1 * time.Second)
break
}
}
return &KafkaAdapter{
route: route,
brokers: brokers,
topic: topic,
producer: producer,
}, nil
}
func filterMessage(str string) bool {
if messageFilters := os.Getenv("KAFKA_IGNORE_MESSAGE_CONTAINS"); messageFilters != "" {
for _, messageFilter := range strings.Split(messageFilters, ",") {
if messageFilter != "" && strings.Contains(str, messageFilter) {
return true
}
}
}
return false
}
func (a *KafkaAdapter) Stream(logstream chan *router.Message) {
defer a.producer.Close()
for rm := range logstream {
if filterMessage(rm.Data) {
continue
}
message, err := a.formatMessage(rm)
if err != nil {
log.Println("kafka:", err)
a.route.Close()
break
}
if message != nil {
a.producer.Input() <- message
}
}
}
func newConfig() *sarama.Config {
var flushMs int = 1000
config := sarama.NewConfig()
config.ClientID = "logspout"
config.Producer.Return.Errors = false
config.Producer.Return.Successes = false
config.Producer.Flush.Frequency = time.Duration(flushMs) * time.Millisecond
config.Producer.RequiredAcks = sarama.WaitForLocal
config.Version = sarama.V3_0_0_0
if opt := os.Getenv("KAFKA_COMPRESSION_CODEC"); opt != "" {
switch opt {
case "gzip":
config.Producer.Compression = sarama.CompressionGZIP
case "snappy":
config.Producer.Compression = sarama.CompressionSnappy
}
}
return config
}
func (a *KafkaAdapter) formatMessage(m *router.Message) (*sarama.ProducerMessage, error) {
dockerInfo := DockerInfo{
Name: m.Container.Name,
ID: m.Container.ID,
Image: m.Container.Config.Image,
Hostname: m.Container.Config.Hostname,
}
if os.Getenv("DOCKER_LABELS") != "" {
dockerInfo.Labels = make(map[string]string)
for label, value := range m.Container.Config.Labels {
dockerInfo.Labels[strings.Replace(label, ".", "_", -1)] = value
}
}
// tags := GetContainerTags(m.Container, a)
// fields := GetLogstashFields(m.Container, a)
var js []byte
var data map[string]interface{}
var err error
data = make(map[string]interface{})
data["message"] = m.Data
data["docker"] = dockerInfo
data["stream"] = m.Source
// Return the JSON encoding
if js, err = json.Marshal(data); err != nil {
// Log error message and continue parsing next line, if marshalling fails
log.Println("logstash: could not marshal JSON:", err)
return nil, nil
}
js = append(js, byte('\n'))
encoder := sarama.StringEncoder(js)
return &sarama.ProducerMessage{
Topic: a.topic,
Value: encoder,
}, nil
}
func readBrokers(address string) []string {
if strings.Contains(address, "/") {
slash := strings.Index(address, "/")
address = address[:slash]
}
return strings.Split(address, ",")
}
func readTopic(address string, options map[string]string) string {
var topic string
if !strings.Contains(address, "/") {
topic = options["topic"]
} else {
slash := strings.Index(address, "/")
topic = address[slash+1:]
}
return topic
}
func errorf(format string, a ...interface{}) (err error) {
err = fmt.Errorf(format, a...)
if os.Getenv("DEBUG") != "" {
fmt.Println(err.Error())
}
return
}
type DockerInfo struct {
Name string `json:"name"`
ID string `json:"id"`
Image string `json:"image"`
Hostname string `json:"hostname"`
Labels map[string]string `json:"labels"`
}
func loadOptions(config *sarama.Config, options map[string]string) error {
if os.Getenv("DEBUG") != "" {
log.Println("Load options")
}
var err error
if security, found := options["security.protocol"]; found && security == "SASL_PLAINTEXT" {
authen := NewSASLAuthentication(options)
err = authen.SetConfig(config)
}
return err
}