-
Notifications
You must be signed in to change notification settings - Fork 11
/
tracking.go
41 lines (34 loc) · 1.06 KB
/
tracking.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
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package netutil
import (
"net"
"runtime"
)
// closeTrackingConn wraps a net.Conn and keeps track of if it was closed
// or if it was leaked (and closes it if it was leaked).
type closeTrackingConn struct {
net.Conn
}
// TrackClose wraps the conn and sets a finalizer on the returned value to
// close the conn and monitor that it was leaked.
func TrackClose(conn net.Conn) net.Conn {
tracked := &closeTrackingConn{Conn: conn}
runtime.SetFinalizer(tracked, (*closeTrackingConn).finalize)
return tracked
}
// Close clears the finalizer and closes the connection.
func (c *closeTrackingConn) Close() error {
runtime.SetFinalizer(c, nil)
mon.Event("connection_closed")
return c.Conn.Close()
}
// finalize monitors that a connection was leaked and closes the connection.
func (c *closeTrackingConn) finalize() {
mon.Event("connection_leaked")
_ = c.Conn.Close()
}
// NetConn returns the underlying conn, like *tls.Conn does.
func (c *closeTrackingConn) NetConn() net.Conn {
return c.Conn
}