| 1 |
package statsd |
| 2 |
|
| 3 |
import ( |
| 4 |
"net" |
| 5 |
"time" |
| 6 |
) |
| 7 |
|
| 8 |
/* |
| 9 |
UDSTimeout holds the default timeout for UDS socket writes, as they can get |
| 10 |
blocking when the receiving buffer is full. |
| 11 |
*/ |
| 12 |
const defaultUDSTimeout = 1 * time.Millisecond |
| 13 |
|
| 14 |
// udsWriter is an internal class wrapping around management of UDS connection |
| 15 |
type udsWriter struct { |
| 16 |
// Address to send metrics to, needed to allow reconnection on error |
| 17 |
addr net.Addr |
| 18 |
// Established connection object, or nil if not connected yet |
| 19 |
conn net.Conn |
| 20 |
// write timeout |
| 21 |
writeTimeout time.Duration |
| 22 |
} |
| 23 |
|
| 24 |
// New returns a pointer to a new udsWriter given a socket file path as addr. |
| 25 |
func newUdsWriter(addr string) (*udsWriter, error) { |
| 26 |
udsAddr, err := net.ResolveUnixAddr("unixgram", addr) |
| 27 |
if err != nil { |
| 28 |
return nil, err |
| 29 |
} |
| 30 |
// Defer connection to first Write |
| 31 |
writer := &udsWriter{addr: udsAddr, conn: nil, writeTimeout: defaultUDSTimeout} |
| 32 |
return writer, nil |
| 33 |
} |
| 34 |
|
| 35 |
// SetWriteTimeout allows the user to set a custom write timeout |
| 36 |
func (w *udsWriter) SetWriteTimeout(d time.Duration) error { |
| 37 |
w.writeTimeout = d |
| 38 |
return nil |
| 39 |
} |
| 40 |
|
| 41 |
// Write data to the UDS connection with write timeout and minimal error handling: |
| 42 |
// create the connection if nil, and destroy it if the statsd server has disconnected |
| 43 |
func (w *udsWriter) Write(data []byte) (int, error) { |
| 44 |
// Try connecting (first packet or connection lost) |
| 45 |
if w.conn == nil { |
| 46 |
conn, err := net.Dial(w.addr.Network(), w.addr.String()) |
| 47 |
if err != nil { |
| 48 |
return 0, err |
| 49 |
} |
| 50 |
w.conn = conn |
| 51 |
} |
| 52 |
w.conn.SetWriteDeadline(time.Now().Add(w.writeTimeout)) |
| 53 |
n, e := w.conn.Write(data) |
| 54 |
if e != nil { |
| 55 |
// Statsd server disconnected, retry connecting at next packet |
| 56 |
w.conn = nil |
| 57 |
return 0, e |
| 58 |
} |
| 59 |
return n, e |
| 60 |
} |
| 61 |
|
| 62 |
func (w *udsWriter) Close() error { |
| 63 |
if w.conn != nil { |
| 64 |
return w.conn.Close() |
| 65 |
} |
| 66 |
return nil |
| 67 |
} |