-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstats.go
More file actions
101 lines (95 loc) · 2.27 KB
/
stats.go
File metadata and controls
101 lines (95 loc) · 2.27 KB
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
package main
import (
"encoding/json"
"os"
"time"
"github.com/dustin/go-humanize"
)
func loadSavedStats() {
f, err := os.Open(statsFilename)
if err != nil {
if !os.IsNotExist(err) {
doLog("loadSavedStats: %v", err)
}
return
}
defer f.Close()
var s SavedStats
if err := json.NewDecoder(f).Decode(&s); err != nil {
doLog("loadSavedStats: %v", err)
return
}
ephemeralLock.Lock()
if !s.StartTime.IsZero() {
startTime = s.StartTime
}
if s.PeakUsers > 0 {
ephemeralPeak = s.PeakUsers
}
if s.SessionsTotal > 0 {
ephemeralSessionsTotal = s.SessionsTotal
}
bytesInTotal = s.BytesInTotal
bytesOutTotal = s.BytesOutTotal
ephemeralLock.Unlock()
}
func saveStats(data PageData) {
tmp := statsFilename + ".tmp"
f, err := os.Create(tmp)
if err != nil {
doLog("saveStats: %v", err)
return
}
enc := json.NewEncoder(f)
s := SavedStats{
StartTime: startTime,
SessionsTotal: data.TotalSessions,
PeakUsers: data.PeakUsers,
BytesInTotal: data.BytesInTotal,
BytesOutTotal: data.BytesOutTotal,
}
if err := enc.Encode(&s); err != nil {
doLog("saveStats: %v", err)
f.Close()
return
}
f.Close()
if err := os.Rename(tmp, statsFilename); err != nil {
doLog("saveStats rename: %v", err)
}
}
func gatherStats() PageData {
ephemeralLock.Lock()
current := len(ephemeralIDMap)
peak := ephemeralPeak
total := ephemeralSessionsTotal
sessions := []SessionInfo{}
for _, s := range ephemeralIDMap {
sess := SessionInfo{
ID: s.id,
DestPort: s.destPort,
Duration: time.Since(s.startTime).Round(time.Second).String(),
BytesIn: s.bytesIn,
BytesOut: s.bytesOut,
BytesInStr: humanize.Bytes(uint64(s.bytesIn)),
BytesOutStr: humanize.Bytes(uint64(s.bytesOut)),
}
sessions = append(sessions, sess)
}
inTotal := bytesInTotal
outTotal := bytesOutTotal
ephemeralLock.Unlock()
return PageData{
CurrentUsers: current,
PeakUsers: peak,
TotalSessions: total,
Uptime: time.Since(startTime).Round(time.Second).String(),
BatchInterval: batchingMicroseconds,
Compression: compressionLevel,
Sessions: sessions,
BytesInTotal: inTotal,
BytesOutTotal: outTotal,
BytesInTotalStr: humanize.Bytes(uint64(inTotal)),
BytesOutTotalStr: humanize.Bytes(uint64(outTotal)),
}
}