-
Notifications
You must be signed in to change notification settings - Fork 344
/
conntrack_connections.go
260 lines (239 loc) · 9.49 KB
/
conntrack_connections.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// Copyright 2021 Antrea Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package connections
import (
"encoding/binary"
"fmt"
"time"
"github.com/vmware/go-ipfix/pkg/registry"
corev1 "k8s.io/api/core/v1"
"k8s.io/klog/v2"
"antrea.io/antrea/pkg/agent/flowexporter"
"antrea.io/antrea/pkg/agent/flowexporter/flowrecords"
"antrea.io/antrea/pkg/agent/interfacestore"
"antrea.io/antrea/pkg/agent/metrics"
"antrea.io/antrea/pkg/agent/openflow"
"antrea.io/antrea/pkg/agent/proxy"
"antrea.io/antrea/pkg/querier"
)
var serviceProtocolMap = map[uint8]corev1.Protocol{
6: corev1.ProtocolTCP,
17: corev1.ProtocolUDP,
132: corev1.ProtocolSCTP,
}
type ConntrackConnectionStore struct {
flowRecords *flowrecords.FlowRecords
connDumper ConnTrackDumper
v4Enabled bool
v6Enabled bool
networkPolicyQuerier querier.AgentNetworkPolicyInfoQuerier
pollInterval time.Duration
connectionStore
}
func NewConntrackConnectionStore(
connTrackDumper ConnTrackDumper,
flowRecords *flowrecords.FlowRecords,
ifaceStore interfacestore.InterfaceStore,
v4Enabled bool,
v6Enabled bool,
proxier proxy.Proxier,
npQuerier querier.AgentNetworkPolicyInfoQuerier,
pollInterval time.Duration,
) *ConntrackConnectionStore {
return &ConntrackConnectionStore{
flowRecords: flowRecords,
connDumper: connTrackDumper,
v4Enabled: v4Enabled,
v6Enabled: v6Enabled,
networkPolicyQuerier: npQuerier,
pollInterval: pollInterval,
connectionStore: NewConnectionStore(ifaceStore, proxier),
}
}
// Run enables the periodical polling of conntrack connections at a given flowPollInterval.
func (cs *ConntrackConnectionStore) Run(stopCh <-chan struct{}) {
klog.Infof("Starting conntrack polling")
pollTicker := time.NewTicker(cs.pollInterval)
defer pollTicker.Stop()
for {
select {
case <-stopCh:
break
case <-pollTicker.C:
_, err := cs.Poll()
if err != nil {
// Not failing here as errors can be transient and could be resolved in future poll cycles.
// TODO: Come up with a backoff/retry mechanism by increasing poll interval and adding retry timeout
klog.Errorf("Error during conntrack poll cycle: %v", err)
}
// AddOrUpdateFlowRecord method does not return any error, hence no error handling required.
cs.ForAllConnectionsDo(cs.flowRecords.AddOrUpdateFlowRecord)
klog.V(2).Infof("Flow records are successfully updated")
}
}
}
// Poll calls into conntrackDumper interface to dump conntrack flows. It returns the number of connections for each
// address family, as a slice. In dual-stack clusters, the slice will contain 2 values (number of IPv4 connections first,
// then number of IPv6 connections).
// TODO: As optimization, only poll invalid/closed connections during every poll, and poll the established connections right before the export.
func (cs *ConntrackConnectionStore) Poll() ([]int, error) {
klog.V(2).Infof("Polling conntrack")
// Reset IsPresent flag for all connections in connection map before dumping flows in conntrack module.
// if the connection does not exist in conntrack table and has been exported, we will delete it from connection map.
deleteIfStaleOrResetConn := func(key flowexporter.ConnectionKey, conn *flowexporter.Connection) error {
if !conn.IsPresent && conn.DoneExport {
if err := cs.DeleteConnWithoutLock(key); err != nil {
return err
}
} else {
conn.IsPresent = false
}
return nil
}
if err := cs.ForAllConnectionsDo(deleteIfStaleOrResetConn); err != nil {
return []int{}, err
}
var zones []uint16
var connsLens []int
if cs.v4Enabled {
zones = append(zones, openflow.CtZone)
}
if cs.v6Enabled {
zones = append(zones, openflow.CtZoneV6)
}
var totalConns int
for _, zone := range zones {
filteredConnsList, totalConnsPerZone, err := cs.connDumper.DumpFlows(zone)
if err != nil {
return []int{}, err
}
totalConns += totalConnsPerZone
// Update only the Connection store. IPFIX records are generated based on Connection store.
for _, conn := range filteredConnsList {
cs.AddOrUpdateConn(conn)
}
connsLens = append(connsLens, len(filteredConnsList))
}
metrics.TotalConnectionsInConnTrackTable.Set(float64(totalConns))
maxConns, err := cs.connDumper.GetMaxConnections()
if err != nil {
return []int{}, err
}
metrics.MaxConnectionsInConnTrackTable.Set(float64(maxConns))
klog.V(2).Infof("Conntrack polling successful")
return connsLens, nil
}
func (cs *ConntrackConnectionStore) addNetworkPolicyMetadata(conn *flowexporter.Connection) {
// Retrieve NetworkPolicy Name and Namespace by using the ingress and egress
// IDs stored in the connection label.
if len(conn.Labels) != 0 {
klog.V(4).Infof("connection label: %x; label masks: %x", conn.Labels, conn.LabelsMask)
ingressOfID := binary.LittleEndian.Uint32(conn.Labels[:4])
egressOfID := binary.LittleEndian.Uint32(conn.Labels[4:8])
if ingressOfID != 0 {
policy := cs.networkPolicyQuerier.GetNetworkPolicyByRuleFlowID(ingressOfID)
rule := cs.networkPolicyQuerier.GetRuleByFlowID(ingressOfID)
if policy == nil || rule == nil {
// This should not happen because the rule flow ID to rule mapping is
// preserved for max(5s, flowPollInterval) even after the rule deletion.
klog.Warningf("Cannot find NetworkPolicy or rule with ingressOfID %v", ingressOfID)
} else {
conn.IngressNetworkPolicyName = policy.Name
conn.IngressNetworkPolicyNamespace = policy.Namespace
conn.IngressNetworkPolicyType = flowexporter.PolicyTypeToUint8(policy.Type)
conn.IngressNetworkPolicyRuleName = rule.Name
conn.IngressNetworkPolicyRuleAction = registry.NetworkPolicyRuleActionAllow
}
}
if egressOfID != 0 {
policy := cs.networkPolicyQuerier.GetNetworkPolicyByRuleFlowID(egressOfID)
rule := cs.networkPolicyQuerier.GetRuleByFlowID(egressOfID)
if policy == nil || rule == nil {
// This should not happen because the rule flow ID to rule mapping is
// preserved for max(5s, flowPollInterval) even after the rule deletion.
klog.Warningf("Cannot find NetworkPolicy or rule with egressOfID %v", egressOfID)
} else {
conn.EgressNetworkPolicyName = policy.Name
conn.EgressNetworkPolicyNamespace = policy.Namespace
conn.EgressNetworkPolicyType = flowexporter.PolicyTypeToUint8(policy.Type)
conn.EgressNetworkPolicyRuleName = rule.Name
conn.EgressNetworkPolicyRuleAction = registry.NetworkPolicyRuleActionAllow
}
}
}
}
// AddOrUpdateConn updates the connection if it is already present, i.e., update timestamp, counters etc.,
// or adds a new connection with the resolved K8s metadata.
func (cs *ConntrackConnectionStore) AddOrUpdateConn(conn *flowexporter.Connection) {
connKey := flowexporter.NewConnectionKey(conn)
cs.mutex.Lock()
defer cs.mutex.Unlock()
existingConn, exists := cs.connections[connKey]
if exists {
existingConn.IsPresent = true
// avoid updating stats of the existing connection that is about to close
if flowexporter.IsConnectionDying(existingConn) {
return
}
// Update the necessary fields that are used in generating flow records.
// Can same 5-tuple flow get deleted and added to conntrack table? If so use ID.
existingConn.StopTime = conn.StopTime
existingConn.OriginalBytes = conn.OriginalBytes
existingConn.OriginalPackets = conn.OriginalPackets
existingConn.ReverseBytes = conn.ReverseBytes
existingConn.ReversePackets = conn.ReversePackets
existingConn.TCPState = conn.TCPState
klog.V(4).Infof("Antrea flow updated: %v", existingConn)
} else {
cs.fillPodInfo(conn)
if conn.Mark == openflow.ServiceCTMark {
clusterIP := conn.DestinationServiceAddress.String()
svcPort := conn.DestinationServicePort
protocol, err := lookupServiceProtocol(conn.FlowKey.Protocol)
if err != nil {
klog.Warningf("Could not retrieve Service protocol: %v", err)
} else {
serviceStr := fmt.Sprintf("%s:%d/%s", clusterIP, svcPort, protocol)
cs.fillServiceInfo(conn, serviceStr)
}
}
cs.addNetworkPolicyMetadata(conn)
metrics.TotalAntreaConnectionsInConnTrackTable.Inc()
klog.V(4).Infof("New Antrea flow added: %v", conn)
// Add new antrea connection to connection store
cs.connections[connKey] = conn
}
}
// DeleteConnWithoutLock deletes the connection from the connection map given
// the connection key without grabbing the lock. Caller is expected to grab lock.
func (cs *ConntrackConnectionStore) DeleteConnWithoutLock(connKey flowexporter.ConnectionKey) error {
_, exists := cs.connections[connKey]
if !exists {
return fmt.Errorf("connection with key %v doesn't exist in map", connKey)
}
delete(cs.connections, connKey)
metrics.TotalAntreaConnectionsInConnTrackTable.Dec()
return nil
}
// SetExportDone sets DoneExport field of conntrack connection to true given the connection key.
func (cs *ConntrackConnectionStore) SetExportDone(connKey flowexporter.ConnectionKey) error {
cs.mutex.Lock()
defer cs.mutex.Unlock()
if conn, found := cs.connections[connKey]; !found {
return fmt.Errorf("connection with key %v does not exist in connection map", connKey)
} else {
conn.DoneExport = true
return nil
}
}