/
main.go
414 lines (372 loc) · 10.5 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
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package main
// FIXME write some stats every now and again - packets per second etc
// FIXME detect overflows?
// FIXME write dt in the file?
// FIXME don't dump stats file if empty?
// FIXME have a max entries parameter
// - dump the stats if get beyond that many entries?
// - or just refuse to add any more?
// - or add to 0.0.0.0 entry?
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"log/syslog"
"net"
"os"
"os/signal"
"path"
"runtime"
"runtime/pprof"
"sync"
"syscall"
"time"
)
const (
// Time format to output in CSV files
// http://stackoverflow.com/questions/804118/best-timestamp-format-for-csv-excel
CsvTimeFormat = "2006-01-02 15:04:05"
// Format to use when making filenames
FileTimeFormat = "2006-01-02-150405"
// Number of packets to keep in the AddPackets Queue
AddPacketsQueueSize = 8
)
// Globals
var (
// Flags
IPv4SourceGroup = flag.Int("ip4-src-group", 0, "NFLog Group to read IPv4 packets and account the source address")
IPv4DestGroup = flag.Int("ip4-dst-group", 0, "NFLog Group to read IPv4 packets and account the destination address")
IPv4PrefixLength = flag.Int("ip4-prefix-length", 32, "Size of the IPv4 prefix to account to, default is /32")
IPv6SourceGroup = flag.Int("ip6-src-group", 0, "NFLog Group to read IPv6 packets and account the source address")
IPv6DestGroup = flag.Int("ip6-dst-group", 0, "NFLog Group to read IPv6 packets and account the destination address")
IPv6PrefixLength = flag.Int("ip6-prefix-length", 64, "Size of the IPv6 prefix to account to, default is /64")
Cpus = flag.Int("cpus", 0, "Number of CPUs to use - default 0 is all of them")
UseSyslog = flag.Bool("syslog", false, "Use Syslog for logging")
Debug = flag.Bool("debug", false, "Print every single packet that arrives")
Verbose = flag.Bool("verbose", false, "Print more logging stuff")
Interval = flag.Duration("interval", time.Minute*5, "Interval to log stats")
LogDirectory = flag.String("log-directory", "/var/log/accounting", "Directory to write accounting files to.")
CpuProfile = flag.String("cpuprofile", "", "Write cpu profile to file")
MemProfile = flag.String("memprofile", "", "write memory profile to this file")
Priority = flag.Int("priority", -19, "Set priority level")
// Globals
BaseName = path.Base(os.Args[0])
Version = "0.1"
DefaultMapSize = 1024
)
// Information about one direction for a single IP or range
type HalfIpStats struct {
Bytes int64
Packets int64
}
// Collect info about a single IP (or range)
type IpStats struct {
Source HalfIpStats
Dest HalfIpStats
}
// Accounting for IP addresses
//
// The key is the net.IP which is a []byte converted to a string so it
// can be used as a hash key
type IpMap map[string]*IpStats
// Dump the IpMap to the output as a CSV
func (Ips IpMap) Dump(w io.Writer, when time.Time) error {
wb := bufio.NewWriter(w)
whenString := when.Format(CsvTimeFormat)
_, err := fmt.Fprintf(wb, "Time,IP,SourceBytes,SourcePackets,DestBytes,DestPackets\n")
if err != nil {
return err
}
for key, stat := range Ips {
ip := net.IP(key)
_, err := fmt.Fprintf(wb, "%s,%s,%d,%d,%d,%d\n", whenString, ip, stat.Source.Bytes, stat.Source.Packets, stat.Dest.Bytes, stat.Dest.Packets)
if err != nil {
return err
}
}
return wb.Flush()
}
// Returns the time rounded down to *Interval
func FlooredTime(t time.Time) time.Time {
ns := t.UnixNano()
ns /= int64(*Interval)
ns *= int64(*Interval)
return time.Unix(0, ns)
}
// AddPacket holds the info about one packet
//
// Addr is a net.IP which is a []byte converted into a string This
// won't be a nice UTF-8 string but will preserve the bytes and can be
// used as a hash key
type AddPacket struct {
Direction IpDirection
Addr string
Length int
}
// Accounting
type Accounting struct {
StartPeriod time.Time
EndPeriod time.Time
Ips IpMap
engineWg sync.WaitGroup
dumpStatsWg sync.WaitGroup
engineStop chan struct{}
dumpStatsStop chan struct{}
processAddPackets chan []AddPacket
returnAddPackets chan []AddPacket
flip chan bool
oldIps chan IpMap
}
func NewAccounting() *Accounting {
a := &Accounting{
Ips: make(IpMap, DefaultMapSize),
engineStop: make(chan struct{}),
dumpStatsStop: make(chan struct{}),
processAddPackets: make(chan []AddPacket, AddPacketsQueueSize),
returnAddPackets: make(chan []AddPacket, AddPacketsQueueSize),
flip: make(chan bool, 1),
oldIps: make(chan IpMap, 1),
}
// Make some buffers
for i := 0; i < AddPacketsQueueSize; i++ {
a.returnAddPackets <- make([]AddPacket, 0, 128)
}
return a
}
// Make a new map returning the old one
func (a *Accounting) newMaps() IpMap {
a.flip <- true
return <-a.oldIps
}
// Account a single packet in a thread safe way
func (a *Accounting) Packet(Direction IpDirection, Addr string, Length int) {
stat := a.Ips[Addr]
if stat == nil {
stat = &IpStats{}
a.Ips[Addr] = stat
}
if Direction == IpSource {
stat.Source.Bytes += int64(Length)
stat.Source.Packets += 1
} else {
stat.Dest.Bytes += int64(Length)
stat.Dest.Packets += 1
}
if *Debug {
log.Printf("IP message %s Addr %s Size %d", Direction, net.IP(Addr), Length)
}
}
// Accounting engine to account packets
//
// It has sole control over the Ips map which means that no locking is
// required
func (a *Accounting) Engine() {
defer a.engineWg.Done()
for {
select {
// Process a bunch of packets
case ps := <-a.processAddPackets:
for _, p := range ps {
a.Packet(p.Direction, p.Addr, p.Length)
}
a.returnAddPackets <- ps
// Flip the map
case <-a.flip:
a.oldIps <- a.Ips
a.Ips = make(IpMap, DefaultMapSize)
// Stop the engine
case <-a.engineStop:
if *Verbose {
log.Printf("Engine stop")
}
return
}
}
}
// Dump the current stats to a file
//
// We do this carefully writing to a .tmp file and renaming
func (a *Accounting) DumpFile() {
fileLeaf := a.StartPeriod.Format(FileTimeFormat) + "_" + a.EndPeriod.Format(FileTimeFormat)
filePath := path.Join(*LogDirectory, fileLeaf)
fileTmp := filePath + ".tmp"
fileCsv := filePath + ".csv"
_, err := os.Lstat(fileCsv)
if err == nil {
log.Printf("Output file %q already exists", fileCsv)
return
}
log.Printf("Dumping stats to %s", fileCsv)
fd, err := os.Create(fileTmp)
if err != nil {
log.Printf("Failed to open stats file: %s", err)
return
}
Ips := a.newMaps()
err = Ips.Dump(fd, a.StartPeriod)
err2 := fd.Close()
if err != nil {
log.Printf("Failed to write to stats file: %s", err)
return
}
if err2 != nil {
log.Printf("Failed to close stats file: %s", err)
return
}
err = os.Rename(fileTmp, fileCsv)
if err != nil {
log.Printf("Failed to rename %q to %q: %s", fileTmp, fileCsv, err)
return
}
log.Printf("Stats file %q written", fileCsv)
}
// Schedules file dumping dump for the end of the interval
func (a *Accounting) DumpStats() {
defer a.dumpStatsWg.Done()
a.StartPeriod = time.Now()
a.EndPeriod = FlooredTime(a.StartPeriod).Add(*Interval)
for {
if *Verbose {
log.Printf("Next stats dump at %s", a.EndPeriod)
}
select {
case <-time.After(a.EndPeriod.Sub(time.Now())):
case <-a.dumpStatsStop:
if *Verbose {
log.Printf("DumpStats stop")
}
a.EndPeriod = time.Now()
a.DumpFile()
return
}
a.DumpFile()
a.StartPeriod = a.EndPeriod
a.EndPeriod = a.StartPeriod.Add(*Interval)
}
}
// Starts the accounting
func (a *Accounting) Start() {
log.Printf("Starting accounting")
a.engineWg.Add(1)
go a.Engine()
a.dumpStatsWg.Add(1)
go a.DumpStats()
log.Printf("Started accounting")
}
// Stops the accounting saving the stats so far
func (a *Accounting) Stop() {
log.Printf("Stopping accounting")
close(a.dumpStatsStop)
if *Verbose {
log.Printf("Wait for dump stats stop")
}
a.dumpStatsWg.Wait()
close(a.engineStop)
if *Verbose {
log.Printf("Wait for engine stop")
}
a.engineWg.Wait()
log.Printf("Stopped accounting")
}
// usage prints the syntax
func usage() {
fmt.Fprintf(os.Stderr,
"%s ver %s\n\n"+
"Usage: %s [flags]\n\n"+
"flags:\n\n",
BaseName, Version, BaseName)
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, "\n")
}
// main
func main() {
flag.Usage = usage
flag.Parse()
if *Debug {
*Verbose = true
}
const Day = 24 * time.Hour
// Check interval
if *Interval < time.Second {
log.Fatalf("Interval must be >= 1 Second")
}
if *Interval >= Day {
if (*Interval % Day) != 0 {
log.Fatalf("Interval %s isn't a whole number of days", *Interval)
}
} else {
if (Day % *Interval) != 0 {
log.Fatalf("Interval %s doesn't divide a day exactly", *Interval)
}
}
// Make output directory
err := os.MkdirAll(*LogDirectory, 0750)
if err != nil {
log.Fatalf("Failed to make log directory %q: %s", *LogDirectory, err)
}
if *Cpus <= 0 {
runtime.GOMAXPROCS(runtime.NumCPU())
} else {
runtime.GOMAXPROCS(*Cpus)
}
if *UseSyslog {
w, err := syslog.New(syslog.LOG_INFO, BaseName)
if err != nil {
log.Fatalf("Failed to start syslog: %s", err)
}
log.SetFlags(0)
log.SetOutput(w)
}
// Setup profiling if desired
if *CpuProfile != "" {
log.Printf("Starting cpu profiler on %q", *CpuProfile)
f, err := os.Create(*CpuProfile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
// Set priority
if err := syscall.Setpriority(syscall.PRIO_PGRP, 0, *Priority); err != nil {
log.Printf("Failed to set priority %d: %v", *Priority, err)
}
a := NewAccounting()
config := func(Group int, IpVersion byte, Direction IpDirection, MaskBits int) {
if Group > 0 {
log.Printf("Monitoring NFLog multicast group %d for IPv%d %s mask /%d", Group, IpVersion, Direction, MaskBits)
NewNfLog(Group, IpVersion, Direction, MaskBits, a)
}
}
config(*IPv4DestGroup, 4, IpDest, *IPv4PrefixLength)
config(*IPv4SourceGroup, 4, IpSource, *IPv4PrefixLength)
config(*IPv6DestGroup, 6, IpDest, *IPv6PrefixLength)
config(*IPv6SourceGroup, 6, IpSource, *IPv6PrefixLength)
if nflogs.Count() == 0 {
log.Fatal("Not monitoring any groups - exiting")
}
// Loop forever accounting stuff
a.Start()
// Exit neatly on interrupt
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT)
signal.Notify(ch, syscall.SIGTERM)
signal.Notify(ch, syscall.SIGQUIT)
s := <-ch
log.Printf("%s received - shutting down", s)
if *MemProfile != "" {
log.Printf("Writing memory profile %q\n", *MemProfile)
f, err := os.Create(*MemProfile)
if err != nil {
log.Fatal(err)
}
pprof.WriteHeapProfile(f)
f.Close()
return
}
a.Stop()
nflogs.Stop()
log.Printf("Exit")
}