forked from nerdalert/nflow-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen_stats_file.go
92 lines (70 loc) · 1.99 KB
/
gen_stats_file.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
package main
import (
"encoding/json"
"fmt"
"os"
)
type ConfigFlowState struct {
Count int
Bytes int
}
func InitFlowState(enabledFlows []EnabledConfigFlow) []ConfigFlowState {
var configFlowStates []ConfigFlowState
for i := 0; i < len(enabledFlows); i++ {
configFlowState := new(ConfigFlowState)
configFlowState.Count = 0
configFlowState.Bytes = 0
configFlowStates = append(configFlowStates, *configFlowState)
}
return configFlowStates
}
type OutStatsTotal struct {
Count int `json:"count"`
Bytes int `json:"bytes"`
SrcAddr string `json:"src_addr"`
SrcPort uint16 `json:"src_port"`
DstAddr string `json:"dst_addr"`
DstPort uint16 `json:"dst_port"`
Proto int `json:"proto"`
}
type OutStats struct {
Total []OutStatsTotal `json:"total"`
}
func GenStatsFile(filename string, configFlowStates []ConfigFlowState, enabledFlows []EnabledConfigFlow, flowConfigs []ConfigFlow) error {
statsFile, err := os.Create(filename)
if err != nil {
return fmt.Errorf("failed to create stats file %s: %v", filename, err)
}
defer statsFile.Close()
var outStatsTotal []OutStatsTotal
for i := 0; i < len(configFlowStates); i++ {
flowState := configFlowStates[i]
flowConfig := flowConfigs[enabledFlows[i].ConfigIndex]
outStatsTotal = append(outStatsTotal, OutStatsTotal{
Count: flowState.Count,
Bytes: flowState.Bytes,
SrcAddr: flowConfig.SrcAddr,
SrcPort: flowConfig.SrcPort,
DstAddr: flowConfig.DstAddr,
DstPort: flowConfig.DstPort,
Proto: flowConfig.Proto,
})
}
outStats := OutStats{
Total: outStatsTotal,
}
result, err := json.Marshal(outStats)
if err != nil {
return fmt.Errorf("failed to marshal stats: %v", err)
}
_, err = statsFile.Write(result)
if err != nil {
return fmt.Errorf("failed to write stats to file %s: %v", filename, err)
}
err = statsFile.Sync()
if err != nil {
return fmt.Errorf("failed to sync stats file %s: %v", filename, err)
}
fmt.Println("Successfully generated stats file: " + filename)
return nil
}