/
introspection.go
78 lines (66 loc) · 1.42 KB
/
introspection.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
package interception
import (
"flag"
"fmt"
"os"
"sync"
"time"
"github.com/safing/portbase/log"
)
var (
packetMetricsDestination string
metrics = &packetMetrics{
done: make(chan struct{}),
}
)
func init() {
flag.StringVar(&packetMetricsDestination, "write-packet-metrics", "", "write packet metrics to the specified file")
}
type (
performanceRecord struct {
start int64
duration time.Duration
verdict string
}
packetMetrics struct {
done chan struct{}
l sync.Mutex
records []*performanceRecord
}
)
func (pm *packetMetrics) record(tp *tracedPacket, verdict string) {
go func(start int64, duration time.Duration) {
pm.l.Lock()
defer pm.l.Unlock()
pm.records = append(pm.records, &performanceRecord{
start: start,
duration: duration,
verdict: verdict,
})
}(tp.start.UnixNano(), time.Since(tp.start))
}
func (pm *packetMetrics) writeMetrics() {
if packetMetricsDestination == "" {
return
}
f, err := os.Create(packetMetricsDestination)
if err != nil {
log.Errorf("Failed to create packet metrics file: %s", err)
return
}
defer f.Close()
for {
select {
case <-pm.done:
return
case <-time.After(time.Second * 5):
}
pm.l.Lock()
records := pm.records
pm.records = nil
pm.l.Unlock()
for _, r := range records {
fmt.Fprintf(f, "%d;%s;%s;%.2f\n", r.start, r.verdict, r.duration, float64(r.duration)/float64(time.Microsecond))
}
}
}