-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
client.go
102 lines (84 loc) · 2.4 KB
/
client.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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package accesslog
import (
"net"
"sync/atomic"
"unsafe"
cilium "github.com/cilium/proxy/go/cilium/api"
"github.com/golang/protobuf/proto"
"github.com/sirupsen/logrus"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/proxylib/proxylib"
)
type Client struct {
connected uint32 // Accessed atomically without locking
path string
mutex lock.Mutex // Used to protect opening the connection
conn unsafe.Pointer // Read atomically without locking
}
func (cl *Client) connect() *net.UnixConn {
if cl.path == "" {
return nil
}
if atomic.LoadUint32(&cl.connected) > 0 {
// Guaranteed to be non-nil
return (*net.UnixConn)(atomic.LoadPointer(&cl.conn))
}
cl.mutex.Lock()
defer cl.mutex.Unlock()
// Safe to read cl.conn while holding the mutex
conn := (*net.UnixConn)(cl.conn)
// Did someone else connect while we were contending on the lock?
// cl.connected may be written to by others concurrently
if atomic.LoadUint32(&cl.connected) > 0 {
return conn
}
if conn != nil {
conn.Close() // not setting conn to nil!
}
logrus.Debugf("Accesslog: Connecting to Cilium access log socket: %s", cl.path)
conn, err := net.DialUnix("unixpacket", nil, &net.UnixAddr{Name: cl.path, Net: "unixpacket"})
if err != nil {
logrus.WithError(err).Error("Accesslog: DialUnix() failed")
return nil
}
atomic.StorePointer(&cl.conn, unsafe.Pointer(conn))
// Always have a non-nil 'cl.conn' after 'cl.connected' is set for the first time!
atomic.StoreUint32(&cl.connected, 1)
return conn
}
func (cl *Client) Log(pblog *cilium.LogEntry) {
if conn := cl.connect(); conn != nil {
// Encode
logmsg, err := proto.Marshal(pblog)
if err != nil {
logrus.WithError(err).Error("Accesslog: Protobuf marshaling error")
return
}
// Write
_, err = conn.Write(logmsg)
if err != nil {
logrus.WithError(err).Error("Accesslog: Write() failed")
atomic.StoreUint32(&cl.connected, 0) // Mark connection as broken
}
} else {
logrus.Debugf("Accesslog: No connection, cannot send: %s", pblog.String())
}
}
func (c *Client) Path() string {
return c.path
}
func NewClient(accessLogPath string) proxylib.AccessLogger {
client := &Client{
path: accessLogPath,
}
client.connect()
return client
}
func (cl *Client) Close() {
conn := (*net.UnixConn)(atomic.LoadPointer(&cl.conn))
if conn != nil {
conn.Close()
}
}