-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconn.go
114 lines (92 loc) · 2.38 KB
/
conn.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
package conntrack
import (
"net"
"sync/atomic"
"time"
)
// Conn is a tracked [net.Conn], created by a [Listener] or [Dialer].
type Conn struct {
net.Conn
tracker *Tracker
config connConfig
clientServer string
createdAt time.Time
rd, wr uint64
}
func newConn(conn net.Conn, t *Tracker, config connConfig, clientServer string) *Conn {
return &Conn{
Conn: conn,
tracker: t,
config: config,
clientServer: clientServer,
createdAt: time.Now().UTC(),
}
}
// Read decorates the net.Conn method for tracking purposes.
func (c *Conn) Read(b []byte) (n int, err error) {
defer func() {
atomic.AddUint64(&c.rd, uint64(n))
c.config.OnRead(n, err)
}()
return c.Conn.Read(b)
}
// Write decorates the net.Conn method for tracking purposes.
func (c *Conn) Write(b []byte) (n int, err error) {
defer func() {
atomic.AddUint64(&c.wr, uint64(n))
c.config.OnWrite(n, err)
}()
return c.Conn.Write(b)
}
// Close decorates the net.Conn method for tracking purposes.
func (c *Conn) Close() (err error) {
defer func() {
c.tracker.closeConn(c, err)
c.config.OnClose(c, err)
}()
return c.Conn.Close()
}
type connConfig struct {
Category string
OnRead func(int, error)
OnWrite func(int, error)
OnClose func(net.Conn, error)
}
//
//
//
// ConnInfo is point-in-time metadata about a tracked connection.
type ConnInfo struct {
// Category of the Dialer or Listener which created this connection.
Category string
// ClientServer is either "client" (when the connection is from a dialer) or
// "server" (when the connection is from a listener).
ClientServer string
// LocalAddr is the local address of the connection.
LocalAddr string
// RemoteAddr is the remote address of the connection.
RemoteAddr string
// EstablishedFor is how long the connection has existed.
EstablishedFor time.Duration
// ReadBytes is how many bytes have been read from the connection.
ReadBytes uint64
// WriteBytes is how many bytes have been written to the connection.
WriteBytes uint64
}
//
//
//
// SafeLocalAddr returns c.LocalAddr().String(), or "<nil>" if c is nil.
func SafeLocalAddr(c net.Conn) string {
if c == nil {
return "<nil>"
}
return c.LocalAddr().String()
}
// SafeRemoteAddr returns c.RemoteAddr().String(), or "<nil>" if c is nil.
func SafeRemoteAddr(c net.Conn) string {
if c == nil {
return "<nil>"
}
return c.RemoteAddr().String()
}