forked from projectcalico/felix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
feature_detect.go
266 lines (236 loc) · 8.8 KB
/
feature_detect.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
// Copyright (c) 2018-2020 Tigera, Inc. All rights reserved.
//
// 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 iptables
import (
"bytes"
"io"
"os/exec"
"regexp"
"strconv"
"strings"
"sync"
log "github.com/sirupsen/logrus"
"github.com/projectcalico/felix/versionparse"
)
var (
vXDotYDotZRegexp = regexp.MustCompile(`v(\d+\.\d+\.\d+)`)
// iptables versions:
// v1Dot4Dot7 is the oldest version we've ever supported.
v1Dot4Dot7 = versionparse.MustParseVersion("1.4.7")
// v1Dot6Dot0 added --random-fully to SNAT.
v1Dot6Dot0 = versionparse.MustParseVersion("1.6.0")
// v1Dot6Dot2 added --random-fully to MASQUERADE and the xtables lock to iptables-restore.
v1Dot6Dot2 = versionparse.MustParseVersion("1.6.2")
// Linux kernel versions:
// v3Dot10Dot0 is the oldest version we support at time of writing.
v3Dot10Dot0 = versionparse.MustParseVersion("3.10.0")
// v3Dot14Dot0 added the random-fully feature on the iptables interface.
v3Dot14Dot0 = versionparse.MustParseVersion("3.14.0")
)
type Features struct {
// SNATFullyRandom is true if --random-fully is supported by the SNAT action.
SNATFullyRandom bool
// MASQFullyRandom is true if --random-fully is supported by the MASQUERADE action.
MASQFullyRandom bool
// RestoreSupportsLock is true if the iptables-restore command supports taking the xtables lock and the
// associated -w and -W arguments.
RestoreSupportsLock bool
}
type FeatureDetector struct {
lock sync.Mutex
featureCache *Features
featureOverride map[string]string
// Path to file with kernel version
GetKernelVersionReader func() (io.Reader, error)
// Factory for making commands, used by UTs to shim exec.Command().
NewCmd cmdFactory
}
func NewFeatureDetector(overrides map[string]string) *FeatureDetector {
return &FeatureDetector{
GetKernelVersionReader: versionparse.GetKernelVersionReader,
NewCmd: NewRealCmd,
featureOverride: overrides,
}
}
func (d *FeatureDetector) GetFeatures() *Features {
d.lock.Lock()
defer d.lock.Unlock()
if d.featureCache == nil {
d.refreshFeaturesLockHeld()
}
return d.featureCache
}
func (d *FeatureDetector) RefreshFeatures() {
d.lock.Lock()
defer d.lock.Unlock()
d.refreshFeaturesLockHeld()
}
func (d *FeatureDetector) refreshFeaturesLockHeld() {
// Get the versions. If we fail to detect a version for some reason, we use a safe default.
log.Debug("Refreshing detected iptables features")
iptV := d.getIptablesVersion()
kerV := d.getKernelVersion()
// Calculate the features.
features := Features{
SNATFullyRandom: iptV.Compare(v1Dot6Dot0) >= 0 && kerV.Compare(v3Dot14Dot0) >= 0,
MASQFullyRandom: iptV.Compare(v1Dot6Dot2) >= 0 && kerV.Compare(v3Dot14Dot0) >= 0,
RestoreSupportsLock: iptV.Compare(v1Dot6Dot2) >= 0,
}
if value, ok := (d.featureOverride)["SNATFullyRandom"]; ok {
ovr, err := strconv.ParseBool(value)
if err == nil {
log.WithField("override", ovr).Info("Override feature SNATFullyRandom")
features.SNATFullyRandom = ovr
}
}
if value, ok := (d.featureOverride)["MASQFullyRandom"]; ok {
ovr, err := strconv.ParseBool(value)
if err == nil {
log.WithField("override", ovr).Info("Override feature MASQFullyRandom")
features.MASQFullyRandom = ovr
}
}
if value, ok := (d.featureOverride)["RestoreSupportsLock"]; ok {
ovr, err := strconv.ParseBool(value)
if err == nil {
log.WithField("override", ovr).Info("Override feature RestoreSupportsLock")
features.RestoreSupportsLock = ovr
}
}
if d.featureCache == nil || *d.featureCache != features {
log.WithFields(log.Fields{
"features": features,
"kernelVersion": kerV,
"iptablesVersion": iptV,
}).Info("Updating detected iptables features")
d.featureCache = &features
}
}
func (d *FeatureDetector) getIptablesVersion() *versionparse.Version {
cmd := d.NewCmd("iptables", "--version")
out, err := cmd.Output()
if err != nil {
log.WithError(err).Warn("Failed to get iptables version, assuming old version with no optional features")
return v1Dot4Dot7
}
s := string(out)
log.WithField("rawVersion", s).Debug("Ran iptables --version")
matches := vXDotYDotZRegexp.FindStringSubmatch(s)
if len(matches) == 0 {
log.WithField("rawVersion", s).Warn(
"Failed to parse iptables version, assuming old version with no optional features")
return v1Dot4Dot7
}
parsedVersion, err := versionparse.NewVersion(matches[1])
if err != nil {
log.WithField("rawVersion", s).WithError(err).Warn(
"Failed to parse iptables version, assuming old version with no optional features")
return v1Dot4Dot7
}
log.WithField("version", parsedVersion).Debug("Parsed iptables version")
return parsedVersion
}
func (d *FeatureDetector) getKernelVersion() *versionparse.Version {
reader, err := d.GetKernelVersionReader()
if err != nil {
log.WithError(err).Warn("Failed to get the kernel version reader, assuming old version with no optional features")
return v3Dot10Dot0
}
kernVersion, err := versionparse.GetKernelVersion(reader)
if err != nil {
log.WithError(err).Warn("Failed to get kernel version, assuming old version with no optional features")
return v3Dot10Dot0
}
return kernVersion
}
func countRulesInIptableOutput(in []byte) int {
count := 0
for _, x := range bytes.Split(in, []byte("\n")) {
if len(x) >= 1 && x[0] == '-' {
count++
}
}
return count
}
// GetIptablesBackend attempts to detect the iptables backend being used where Felix is running.
// This code is duplicating the detection method found at
// https://github.com/kubernetes/kubernetes/blob/623b6978866b5d3790d17ff13601ef9e7e4f4bf0/build/debian-iptables/iptables-wrapper#L28
// If there is a specifiedBackend then it is used but if it does not match the detected
// backend then a warning is logged.
func DetectBackend(lookPath func(file string) (string, error), newCmd cmdFactory, specifiedBackend string) string {
ip6LgcySave := findBestBinary(lookPath, 6, "legacy", "save")
ip4LgcySave := findBestBinary(lookPath, 4, "legacy", "save")
ip6l, _ := newCmd(ip6LgcySave).Output()
ip4l, _ := newCmd(ip4LgcySave).Output()
log.WithField("ip6l", string(ip6l)).Debug("Ip6tables legacy save out")
log.WithField("ip4l", string(ip4l)).Debug("Iptables legacy save out")
legacyLines := countRulesInIptableOutput(ip6l) + countRulesInIptableOutput(ip4l)
var detectedBackend string
if legacyLines >= 10 {
detectedBackend = "legacy"
} else {
ip6NftSave := findBestBinary(lookPath, 6, "nft", "save")
ip4NftSave := findBestBinary(lookPath, 4, "nft", "save")
ip6n, _ := newCmd(ip6NftSave).Output()
log.WithField("ip6n", string(ip6n)).Debug("Ip6tables save out")
ip4n, _ := newCmd(ip4NftSave).Output()
log.WithField("ip4n", string(ip4n)).Debug("Iptables save out")
nftLines := countRulesInIptableOutput(ip6n) + countRulesInIptableOutput(ip4n)
if legacyLines >= nftLines {
detectedBackend = "legacy"
} else {
detectedBackend = "nft"
}
}
log.WithField("detectedBackend", detectedBackend).Debug("Detected Iptables backend")
specifiedBackend = strings.ToLower(specifiedBackend)
if specifiedBackend != "auto" {
if specifiedBackend != detectedBackend {
log.WithFields(log.Fields{"detectedBackend": detectedBackend, "specifiedBackend": specifiedBackend}).Warn("Iptables backend specified does not match the detected backend, using specified backend")
}
return specifiedBackend
}
return detectedBackend
}
// findBestBinary tries to find an iptables binary for the specific variant (legacy/nftables mode) and returns the name
// of the binary. Falls back on iptables-restore/iptables-save if the specific variant isn't available.
// Panics if no binary can be found.
func findBestBinary(lookPath func(file string) (string, error), ipVersion uint8, backendMode, saveOrRestore string) string {
if lookPath == nil {
lookPath = exec.LookPath
}
verInfix := ""
if ipVersion == 6 {
verInfix = "6"
}
candidates := []string{
"ip" + verInfix + "tables-" + backendMode + "-" + saveOrRestore,
"ip" + verInfix + "tables-" + saveOrRestore,
}
logCxt := log.WithFields(log.Fields{
"ipVersion": ipVersion,
"backendMode": backendMode,
"saveOrRestore": saveOrRestore,
"candidates": candidates,
})
for _, candidate := range candidates {
_, err := lookPath(candidate)
if err == nil {
logCxt.WithField("command", candidate).Info("Looked up iptables command")
return candidate
}
}
logCxt.Panic("Failed to find iptables command")
return ""
}