-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
reconciler.go
302 lines (263 loc) · 8.33 KB
/
reconciler.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package iptables
import (
"context"
"net"
"net/netip"
"github.com/cilium/hive/cell"
"github.com/cilium/stream"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/util/sets"
"github.com/cilium/cilium/pkg/datapath/tables"
"github.com/cilium/cilium/pkg/logging"
"github.com/cilium/cilium/pkg/node"
"github.com/cilium/cilium/pkg/time"
)
type desiredState struct {
installRules bool
devices sets.Set[string]
localNodeInfo localNodeInfo
proxies map[string]proxyInfo
noTrackPods sets.Set[noTrackPodInfo]
}
type localNodeInfo struct {
internalIPv4 net.IP
internalIPv6 net.IP
ipv4AllocCIDR string
ipv6AllocCIDR string
ipv4NativeRoutingCIDR string
ipv6NativeRoutingCIDR string
}
func (lni localNodeInfo) equal(other localNodeInfo) bool {
if lni.internalIPv4.Equal(other.internalIPv4) &&
lni.internalIPv6.Equal(other.internalIPv6) &&
lni.ipv4AllocCIDR == other.ipv4AllocCIDR &&
lni.ipv6AllocCIDR == other.ipv6AllocCIDR &&
lni.ipv4NativeRoutingCIDR == other.ipv4NativeRoutingCIDR &&
lni.ipv6NativeRoutingCIDR == other.ipv6NativeRoutingCIDR {
return true
}
return false
}
func toLocalNodeInfo(n node.LocalNode) localNodeInfo {
var (
v4AllocCIDR, v6AllocCIDR string
v4NativeRoutingCIDR, v6NativeRoutingCIDR string
)
if n.IPv4AllocCIDR != nil {
v4AllocCIDR = n.IPv4AllocCIDR.String()
}
if n.IPv6AllocCIDR != nil {
v6AllocCIDR = n.IPv6AllocCIDR.String()
}
if n.IPv4NativeRoutingCIDR != nil {
v4NativeRoutingCIDR = n.IPv4NativeRoutingCIDR.String()
}
if n.IPv6NativeRoutingCIDR != nil {
v6NativeRoutingCIDR = n.IPv6NativeRoutingCIDR.String()
}
return localNodeInfo{
internalIPv4: n.GetCiliumInternalIP(false),
internalIPv6: n.GetCiliumInternalIP(true),
ipv4AllocCIDR: v4AllocCIDR,
ipv6AllocCIDR: v6AllocCIDR,
ipv4NativeRoutingCIDR: v4NativeRoutingCIDR,
ipv6NativeRoutingCIDR: v6NativeRoutingCIDR,
}
}
// reconciliationRequest is a request to the reconciler to update the
// state with the new info.
// updated is a notification channel that is closed when reconciliation has
// been completed successfully.
type reconciliationRequest[T any] struct {
info T
// closed when the state is reconciled successfully
updated chan struct{}
}
type proxyInfo struct {
name string
port uint16
isLocalOnly bool
}
type noTrackPodInfo struct {
ip netip.Addr
port uint16
}
func reconciliationLoop(
ctx context.Context,
log logrus.FieldLogger,
health cell.Health,
installIptRules bool,
params *reconcilerParams,
updateRules func(state desiredState, firstInit bool) error,
updateProxyRules func(proxyPort uint16, localOnly bool, name string) error,
installNoTrackRules func(addr netip.Addr, port uint16) error,
removeNoTrackRules func(addr netip.Addr, port uint16) error,
) error {
// The minimum interval between reconciliation attempts
const minReconciliationInterval = 200 * time.Millisecond
// log limiter for partial (proxy and no track rules) reconciliation errors
partialLogLimiter := logging.NewLimiter(10*time.Second, 3)
// log limiter for full reconciliation errors
fullLogLimiter := logging.NewLimiter(10*time.Second, 3)
state := desiredState{
installRules: installIptRules,
proxies: make(map[string]proxyInfo),
noTrackPods: sets.New[noTrackPodInfo](),
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
localNodeEvents := stream.ToChannel(ctx, params.localNodeStore)
state.localNodeInfo = toLocalNodeInfo(<-localNodeEvents)
devices, devicesWatch := tables.SelectedDevices(params.devices, params.db.ReadTxn())
state.devices = sets.New(tables.DeviceNames(devices)...)
// Use a ticker to limit how often the desired state is reconciled to avoid doing
// lots of operations when e.g. ipset updates.
ticker := time.NewTicker(minReconciliationInterval)
defer ticker.Stop()
// stateChanged is true when the desired state has changed or when reconciling it
// has failed. It's set to false when reconciling succeeds.
stateChanged := true
firstInit := true
// list of pending channels waiting for reconciliation
var updatedChs []chan<- struct{}
stop:
for {
select {
case <-ctx.Done():
break stop
case <-devicesWatch:
devices, devicesWatch = tables.SelectedDevices(params.devices, params.db.ReadTxn())
newDevices := sets.New(tables.DeviceNames(devices)...)
if newDevices.Equal(state.devices) {
continue
}
state.devices = newDevices
stateChanged = true
case localNode, ok := <-localNodeEvents:
if !ok {
break stop
}
localNodeInfo := toLocalNodeInfo(localNode)
if localNodeInfo.equal(state.localNodeInfo) {
continue
}
state.localNodeInfo = localNodeInfo
stateChanged = true
case req, ok := <-params.proxies:
if !ok {
break stop
}
if info, ok := state.proxies[req.info.name]; ok && info == req.info {
continue
}
// if existing, previous rules related to the previous entry for the same proxy name
// will be deleted by the manager (see Manager.addProxyRules)
state.proxies[req.info.name] = req.info
if !firstInit {
// first init not yet completed, proxy rules will be updated as part of that
stateChanged = true
updatedChs = append(updatedChs, req.updated)
continue
}
if err := updateProxyRules(req.info.port, req.info.isLocalOnly, req.info.name); err != nil {
if partialLogLimiter.Allow() {
log.WithError(err).Error("iptables proxy rules incremental update failed, will retry a full reconciliation")
}
// incremental rules update failed, schedule a full iptables reconciliation
stateChanged = true
updatedChs = append(updatedChs, req.updated)
} else {
close(req.updated)
}
case req, ok := <-params.addNoTrackPod:
if !ok {
break stop
}
if state.noTrackPods.Has(req.info) {
close(req.updated)
continue
}
state.noTrackPods.Insert(req.info)
if !firstInit {
// first init not yet completed, no track pod rules will be updated as part of that
stateChanged = true
updatedChs = append(updatedChs, req.updated)
continue
}
if err := installNoTrackRules(req.info.ip, req.info.port); err != nil {
if partialLogLimiter.Allow() {
log.WithError(err).Error("iptables no track rules incremental install failed, will retry a full reconciliation")
}
// incremental rules update failed, schedule a full iptables reconciliation
stateChanged = true
updatedChs = append(updatedChs, req.updated)
} else {
close(req.updated)
}
case req, ok := <-params.delNoTrackPod:
if !ok {
break stop
}
if !state.noTrackPods.Has(req.info) {
close(req.updated)
continue
}
state.noTrackPods.Delete(req.info)
if !firstInit {
// first init not yet completed, no track pod rules will be updated as part of that
stateChanged = true
updatedChs = append(updatedChs, req.updated)
continue
}
if err := removeNoTrackRules(req.info.ip, req.info.port); err != nil {
if partialLogLimiter.Allow() {
log.WithError(err).Error("iptables no track rules incremental removal failed, will retry a full reconciliation")
}
// incremental rules update failed, schedule a full iptables reconciliation
stateChanged = true
updatedChs = append(updatedChs, req.updated)
} else {
close(req.updated)
}
case <-ticker.C:
if !stateChanged {
continue
}
if err := updateRules(state, firstInit); err != nil {
if fullLogLimiter.Allow() {
log.WithError(err).Error("iptables rules full reconciliation failed, will retry another one later")
}
health.Degraded("iptables rules full reconciliation failed", err)
// Keep stateChanged=true to try again on the next tick.
} else {
health.OK("iptables rules full reconciliation completed")
firstInit = false
stateChanged = false
}
// close all channels waiting for reconciliation
// do this even in case of a failed reconciliation, to avoid
// blocking consumer goroutines indefinitely.
for _, ch := range updatedChs {
close(ch)
}
updatedChs = updatedChs[:0]
}
}
cancel()
// close all channels waiting for reconciliation
for _, ch := range updatedChs {
close(ch)
}
// drain channels
for range localNodeEvents {
}
for range params.proxies {
}
for range params.addNoTrackPod {
}
for range params.delNoTrackPod {
}
return nil
}