forked from projectcalico/felix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-workload.go
360 lines (323 loc) · 10.2 KB
/
test-workload.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Copyright (c) 2017-2019 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 main
import (
"fmt"
"io"
"net"
"os"
"os/exec"
"strings"
"time"
"github.com/containernetworking/cni/pkg/ns"
"github.com/docopt/docopt-go"
log "github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
"github.com/projectcalico/felix/fv/utils"
)
const usage = `test-workload, test workload for Felix FV testing.
If <interface-name> is "", the workload will start in the current namespace.
Usage:
test-workload [--udp] [--namespace-path=<path>] [--sidecar-iptables] [--up-lo] <interface-name> <ip-address> <ports>
`
func main() {
log.SetLevel(log.DebugLevel)
arguments, err := docopt.Parse(usage, nil, true, "v0.1", false)
if err != nil {
println(usage)
log.WithError(err).Fatal("Failed to parse usage")
}
interfaceName := arguments["<interface-name>"].(string)
ipAddress := arguments["<ip-address>"].(string)
portsStr := arguments["<ports>"].(string)
udp := arguments["--udp"].(bool)
nsPath := ""
if arg, ok := arguments["--namespace-path"]; ok && arg != nil {
nsPath = arg.(string)
}
sidecarIptables := arguments["--sidecar-iptables"].(bool)
upLo := arguments["--up-lo"].(bool)
panicIfError(err)
ports := strings.Split(portsStr, ",")
var namespace ns.NetNS
if nsPath != "" {
namespace, err = ns.GetNS(nsPath)
if err != nil {
log.WithError(err).WithField("namespace path", nsPath).Fatal("Failed to get netns from path")
}
} else if interfaceName != "" {
// Create a new network namespace for the workload.
attempts := 0
for {
namespace, err = ns.NewNS()
if err == nil {
break
}
log.WithError(err).Error("Failed to create namespace")
attempts++
time.Sleep(1 * time.Second)
if attempts > 30 {
log.WithError(err).Panic("Giving up after multiple retries")
}
}
log.WithField("namespace", namespace).Debug("Created namespace")
peerName := "w" + interfaceName
if len(peerName) > 11 {
peerName = peerName[:11]
}
// Create a veth pair.
veth := &netlink.Veth{
LinkAttrs: netlink.LinkAttrs{Name: interfaceName},
PeerName: peerName,
}
err = netlink.LinkAdd(veth)
panicIfError(err)
log.WithField("veth", veth).Debug("Created veth pair")
err := netlink.LinkSetUp(veth)
panicIfError(err)
peerVeth, err := netlink.LinkByName(veth.PeerName)
panicIfError(err)
// Need to set the peer up in order to get an IPv6 address.
err = netlink.LinkSetUp(peerVeth)
panicIfError(err)
var hostIPv6Addr net.IP
if strings.Contains(ipAddress, ":") {
attempts := 0
for {
// No need to add a dummy next hop route as the host veth device will already have an IPv6
// link local address that can be used as a next hop.
// Just fetch the address of the host end of the veth and use it as the next hop.
addresses, err := netlink.AddrList(veth, netlink.FAMILY_V6)
if err != nil {
log.WithError(err).Panic("Error listing IPv6 addresses for the host side of the veth pair")
}
if len(addresses) < 1 {
attempts++
if attempts > 30 {
log.WithError(err).Panic("Giving up waiting for IPv6 addresses after multiple retries")
}
time.Sleep(100 * time.Millisecond)
continue
}
hostIPv6Addr = addresses[0].IP
break
}
}
// Move the workload end of the pair into the namespace, and set it up.
workloadIf, err := netlink.LinkByName(veth.PeerName)
log.WithField("workloadIf", workloadIf).Debug("Workload end")
panicIfError(err)
err = netlink.LinkSetNsFd(workloadIf, int(namespace.Fd()))
panicIfError(err)
err = namespace.Do(func(_ ns.NetNS) (err error) {
err = utils.RunCommand("ip", "link", "set", veth.PeerName, "name", "eth0")
if err != nil {
return
}
err = utils.RunCommand("ip", "link", "set", "eth0", "up")
if err != nil {
return
}
if strings.Contains(ipAddress, ":") {
// Make sure ipv6 is enabled in the container/pod network namespace.
// Without these sysctls enabled, interfaces will come up but they won't get a link local IPv6 address,
// which is required to add the default IPv6 route.
if err = writeProcSys("/proc/sys/net/ipv6/conf/all/disable_ipv6", "0"); err != nil {
return
}
if err = writeProcSys("/proc/sys/net/ipv6/conf/default/disable_ipv6", "0"); err != nil {
return
}
if err = writeProcSys("/proc/sys/net/ipv6/conf/lo/disable_ipv6", "0"); err != nil {
return
}
err = utils.RunCommand("ip", "-6", "addr", "add", ipAddress+"/128", "dev", "eth0")
if err != nil {
return
}
err = utils.RunCommand("ip", "-6", "route", "add", "default", "via", hostIPv6Addr.String(), "dev", "eth0")
// Output the routing table to the log for diagnostic purposes.
utils.RunCommand("ip", "-6", "route")
utils.RunCommand("ip", "-6", "addr")
} else {
err = utils.RunCommand("ip", "addr", "add", ipAddress+"/32", "dev", "eth0")
if err != nil {
return
}
err = utils.RunCommand("ip", "route", "add", "169.254.169.254/32", "dev", "eth0")
if err != nil {
return
}
err = utils.RunCommand("ip", "route", "add", "default", "via", "169.254.169.254", "dev", "eth0")
// Output the routing table to the log for diagnostic purposes.
utils.RunCommand("ip", "route")
utils.RunCommand("ip", "addr")
}
return
})
panicIfError(err)
// Set the host end up too.
hostIf, err := netlink.LinkByName(veth.LinkAttrs.Name)
log.WithField("hostIf", hostIf).Debug("Host end")
panicIfError(err)
err = netlink.LinkSetUp(hostIf)
panicIfError(err)
} else {
namespace, err = ns.GetCurrentNS()
panicIfError(err)
}
// Print out the namespace path, so that test code can pick it up and execute subsequent
// operations in the same namespace - which (in the context of this FV framework)
// effectively means _as_ this workload.
fmt.Println(namespace.Path())
// Now listen on the specified ports in the workload namespace.
err = namespace.Do(func(_ ns.NetNS) error {
if upLo {
if err := utils.RunCommand("ip", "link", "set", "lo", "up"); err != nil {
return fmt.Errorf("failed to bring loopback up: %v", err)
}
}
if sidecarIptables {
if err := doSidecarIptablesSetup(); err != nil {
return fmt.Errorf("failed to setup sidecar-like iptables: %v", err)
}
}
if strings.Contains(ipAddress, ":") {
attempts := 0
for {
out, err := exec.Command("ip", "-6", "addr").CombinedOutput()
panicIfError(err)
if strings.Contains(string(out), "tentative") {
attempts++
if attempts > 30 {
log.Panic("IPv6 address still tentative after 30s")
}
time.Sleep(1 * time.Second)
continue
}
break
}
}
handleRequest := func(conn net.Conn) {
log.WithFields(log.Fields{
"localAddr": conn.LocalAddr(),
"remoteAddr": conn.RemoteAddr(),
}).Info("Accepted new connection.")
defer func() {
conn.Close()
log.Info("Closed connection.")
}()
for {
buf := make([]byte, 1024)
size, err := conn.Read(buf)
if err != nil {
return
}
data := buf[:size]
log.WithField("data", data).Info("Read data from connection")
conn.Write(data)
}
}
// Listen on each port for either TCP or UDP.
for _, port := range ports {
var myAddr string
if strings.Contains(ipAddress, ":") {
myAddr = "[" + ipAddress + "]:" + port
} else {
myAddr = ipAddress + ":" + port
}
logCxt := log.WithFields(log.Fields{
"udp": udp,
"myAddr": myAddr,
})
if udp {
// Since UDP is connectionless, we can't use Listen() as we do for TCP. Instead,
// we use ListenPacket so that we can directly send/receive individual packets.
logCxt.Info("About to listen for UDP packets")
p, err := net.ListenPacket("udp", myAddr)
panicIfError(err)
logCxt.Info("Listening for UDP connections")
go func() {
defer p.Close()
for {
buffer := make([]byte, 1024)
n, addr, err := p.ReadFrom(buffer)
panicIfError(err)
_, err = p.WriteTo(buffer[:n], addr)
logCxt.WithError(err).WithField("remoteAddr", addr).Info("Responded")
}
}()
} else {
logCxt.Info("About to listen for TCP connections")
l, err := net.Listen("tcp", myAddr)
panicIfError(err)
logCxt.Info("Listening for TCP connections")
go func() {
defer l.Close()
for {
conn, err := l.Accept()
panicIfError(err)
go handleRequest(conn)
}
}()
}
}
for {
time.Sleep(10 * time.Second)
}
return nil
})
panicIfError(err)
}
func panicIfError(err error) {
if err != nil {
panic(err)
}
return
}
// writeProcSys takes the sysctl path and a string value to set i.e. "0" or "1" and sets the sysctl.
func writeProcSys(path, value string) error {
f, err := os.OpenFile(path, os.O_WRONLY, 0)
if err != nil {
return err
}
n, err := f.Write([]byte(value))
if err == nil && n < len(value) {
err = io.ErrShortWrite
}
if err1 := f.Close(); err == nil {
err = err1
}
return err
}
// doSidecarIptablesSetup generates some iptables rules to redirect a
// traffic to localhost:15001. This is to simulate a sidecar.
//
// Commands are a very simplified version of commands from
// https://github.com/istio/cni/blob/f1a08bef3f235de1ecb67074b741b0d4c5fd8c44/tools/deb/istio-iptables.sh
func doSidecarIptablesSetup() error {
cmds := [][]string{
{"iptables", "-t", "nat", "-N", "FV_WL_REDIRECT"},
{"iptables", "-t", "nat", "-A", "FV_WL_REDIRECT", "-p", "tcp", "-j", "REDIRECT", "--to-port", "15001"},
{"iptables", "-t", "nat", "-N", "FV_WL_OUTPUT"},
{"iptables", "-t", "nat", "-A", "OUTPUT", "-p", "tcp", "-j", "FV_WL_OUTPUT"},
{"iptables", "-t", "nat", "-A", "FV_WL_OUTPUT", "!", "-d", "127.0.0.1/32", "-j", "FV_WL_REDIRECT"},
}
for _, cmd := range cmds {
if err := utils.RunCommand(cmd[0], cmd[1:]...); err != nil {
return err
}
}
return nil
}