/
logserver_statistics.go
182 lines (150 loc) · 4.45 KB
/
logserver_statistics.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
package server
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"sort"
"time"
"github.com/vaitekunas/journal/logrpc"
context "golang.org/x/net/context"
)
// GatherStatistics saves log-related statistics
func (l *LogServer) GatherStatistics(service, instance, key, ip string, logEntry *logrpc.LogEntry) {
l.Lock()
defer l.Unlock()
now := time.Now()
if _, ok := l.stats[key]; !ok {
l.stats[key] = &Statistic{
Service: service,
Instance: instance,
LogsParsed: [24]int64{},
LogsParsedBytes: [24]int64{},
}
}
jsoned, err := json.Marshal(logEntry.GetEntry())
if err != nil {
jsoned = []byte{}
}
stats := l.stats[key]
stats.LogsParsed[now.Hour()]++
stats.LogsParsedBytes[now.Hour()] += int64(len(jsoned))
stats.LastIP = ip
stats.LastActive = now
}
// AggregateStatistics contains aggregated logging statistics
type AggregateStatistics struct {
service string
instances int
volume int64
logs int64
share float64
}
// AggregateServiceStatistics aggregates statistics
func (l *LogServer) AggregateServiceStatistics() (totalVolume int64, services []*AggregateStatistics, hourly [24][2]int64) {
l.Lock()
defer l.Unlock()
// Aggregate data
var totalLogVolume int64
serviceAggroMap := map[string]*AggregateStatistics{}
serviceNames := []string{}
hourly = [24][2]int64{}
for _, stats := range l.stats {
service := stats.Service
_, _, plogs, pbytes := parsedSums(stats.LogsParsed, stats.LogsParsedBytes)
serviceAggro, ok := serviceAggroMap[service]
if !ok {
serviceNames = append(serviceNames, service)
serviceAggro = &AggregateStatistics{service: service}
serviceAggroMap[service] = serviceAggro
}
for i := 0; i <= 23; i++ {
hourly[i][0] += stats.LogsParsed[i]
hourly[i][1] += stats.LogsParsedBytes[i]
}
serviceAggro.instances++
serviceAggro.logs += plogs
serviceAggro.volume += pbytes
totalLogVolume += pbytes
}
// Calculate shares
shares := make([]float64, len(serviceNames))
for i, name := range serviceNames {
stsum := serviceAggroMap[name]
stsum.share = float64(stsum.volume) / float64(totalLogVolume)
shares[i] = stsum.share
}
// Sort by share
shareSort := &floatSorter{floats: shares}
sort.Sort(shareSort)
aggro := make([]*AggregateStatistics, len(shares))
for i := range shareSort.GetIndexes() {
aggro[i] = serviceAggroMap[serviceNames[i]]
}
return totalLogVolume, aggro, hourly
}
// periodicallyDumpStats periodically dumps statistics to file
func (l *LogServer) periodicallyDumpStats(ctx context.Context, period time.Duration) {
Loop:
for {
select {
case <-time.After(period):
l.dumpStatsToFile()
case <-ctx.Done():
break Loop
}
}
}
// dumpStatsToFile dumps all the statistics into file
func (l *LogServer) dumpStatsToFile() error {
l.Lock()
defer l.Unlock()
// Make sure file exists
if err := fileExists(l.statsPath); err != nil {
return fmt.Errorf("dumpStatsToFile: could not create statistics database: %s", err.Error())
}
// JSON statistics
jsoned, errJSON := json.Marshal(l.stats)
if errJSON != nil {
return fmt.Errorf("dumpStatsToFile: could not marshal statistics to json: %s", errJSON.Error())
}
// Open file for reading
f, err := os.OpenFile(l.statsPath, os.O_WRONLY, 600)
if err != nil {
return fmt.Errorf("dumpStatsToFile: could not open statistics file for writing: %s", err.Error())
}
// Write stats
if _, err := f.Write(jsoned); err != nil {
defer f.Close()
return fmt.Errorf("dumpStatsToFile: could not dump stats: %s", err.Error())
}
return f.Close()
}
// loadStatisticsFromDisk loads server statistics from file
func (l *LogServer) loadStatisticsFromDisk() error {
l.Lock()
defer l.Unlock()
// Make sure file exists
if err := fileExists(l.statsPath); err != nil {
return fmt.Errorf("loadStatisticsFromDisk: could not create statistics database: %s", err.Error())
}
// Open file for reading
f, err := os.OpenFile(l.statsPath, os.O_RDONLY, 600)
if err != nil {
return fmt.Errorf("loadStatisticsFromDisk: could not open statistics file for reading: %s", err.Error())
}
defer f.Close()
// Read json-encoded statistics
jsoned, err := ioutil.ReadFile(l.statsPath)
if err != nil {
return fmt.Errorf("loadStatisticsFromDisk: could not read file: %s", err.Error())
}
if len(jsoned) == 0 {
return nil
}
// Unmarshal json-encoded statistics
if err := json.Unmarshal(jsoned, &l.stats); err != nil {
return fmt.Errorf("loadStatisticsFromDisk: could not unmarshal statistics: %s", err.Error())
}
return nil
}