forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
publish.go
356 lines (288 loc) · 9.1 KB
/
publish.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package publisher
import (
"errors"
"flag"
"os"
"sync/atomic"
"time"
"github.com/nranchev/go-libGeoIP"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/common/op"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/outputs"
"github.com/elastic/beats/libbeat/processors"
// load supported output plugins
_ "github.com/elastic/beats/libbeat/outputs/console"
_ "github.com/elastic/beats/libbeat/outputs/elasticsearch"
_ "github.com/elastic/beats/libbeat/outputs/fileout"
_ "github.com/elastic/beats/libbeat/outputs/kafka"
_ "github.com/elastic/beats/libbeat/outputs/logstash"
_ "github.com/elastic/beats/libbeat/outputs/redis"
// load support output codec
_ "github.com/elastic/beats/libbeat/outputs/codecs/format"
_ "github.com/elastic/beats/libbeat/outputs/codecs/json"
)
// command line flags
var publishDisabled *bool
var debug = logp.MakeDebug("publish")
type Context struct {
publishOptions
Signal op.Signaler
}
type pipeline interface {
publish(m message) bool
}
type publishOptions struct {
Guaranteed bool
Sync bool
}
type TransactionalEventPublisher interface {
PublishTransaction(transaction op.Signaler, events []common.MapStr)
}
type Publisher interface {
Connect() Client
}
type BeatPublisher struct {
shipperName string // Shipper name as set in the configuration file
hostname string // Host name as returned by the operation system
name string // The shipperName if configured, the hostname otherwise
version string
IPAddrs []string
disabled bool
Index string
Output []*outputWorker
TopologyOutput outputs.TopologyOutputer
geoLite *libgeo.GeoIP
Processors *processors.Processors
globalEventMetadata common.EventMetadata // Fields and tags to add to each event.
RefreshTopologyTimer <-chan time.Time
// On shutdown the publisher is finished first and the outputers next,
// so no publisher will attempt to send messages on closed channels.
// Note: beat data producers must be shutdown before the publisher plugin
wsPublisher workerSignal
wsOutput workerSignal
pipelines struct {
sync pipeline
async pipeline
}
// keep count of clients connected to publisher. A publisher is allowed to
// Stop only if all clients have been disconnected
numClients uint32
}
type ShipperConfig struct {
common.EventMetadata `config:",inline"` // Fields and tags to add to each event.
Name string `config:"name"`
RefreshTopologyFreq time.Duration `config:"refresh_topology_freq"`
TopologyExpire int `config:"topology_expire"`
Geoip common.Geoip `config:"geoip"`
// internal publisher queue sizes
QueueSize *int `config:"queue_size"`
BulkQueueSize *int `config:"bulk_queue_size"`
MaxProcs *int `config:"max_procs"`
}
type Topology struct {
Name string `json:"name"`
IP string `json:"ip"`
}
const (
DefaultQueueSize = 1000
DefaultBulkQueueSize = 0
)
func init() {
publishDisabled = flag.Bool("N", false, "Disable actual publishing for testing")
}
func (publisher *BeatPublisher) IsPublisherIP(ip string) bool {
for _, myip := range publisher.IPAddrs {
if myip == ip {
return true
}
}
return false
}
func (publisher *BeatPublisher) GetServerName(ip string) string {
// in case the IP is localhost, return current shipper name
islocal, err := common.IsLoopback(ip)
if err != nil {
logp.Err("Parsing IP %s fails with: %s", ip, err)
return ""
}
if islocal {
return publisher.name
}
// find the shipper with the desired IP
if publisher.TopologyOutput != nil {
logp.Warn("Topology settings are deprecated.")
return publisher.TopologyOutput.GetNameByIP(ip)
}
return ""
}
func (publisher *BeatPublisher) GeoLite() *libgeo.GeoIP {
return publisher.geoLite
}
func (publisher *BeatPublisher) Connect() Client {
atomic.AddUint32(&publisher.numClients, 1)
return newClient(publisher)
}
func (publisher *BeatPublisher) UpdateTopologyPeriodically() {
for range publisher.RefreshTopologyTimer {
_ = publisher.PublishTopology() // ignore errors
}
}
func (publisher *BeatPublisher) PublishTopology(params ...string) error {
localAddrs := params
if len(params) == 0 {
addrs, err := common.LocalIPAddrsAsStrings(false)
if err != nil {
logp.Err("Getting local IP addresses fails with: %s", err)
return err
}
localAddrs = addrs
}
if publisher.TopologyOutput != nil {
debug("Add topology entry for %s: %s", publisher.name, localAddrs)
err := publisher.TopologyOutput.PublishIPs(publisher.name, localAddrs)
if err != nil {
return err
}
}
return nil
}
// Create new PublisherType
func New(
beatName string,
beatVersion string,
configs map[string]*common.Config,
shipper ShipperConfig,
processors *processors.Processors,
) (*BeatPublisher, error) {
publisher := BeatPublisher{}
err := publisher.init(beatName, beatVersion, configs, shipper, processors)
if err != nil {
return nil, err
}
return &publisher, nil
}
func (publisher *BeatPublisher) init(
beatName string,
beatVersion string,
configs map[string]*common.Config,
shipper ShipperConfig,
processors *processors.Processors,
) error {
var err error
publisher.Processors = processors
publisher.disabled = *publishDisabled
if publisher.disabled {
logp.Info("Dry run mode. All output types except the file based one are disabled.")
}
shipper.InitShipperConfig()
publisher.geoLite = common.LoadGeoIPData(shipper.Geoip)
publisher.wsPublisher.Init()
publisher.wsOutput.Init()
if len(configs) > 1 {
logp.Warn("Support for loading more than one output is deprecated and will not be supported in version 6.0.")
}
if !publisher.disabled {
plugins, err := outputs.InitOutputs(beatName, configs, shipper.TopologyExpire)
if err != nil {
return err
}
var outputers []*outputWorker
var topoOutput outputs.TopologyOutputer
for _, plugin := range plugins {
output := plugin.Output
config := plugin.Config
debug("Create output worker")
outputers = append(outputers,
newOutputWorker(
config,
output,
&publisher.wsOutput,
*shipper.QueueSize,
*shipper.BulkQueueSize))
if ok, _ := config.Bool("save_topology", 0); !ok {
continue
}
topo, ok := output.(outputs.TopologyOutputer)
if !ok {
logp.Err("Output type %s does not support topology logging",
plugin.Name)
return errors.New("Topology output not supported")
}
if topoOutput != nil {
logp.Err("Multiple outputs defined to store topology. " +
"Please add save_topology = true option only for one output.")
return errors.New("Multiple outputs defined to store topology")
}
topoOutput = topo
logp.Info("Using %s to store the topology", plugin.Name)
}
publisher.Output = outputers
publisher.TopologyOutput = topoOutput
}
if !publisher.disabled {
if len(publisher.Output) == 0 {
logp.Info("No outputs are defined. Please define one under the output section.")
return errors.New("No outputs are defined. Please define one under the output section.")
}
if publisher.TopologyOutput == nil {
logp.Debug("publish", "No output is defined to store the topology. The server fields might not be filled.")
}
}
publisher.shipperName = shipper.Name
publisher.hostname, err = os.Hostname()
publisher.version = beatVersion
if err != nil {
return err
}
if len(publisher.shipperName) > 0 {
publisher.name = publisher.shipperName
} else {
publisher.name = publisher.hostname
}
logp.Info("Publisher name: %s", publisher.name)
publisher.globalEventMetadata = shipper.EventMetadata
//Store the publisher's IP addresses
publisher.IPAddrs, err = common.LocalIPAddrsAsStrings(false)
if err != nil {
logp.Err("Failed to get local IP addresses: %s", err)
return err
}
if !publisher.disabled && publisher.TopologyOutput != nil {
RefreshTopologyFreq := 10 * time.Second
if shipper.RefreshTopologyFreq != 0 {
RefreshTopologyFreq = shipper.RefreshTopologyFreq
}
publisher.RefreshTopologyTimer = time.Tick(RefreshTopologyFreq)
logp.Info("Topology map refreshed every %s", RefreshTopologyFreq)
// register shipper and its public IP addresses
err = publisher.PublishTopology()
if err != nil {
logp.Err("Failed to publish topology: %s", err)
return err
}
// update topology periodically
go publisher.UpdateTopologyPeriodically()
}
publisher.pipelines.async = newAsyncPipeline(publisher, *shipper.QueueSize, *shipper.BulkQueueSize, &publisher.wsPublisher)
publisher.pipelines.sync = newSyncPipeline(publisher, *shipper.QueueSize, *shipper.BulkQueueSize)
return nil
}
func (publisher *BeatPublisher) Stop() {
if atomic.LoadUint32(&publisher.numClients) > 0 {
panic("All clients must disconnect before shutting down publisher pipeline")
}
publisher.wsPublisher.stop()
publisher.wsOutput.stop()
}
func (config *ShipperConfig) InitShipperConfig() {
// TODO: replace by ucfg
if config.QueueSize == nil || *config.QueueSize <= 0 {
queueSize := DefaultQueueSize
config.QueueSize = &queueSize
}
if config.BulkQueueSize == nil || *config.BulkQueueSize < 0 {
bulkQueueSize := DefaultBulkQueueSize
config.BulkQueueSize = &bulkQueueSize
}
}