forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
291 lines (248 loc) · 7.82 KB
/
main.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
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
"runtime"
"runtime/pprof"
"strings"
"syscall"
"time"
"packetbeat/common"
"packetbeat/common/droppriv"
"packetbeat/config"
"packetbeat/filters"
"packetbeat/filters/nop"
"packetbeat/inputs"
"packetbeat/inputs/gobeacon"
"packetbeat/inputs/sniffer"
"packetbeat/inputs/udpjson"
"packetbeat/logp"
"packetbeat/outputs"
"packetbeat/procs"
"packetbeat/protos"
"packetbeat/protos/http"
"packetbeat/protos/mysql"
"packetbeat/protos/pgsql"
"packetbeat/protos/redis"
"packetbeat/protos/tcp"
"packetbeat/protos/thrift"
"github.com/BurntSushi/toml"
)
const Version = "0.5.0"
var EnabledProtocolPlugins map[protos.Protocol]protos.ProtocolPlugin = map[protos.Protocol]protos.ProtocolPlugin{
protos.HttpProtocol: new(http.Http),
protos.MysqlProtocol: new(mysql.Mysql),
protos.PgsqlProtocol: new(pgsql.Pgsql),
protos.RedisProtocol: new(redis.Redis),
protos.ThriftProtocol: new(thrift.Thrift),
}
var EnabledInputPlugins map[inputs.Input]inputs.InputPlugin = map[inputs.Input]inputs.InputPlugin{
inputs.SnifferInput: new(sniffer.SnifferSetup),
inputs.UdpjsonInput: new(udpjson.Udpjson),
inputs.GoBeaconInput: new(gobeacon.GoBeacon),
}
var EnabledFilterPlugins map[filters.Filter]filters.FilterPlugin = map[filters.Filter]filters.FilterPlugin{
filters.NopFilter: new(nop.Nop),
}
func writeHeapProfile(filename string) {
f, err := os.Create(filename)
if err != nil {
logp.Err("Failed creating file %s: %s", filename, err)
return
}
pprof.WriteHeapProfile(f)
f.Close()
logp.Info("Created memory profile file %s.", filename)
}
func debugMemStats() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
logp.Debug("mem", "Memory stats: In use: %d Total (even if freed): %d System: %d",
m.Alloc, m.TotalAlloc, m.Sys)
}
func main() {
// Use our own FlagSet, because some libraries pollute the global one
var cmdLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
configfile := cmdLine.String("c", "packetbeat.conf", "Configuration file")
file := cmdLine.String("I", "", "file")
loop := cmdLine.Int("l", 1, "Loop file. 0 - loop forever")
debugSelectorsStr := cmdLine.String("d", "", "Enable certain debug selectors")
oneAtAtime := cmdLine.Bool("O", false, "Read packets one at a time (press Enter)")
toStderr := cmdLine.Bool("e", false, "Output to stdout instead of syslog")
topSpeed := cmdLine.Bool("t", false, "Read packets as fast as possible, without sleeping")
publishDisabled := cmdLine.Bool("N", false, "Disable actual publishing for testing")
verbose := cmdLine.Bool("v", false, "Log at INFO level")
printVersion := cmdLine.Bool("version", false, "Print version and exit")
memprofile := cmdLine.String("memprofile", "", "Write memory profile to this file")
cpuprofile := cmdLine.String("cpuprofile", "", "Write cpu profile to file")
dumpfile := cmdLine.String("dump", "", "Write all captured packets to this libpcap file.")
cmdLine.Parse(os.Args[1:])
if *printVersion {
fmt.Printf("Packetbeat version %s (%s)\n", Version, runtime.GOARCH)
return
}
logLevel := logp.LOG_ERR
if *verbose {
logLevel = logp.LOG_INFO
}
debugSelectors := []string{}
if len(*debugSelectorsStr) > 0 {
debugSelectors = strings.Split(*debugSelectorsStr, ",")
logLevel = logp.LOG_DEBUG
}
var err error
if config.ConfigMeta, err = toml.DecodeFile(*configfile, &config.ConfigSingleton); err != nil {
fmt.Printf("TOML config parsing failed on %s: %s. Exiting.\n", *configfile, err)
return
}
if len(debugSelectors) == 0 {
debugSelectors = config.ConfigSingleton.Logging.Selectors
}
logp.LogInit(logp.Priority(logLevel), "", !*toStderr, true, debugSelectors)
if !logp.IsDebug("stdlog") {
// disable standard logging by default
log.SetOutput(ioutil.Discard)
}
// CLI flags over-riding config
if *topSpeed {
config.ConfigSingleton.Interfaces.TopSpeed = true
}
if len(*file) > 0 {
config.ConfigSingleton.Interfaces.File = *file
}
config.ConfigSingleton.Interfaces.Loop = *loop
config.ConfigSingleton.Interfaces.OneAtATime = *oneAtAtime
if len(*dumpfile) > 0 {
config.ConfigSingleton.Interfaces.Dumpfile = *dumpfile
}
logp.Debug("main", "Initializing output plugins")
if err = outputs.Publisher.Init(*publishDisabled); err != nil {
logp.Critical(err.Error())
return
}
if err = procs.ProcWatcher.Init(&config.ConfigSingleton.Procs); err != nil {
logp.Critical(err.Error())
return
}
outputs.LoadGeoIPData()
logp.Debug("main", "Initializing protocol plugins")
for proto, plugin := range EnabledProtocolPlugins {
err = plugin.Init(false, outputs.Publisher.Queue)
if err != nil {
logp.Critical("Initializing plugin %s failed: %v", proto, err)
return
}
protos.Protos.Register(proto, plugin)
}
if err = tcp.TcpInit(config.ConfigSingleton.Protocols); err != nil {
logp.Critical(err.Error())
return
}
over := make(chan bool)
if !config.ConfigMeta.IsDefined("input", "inputs") {
config.ConfigSingleton.Input.Inputs = []string{"sniffer"}
}
if len(config.ConfigSingleton.Input.Inputs) == 0 {
logp.Critical("At least one input needs to be enabled")
return
}
logp.Debug("main", "Initializing filters plugins")
for filter, plugin := range EnabledFilterPlugins {
filters.Filters.Register(filter, plugin)
}
filters_plugins, err :=
LoadConfiguredFilters(config.ConfigSingleton.Filter)
if err != nil {
logp.Critical("Error loading filters plugins: %v", err)
}
logp.Debug("main", "Filters plugins order: %v", filters_plugins)
var afterInputsQueue chan common.MapStr
if len(filters_plugins) > 0 {
runner := NewFilterRunner(outputs.Publisher.Queue, filters_plugins)
go func() {
err := runner.Run()
if err != nil {
logp.Critical("Filters runner failed: %v", err)
// shutting doen
inputs.Inputs.StopAll()
}
}()
afterInputsQueue = runner.FiltersQueue
} else {
// short-circuit the runner
afterInputsQueue = outputs.Publisher.Queue
}
logp.Debug("main", "Initializing input plugins")
for input, plugin := range EnabledInputPlugins {
configured_inputs := config.ConfigSingleton.Input.Inputs
if input.IsInList(configured_inputs) {
logp.Debug("main", "Input plugin %s is enabled", input)
err = plugin.Init(false, afterInputsQueue)
if err != nil {
logp.Critical("Ininitializing plugin %s failed: %v", input, err)
return
}
inputs.Inputs.Register(input, plugin)
}
}
// This needs to be after the sniffer Init but before the sniffer Run.
if err = droppriv.DropPrivileges(); err != nil {
logp.Critical(err.Error())
return
}
// Up to here was the initialization, now about running
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
for input, plugin := range inputs.Inputs.Registered() {
// run the plugin in background
go func(input inputs.Input, plugin inputs.InputPlugin) {
err := plugin.Run()
if err != nil {
logp.Critical("Plugin %s main loop failed: %v", input, err)
return
}
over <- true
}(input, plugin)
}
// On ^C or SIGTERM, gracefully stop inputs
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigc
logp.Debug("signal", "Received sigterm/sigint, stopping")
inputs.Inputs.StopAll()
}()
if !*toStderr {
logp.Info("Startup successful, sending output only to syslog from now on")
logp.SetToStderr(false)
}
logp.Debug("main", "Waiting for inputs to finish")
// Wait for one of the inputs goroutines to finish
for _ = range over {
if !inputs.Inputs.AreAllAlive() {
break
}
}
logp.Debug("main", "Cleanup")
// stop and close all other input plugin servers
inputs.Inputs.StopAll()
inputs.Inputs.CloseAll()
if *memprofile != "" {
// wait for all TCP streams to expire
time.Sleep(tcp.TCP_STREAM_EXPIRY * 1.2)
tcp.PrintTcpMap()
runtime.GC()
writeHeapProfile(*memprofile)
debugMemStats()
}
}