| 1 | Subject: [PATCH] qemu: connect the instance's netstack through the dgram netdev |
| 2 | |
| 3 | startUsernet gives QEMU its own gvisor-tap-vsock netstack through the |
| 4 | `socket` netdev (a length-prefixed stream on a unix socket). That netdev, |
| 5 | like `stream`, aborts QEMU in this case: net_socket_send() and |
| 6 | net_stream_data_send() ignore a recv() that fails with EWOULDBLOCK, but |
| 7 | then fall through to net_fill_rstate(rs, buf, size) with size == -1, |
| 8 | which skips its loop and fails `assert(size == 0)`: |
| 9 | |
| 10 | qemu-system-x86_64: ../net/net.c:2172: net_fill_rstate: Assertion |
| 11 | `size == 0' failed. |
| 12 | |
| 13 | QEMU exits with SIGABRT, the hostagent stops the instance, and the guest |
| 14 | loses its network in the middle of what it was doing (an apt install, in |
| 15 | agent-vm). It happens on Linux hosts with KVM, under sustained traffic, |
| 16 | with QEMU 10.2.x, to everyone whose guest goes through that netstack |
| 17 | (Lima's user-v2 network, Colima: qemu-project/qemu#3285, |
| 18 | estuary/flow#3267). What makes recv() return EAGAIN after poll() said |
| 19 | readable is not known. The fault is QEMU's: a unix stream socket whose |
| 20 | only pending data is an out-of-band byte does the same, with no netstack |
| 21 | (`-netdev socket,fd=N` or `-netdev stream`, the peer sends one MSG_OOB |
| 22 | byte). |
| 23 | |
| 24 | The dgram netdev (QEMU 7.2 or later) returns on any failed recv() and has |
| 25 | no framing to lose. With it, the netstack is served on a datagram |
| 26 | socketpair, as vz does for its network (createSockPair, AcceptBess): one |
| 27 | end is passed to QEMU (-netdev dgram,local.type=fd), the other is |
| 28 | served by usernet.GVisorNetstackOpts.DgramConn. A unix datagram socket |
| 29 | keeps frame boundaries and loses nothing: a full buffer blocks the |
| 30 | sender, and QEMU stops reading until it can write. |
| 31 | |
| 32 | Which one QEMU gets is decided by Cmdline, from the netdevs it lists, and |
| 33 | the netstack starts after it: it listens on the unix socket only for the |
| 34 | socket netdev, of a QEMU without dgram. Windows has no unix datagram |
| 35 | sockets and no file descriptor passing: it keeps the stream netdev, so the |
| 36 | abort remains possible there. |
| 37 | |
| 38 | Tests: TestDgramConn (a frame sent as a datagram is answered by the |
| 39 | netstack; it times out without DgramConn being served), TestDgramPair, |
| 40 | TestFdDgramTemplate. The netdev choice in Cmdline needs a QEMU binary: |
| 41 | checked by agent-vm's e2e (internal/vm/lima_e2e_test.go), whose guest |
| 42 | boots and installs packages through it. |
| 43 | |
| 44 | |
| 45 | |
| 46 | new file mode 100644 |
| 47 | |
| 48 | |
| 49 | |
| 50 | @@ -0,0 +1,45 @@ |
| 51 | +//go:build !windows |
| 52 | + |
| 53 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 54 | +// SPDX-License-Identifier: Apache-2.0 |
| 55 | + |
| 56 | +package qemu |
| 57 | + |
| 58 | +import ( |
| 59 | + "net" |
| 60 | + "os" |
| 61 | + "syscall" |
| 62 | +) |
| 63 | + |
| 64 | +// dgramPair returns the two ends of a connected datagram socket, as vz does |
| 65 | +// for its network: ours as a net.Conn for the netstack, and QEMU's as a file |
| 66 | +// to pass to it (-netdev dgram,local.type=fd). A datagram is a frame, and |
| 67 | +// unix datagram sockets neither lose nor reorder them: a full buffer blocks |
| 68 | +// the sender. |
| 69 | +func dgramPair() (ours net.Conn, qemu *os.File, err error) { |
| 70 | + // The descriptors must not leak into the processes started meanwhile: |
| 71 | + // QEMU gets its end through ExtraFiles. |
| 72 | + syscall.ForkLock.RLock() |
| 73 | + fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0) |
| 74 | + if err == nil { |
| 75 | + syscall.CloseOnExec(fds[0]) |
| 76 | + syscall.CloseOnExec(fds[1]) |
| 77 | + } |
| 78 | + syscall.ForkLock.RUnlock() |
| 79 | + if err != nil { |
| 80 | + return nil, nil, err |
| 81 | + } |
| 82 | + for _, fd := range fds { |
| 83 | + // Best effort: the kernel caps these (net.core.wmem_max, rmem_max). |
| 84 | + _ = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, 1<<20) |
| 85 | + _ = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, 4<<20) |
| 86 | + } |
| 87 | + f := os.NewFile(uintptr(fds[0]), "usernet-dgram") |
| 88 | + defer f.Close() |
| 89 | + ours, err = net.FileConn(f) |
| 90 | + if err != nil { |
| 91 | + syscall.Close(fds[1]) |
| 92 | + return nil, nil, err |
| 93 | + } |
| 94 | + return ours, os.NewFile(uintptr(fds[1]), "qemu-dgram"), nil |
| 95 | +} |
| 96 | |
| 97 | new file mode 100644 |
| 98 | |
| 99 | |
| 100 | |
| 101 | @@ -0,0 +1,56 @@ |
| 102 | +//go:build !windows |
| 103 | + |
| 104 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 105 | +// SPDX-License-Identifier: Apache-2.0 |
| 106 | + |
| 107 | +package qemu |
| 108 | + |
| 109 | +import ( |
| 110 | + "net" |
| 111 | + "testing" |
| 112 | + |
| 113 | + "gotest.tools/v3/assert" |
| 114 | +) |
| 115 | + |
| 116 | +// Each write is one datagram, both ways, and QEMU's end is a file that stays |
| 117 | +// usable once ours is a net.Conn. |
| 118 | +func TestDgramPair(t *testing.T) { |
| 119 | + ours, qemu, err := dgramPair() |
| 120 | + assert.NilError(t, err) |
| 121 | + t.Cleanup(func() { ours.Close(); qemu.Close() }) |
| 122 | + theirs, err := net.FileConn(qemu) |
| 123 | + assert.NilError(t, err) |
| 124 | + t.Cleanup(func() { theirs.Close() }) |
| 125 | + |
| 126 | + for _, c := range []struct{ from, to net.Conn }{{ours, theirs}, {theirs, ours}} { |
| 127 | + _, err = c.from.Write([]byte("abc")) |
| 128 | + assert.NilError(t, err) |
| 129 | + _, err = c.from.Write([]byte("defgh")) |
| 130 | + assert.NilError(t, err) |
| 131 | + buf := make([]byte, 64) |
| 132 | + n, err := c.to.Read(buf) |
| 133 | + assert.NilError(t, err) |
| 134 | + assert.Equal(t, string(buf[:n]), "abc") |
| 135 | + n, err = c.to.Read(buf) |
| 136 | + assert.NilError(t, err) |
| 137 | + assert.Equal(t, string(buf[:n]), "defgh") |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +// fd_dgram hands QEMU the datagram socket as the next file descriptor, after |
| 142 | +// those fd_connect made. |
| 143 | +func TestFdDgramTemplate(t *testing.T) { |
| 144 | + _, qemu, err := dgramPair() |
| 145 | + assert.NilError(t, err) |
| 146 | + t.Cleanup(func() { qemu.Close() }) |
| 147 | + |
| 148 | + a := &qArgTemplateApplier{dgram: qemu} |
| 149 | + got, err := a.applyTemplate("dgram,id=net0,local.type=fd,local.str={{ fd_dgram }}") |
| 150 | + assert.NilError(t, err) |
| 151 | + assert.Equal(t, got, "dgram,id=net0,local.type=fd,local.str=3") |
| 152 | + assert.DeepEqual(t, len(a.files), 1) |
| 153 | + assert.Equal(t, a.files[0], qemu) |
| 154 | + |
| 155 | + _, err = (&qArgTemplateApplier{}).applyTemplate("{{ fd_dgram }}") |
| 156 | + assert.ErrorContains(t, err, "no datagram socket") |
| 157 | +} |
| 158 | |
| 159 | new file mode 100644 |
| 160 | |
| 161 | |
| 162 | |
| 163 | @@ -0,0 +1,16 @@ |
| 164 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 165 | +// SPDX-License-Identifier: Apache-2.0 |
| 166 | + |
| 167 | +package qemu |
| 168 | + |
| 169 | +import ( |
| 170 | + "errors" |
| 171 | + "net" |
| 172 | + "os" |
| 173 | +) |
| 174 | + |
| 175 | +// dgramPair: Windows has no unix datagram sockets, and cannot pass a file |
| 176 | +// descriptor to QEMU. |
| 177 | +func dgramPair() (net.Conn, *os.File, error) { |
| 178 | + return nil, nil, errors.ErrUnsupported |
| 179 | +} |
| 180 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | @@ -50,6 +50,10 @@ type Config struct { |
| 185 | // UsernetQEMUSock is the QEMU socket of the instance's own gvisor |
| 186 | // netstack, used instead of slirp when set (see startUsernet). |
| 187 | UsernetQEMUSock string |
| 188 | + // UsernetDgram is QEMU's end of a datagram socketpair whose other end the |
| 189 | + // netstack serves, preferred to UsernetQEMUSock when QEMU has the dgram |
| 190 | + // netdev (see dgramPair). Nil on Windows. |
| 191 | + UsernetDgram *os.File |
| 192 | } |
| 193 | |
| 194 | // minimumQemuVersion returns hardMin and softMin. |
| 195 | @@ -788,11 +792,22 @@ func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err er |
| 196 | case firstUsernetIndex == -1 && cfg.UsernetQEMUSock != "" && runtime.GOOS == "windows": |
| 197 | // No file descriptor passing there (fd_connect): QEMU connects to the |
| 198 | // socket itself, which QEMU 7.2 or later can on Windows. The same |
| 199 | - // stream as the socket netdev's. |
| 200 | + // stream as the socket netdev's, so the same abort on EAGAIN (see the |
| 201 | + // dgram netdev below): Windows has no datagram unix sockets. |
| 202 | if !strings.Contains(string(features.NetdevHelp), "stream") { |
| 203 | return "", nil, errors.New("QEMU 7.2 or later is needed (its stream netdev)") |
| 204 | } |
| 205 | args = append(args, "-netdev", fmt.Sprintf("stream,id=net0,server=off,addr.type=unix,addr.path=%s", cfg.UsernetQEMUSock)) |
| 206 | + case firstUsernetIndex == -1 && cfg.UsernetDgram != nil && strings.Contains(string(features.NetdevHelp), "dgram"): |
| 207 | + // Not the socket netdev below: it reads a length-prefixed stream, and |
| 208 | + // QEMU (10.2.4 at least) aborts with `net_fill_rstate: Assertion |
| 209 | + // 'size == 0' failed` when its recv() returns EAGAIN, which it |
| 210 | + // meant to ignore (net_socket_send, and net_stream_data_send for the |
| 211 | + // stream netdev, fall through to net_fill_rstate with size -1). |
| 212 | + // Seen on Linux hosts, under sustained guest traffic. The dgram |
| 213 | + // netdev ignores a failed recv() and has no framing to lose. It |
| 214 | + // needs QEMU 7.2 or later. |
| 215 | + args = append(args, "-netdev", "dgram,id=net0,local.type=fd,local.str={{ fd_dgram }}") |
| 216 | case firstUsernetIndex == -1 && cfg.UsernetQEMUSock != "": |
| 217 | args = append(args, "-netdev", fmt.Sprintf("socket,id=net0,fd={{ fd_connect %q }}", cfg.UsernetQEMUSock)) |
| 218 | case firstUsernetIndex == -1: |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | @@ -67,40 +67,81 @@ type LimaQemuDriver struct { |
| 224 | usernetStop context.CancelFunc |
| 225 | } |
| 226 | |
| 227 | -// startUsernet starts the instance's own gvisor netstack, as vz does: one |
| 228 | -// network per instance, in the hostagent, where usernet.Outbound applies. |
| 229 | -func startUsernet(ctx context.Context, inst *limatype.Instance) (client *usernet.Client, qemuSock string, stop context.CancelFunc, err error) { |
| 230 | - endpointSock, err := usernet.SockWithDirectory(inst.Dir, "", usernet.EndpointSock) |
| 231 | +// usernetSockets are what connects QEMU to the instance's own gvisor netstack |
| 232 | +// (see startUsernet). QEMU gets the dgram end, or the socket path when its |
| 233 | +// netdevs have no dgram (see Cmdline): the netstack listens on the path only |
| 234 | +// then, as nothing else should be able to connect to it. |
| 235 | +type usernetSockets struct { |
| 236 | + endpoint string |
| 237 | + // qemu is the path of the socket netdev's listener. |
| 238 | + qemu string |
| 239 | + // dgramConn is the netstack's end of a datagram socketpair, qemuDgram |
| 240 | + // QEMU's. Both are nil on Windows. |
| 241 | + dgramConn net.Conn |
| 242 | + qemuDgram *os.File |
| 243 | +} |
| 244 | + |
| 245 | +func newUsernetSockets(inst *limatype.Instance) (*usernetSockets, error) { |
| 246 | + endpoint, err := usernet.SockWithDirectory(inst.Dir, "", usernet.EndpointSock) |
| 247 | if err != nil { |
| 248 | - return nil, "", nil, err |
| 249 | + return nil, err |
| 250 | } |
| 251 | - qemuSock, err = usernet.SockWithDirectory(inst.Dir, "", usernet.QEMUSock) |
| 252 | + qemu, err := usernet.SockWithDirectory(inst.Dir, "", usernet.QEMUSock) |
| 253 | if err != nil { |
| 254 | - return nil, "", nil, err |
| 255 | + return nil, err |
| 256 | } |
| 257 | - os.RemoveAll(endpointSock) |
| 258 | - os.RemoveAll(qemuSock) |
| 259 | - ctx, stop = context.WithCancel(ctx) |
| 260 | - err = usernet.StartGVisorNetstack(ctx, &usernet.GVisorNetstackOpts{ |
| 261 | - MTU: 1500, |
| 262 | - Endpoint: endpointSock, |
| 263 | - QemuSocket: qemuSock, |
| 264 | - Async: true, |
| 265 | + os.RemoveAll(endpoint) |
| 266 | + os.RemoveAll(qemu) |
| 267 | + s := &usernetSockets{endpoint: endpoint, qemu: qemu} |
| 268 | + s.dgramConn, s.qemuDgram, err = dgramPair() |
| 269 | + if err != nil && !errors.Is(err, errors.ErrUnsupported) { |
| 270 | + return nil, err |
| 271 | + } |
| 272 | + return s, nil |
| 273 | +} |
| 274 | + |
| 275 | +// closeQEMUEnd closes the file given to QEMU: it has its own copy once started. |
| 276 | +func (s *usernetSockets) closeQEMUEnd() { |
| 277 | + if s.qemuDgram != nil { |
| 278 | + s.qemuDgram.Close() |
| 279 | + } |
| 280 | +} |
| 281 | + |
| 282 | +// startUsernet starts the instance's own gvisor netstack, as vz does: one |
| 283 | +// network per instance, in the hostagent, where usernet.Outbound applies. |
| 284 | +// viaDgram says which end QEMU was given. |
| 285 | +func startUsernet(ctx context.Context, inst *limatype.Instance, s *usernetSockets, viaDgram bool) (client *usernet.Client, stop context.CancelFunc, err error) { |
| 286 | + opts := &usernet.GVisorNetstackOpts{ |
| 287 | + MTU: 1500, |
| 288 | + Endpoint: s.endpoint, |
| 289 | + Async: true, |
| 290 | DefaultLeases: map[string]string{ |
| 291 | networks.SlirpIPAddress: limayaml.MACAddress(inst.Dir), |
| 292 | }, |
| 293 | Subnet: networks.SlirpNetwork, |
| 294 | - }) |
| 295 | - if err != nil { |
| 296 | - stop() |
| 297 | - return nil, "", nil, err |
| 298 | } |
| 299 | - subnetIP, _, err := net.ParseCIDR(networks.SlirpNetwork) |
| 300 | - if err != nil { |
| 301 | - stop() |
| 302 | - return nil, "", nil, err |
| 303 | + if viaDgram { |
| 304 | + opts.DgramConn = s.dgramConn |
| 305 | + } else { |
| 306 | + opts.QemuSocket = s.qemu |
| 307 | + if s.dgramConn != nil { |
| 308 | + s.dgramConn.Close() |
| 309 | + } |
| 310 | } |
| 311 | - return usernet.NewClient(endpointSock, subnetIP), qemuSock, stop, nil |
| 312 | + ctx, stop = context.WithCancel(ctx) |
| 313 | + err = usernet.StartGVisorNetstack(ctx, opts) |
| 314 | + if err == nil { |
| 315 | + var subnetIP net.IP |
| 316 | + subnetIP, _, err = net.ParseCIDR(networks.SlirpNetwork) |
| 317 | + if err == nil { |
| 318 | + return usernet.NewClient(s.endpoint, subnetIP), stop, nil |
| 319 | + } |
| 320 | + } |
| 321 | + stop() |
| 322 | + if viaDgram { |
| 323 | + s.dgramConn.Close() |
| 324 | + } |
| 325 | + return nil, nil, err |
| 326 | } |
| 327 | |
| 328 | var _ driver.Driver = (*LimaQemuDriver)(nil) |
| 329 | @@ -365,22 +406,40 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) { |
| 330 | SSHAddress: l.Instance.SSHAddress, |
| 331 | VirtioGA: l.virtioPort != "", |
| 332 | } |
| 333 | + // The netstack starts once Cmdline has chosen how QEMU reaches it. |
| 334 | + var socks *usernetSockets |
| 335 | if limayaml.FirstUsernetIndex(l.Instance.Config) == -1 { |
| 336 | - client, sock, stop, err := startUsernet(ctx, l.Instance) |
| 337 | + var err error |
| 338 | + if socks, err = newUsernetSockets(l.Instance); err != nil { |
| 339 | + return nil, err |
| 340 | + } |
| 341 | + qCfg.UsernetQEMUSock, qCfg.UsernetDgram = socks.qemu, socks.qemuDgram |
| 342 | + defer socks.closeQEMUEnd() |
| 343 | + } |
| 344 | + netstackStarted := false |
| 345 | + defer func() { |
| 346 | + if socks != nil && socks.dgramConn != nil && !netstackStarted { |
| 347 | + socks.dgramConn.Close() |
| 348 | + } |
| 349 | + }() |
| 350 | + qExe, qArgs, err := Cmdline(ctx, qCfg) |
| 351 | + if err != nil { |
| 352 | + return nil, err |
| 353 | + } |
| 354 | + if socks != nil { |
| 355 | + viaDgram := slices.ContainsFunc(qArgs, func(a string) bool { return strings.HasPrefix(a, "dgram,id=net0,") }) |
| 356 | + client, stop, err := startUsernet(ctx, l.Instance, socks, viaDgram) |
| 357 | if err != nil { |
| 358 | return nil, err |
| 359 | } |
| 360 | - l.usernetClient, l.usernetStop, qCfg.UsernetQEMUSock = client, stop, sock |
| 361 | + netstackStarted = true |
| 362 | + l.usernetClient, l.usernetStop = client, stop |
| 363 | defer func() { |
| 364 | if l.qCmd == nil { |
| 365 | stop() |
| 366 | } |
| 367 | }() |
| 368 | } |
| 369 | - qExe, qArgs, err := Cmdline(ctx, qCfg) |
| 370 | - if err != nil { |
| 371 | - return nil, err |
| 372 | - } |
| 373 | |
| 374 | var vhostCmds []*exec.Cmd |
| 375 | if *l.Instance.Config.MountType == limatype.VIRTIOFS { |
| 376 | @@ -400,7 +459,7 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) { |
| 377 | } |
| 378 | |
| 379 | var qArgsFinal []string |
| 380 | - applier := &qArgTemplateApplier{} |
| 381 | + applier := &qArgTemplateApplier{dgram: qCfg.UsernetDgram} |
| 382 | for _, unapplied := range qArgs { |
| 383 | applied, err := applier.applyTemplate(unapplied) |
| 384 | if err != nil { |
| 385 | @@ -900,6 +959,8 @@ func (l *LimaQemuDriver) GuestAgentConn(ctx context.Context) (net.Conn, string, |
| 386 | |
| 387 | type qArgTemplateApplier struct { |
| 388 | files []*os.File |
| 389 | + // dgram is the file fd_dgram passes to QEMU. |
| 390 | + dgram *os.File |
| 391 | } |
| 392 | |
| 393 | func (a *qArgTemplateApplier) applyTemplate(qArg string) (string, error) { |
| 394 | @@ -938,6 +999,13 @@ func (a *qArgTemplateApplier) applyTemplate(qArg string) (string, error) { |
| 395 | } |
| 396 | return res |
| 397 | }, |
| 398 | + "fd_dgram": func() (string, error) { |
| 399 | + if a.dgram == nil { |
| 400 | + return "", errors.New("fd_dgram: no datagram socket") |
| 401 | + } |
| 402 | + a.files = append(a.files, a.dgram) |
| 403 | + return strconv.Itoa(len(a.files) + 2), nil |
| 404 | + }, |
| 405 | } |
| 406 | tmpl, err := template.New("").Funcs(funcMap).Parse(qArg) |
| 407 | if err != nil { |
| 408 | |
| 409 | new file mode 100644 |
| 410 | |
| 411 | |
| 412 | |
| 413 | @@ -0,0 +1,82 @@ |
| 414 | +//go:build !windows |
| 415 | + |
| 416 | +// SPDX-FileCopyrightText: Copyright The Lima Authors |
| 417 | +// SPDX-License-Identifier: Apache-2.0 |
| 418 | + |
| 419 | +package usernet |
| 420 | + |
| 421 | +import ( |
| 422 | + "bytes" |
| 423 | + "context" |
| 424 | + "net" |
| 425 | + "os" |
| 426 | + "path/filepath" |
| 427 | + "syscall" |
| 428 | + "testing" |
| 429 | + "time" |
| 430 | + |
| 431 | + "gotest.tools/v3/assert" |
| 432 | +) |
| 433 | + |
| 434 | +// A frame sent as a datagram is served by the netstack, and the answer comes |
| 435 | +// back as one: an ARP request for the gateway gets its reply. |
| 436 | +func TestDgramConn(t *testing.T) { |
| 437 | + dir, err := os.MkdirTemp("", "usernet") |
| 438 | + assert.NilError(t, err) |
| 439 | + t.Cleanup(func() { os.RemoveAll(dir) }) |
| 440 | + |
| 441 | + fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0) |
| 442 | + assert.NilError(t, err) |
| 443 | + serverFile, peerFile := os.NewFile(uintptr(fds[0]), "server"), os.NewFile(uintptr(fds[1]), "peer") |
| 444 | + server, err := net.FileConn(serverFile) |
| 445 | + assert.NilError(t, err) |
| 446 | + peer, err := net.FileConn(peerFile) |
| 447 | + assert.NilError(t, err) |
| 448 | + serverFile.Close() |
| 449 | + peerFile.Close() |
| 450 | + t.Cleanup(func() { peer.Close() }) |
| 451 | + |
| 452 | + ctx, cancel := context.WithCancel(context.Background()) |
| 453 | + t.Cleanup(cancel) |
| 454 | + err = StartGVisorNetstack(ctx, &GVisorNetstackOpts{ |
| 455 | + MTU: 1500, |
| 456 | + Endpoint: filepath.Join(dir, "ep.sock"), |
| 457 | + DgramConn: server, |
| 458 | + Async: true, |
| 459 | + Subnet: "192.168.5.0/24", |
| 460 | + }) |
| 461 | + assert.NilError(t, err) |
| 462 | + |
| 463 | + guestMAC := net.HardwareAddr{0x52, 0x54, 0x00, 0x00, 0x00, 0x01} |
| 464 | + gatewayMAC, err := net.ParseMAC(gatewayMacAddr) |
| 465 | + assert.NilError(t, err) |
| 466 | + arp := bytes.Join([][]byte{ |
| 467 | + {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, guestMAC, {0x08, 0x06}, // Ethernet: broadcast, ARP |
| 468 | + {0x00, 0x01, 0x08, 0x00, 0x06, 0x04, 0x00, 0x01}, // Ethernet, IPv4, request |
| 469 | + guestMAC, {192, 168, 5, 15}, |
| 470 | + make([]byte, 6), {192, 168, 5, 2}, // who has the gateway |
| 471 | + }, nil) |
| 472 | + _, err = peer.Write(arp) |
| 473 | + assert.NilError(t, err) |
| 474 | + |
| 475 | + buf := make([]byte, 2048) |
| 476 | + assert.NilError(t, peer.SetReadDeadline(time.Now().Add(10*time.Second))) |
| 477 | + n, err := peer.Read(buf) |
| 478 | + assert.NilError(t, err) |
| 479 | + reply := buf[:n] |
| 480 | + assert.Assert(t, n >= 42, "frame of %d bytes", n) |
| 481 | + assert.DeepEqual(t, reply[0:6], []byte(guestMAC)) |
| 482 | + assert.DeepEqual(t, reply[6:12], []byte(gatewayMAC)) |
| 483 | + assert.DeepEqual(t, reply[12:14], []byte{0x08, 0x06}) |
| 484 | + assert.DeepEqual(t, reply[20:22], []byte{0x00, 0x02}) // ARP reply |
| 485 | + |
| 486 | + // The connection ends with the netstack's context. |
| 487 | + cancel() |
| 488 | + assert.NilError(t, peer.SetWriteDeadline(time.Now().Add(10*time.Second))) |
| 489 | + _, err = peer.Write(arp) |
| 490 | + for i := 0; err == nil && i < 100; i++ { |
| 491 | + time.Sleep(50 * time.Millisecond) |
| 492 | + _, err = peer.Write(arp) |
| 493 | + } |
| 494 | + assert.ErrorContains(t, err, "") |
| 495 | +} |
| 496 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | @@ -33,6 +33,11 @@ type GVisorNetstackOpts struct { |
| 501 | FdSocket string |
| 502 | Endpoint string |
| 503 | |
| 504 | + // DgramConn is one end of a datagram socketpair, whose other end is |
| 505 | + // QEMU's dgram netdev: one raw Ethernet frame per datagram. The netstack |
| 506 | + // closes it when its context ends. |
| 507 | + DgramConn net.Conn |
| 508 | + |
| 509 | Subnet string |
| 510 | |
| 511 | Async bool |
| 512 | @@ -160,9 +165,29 @@ func run(ctx context.Context, g *errgroup.Group, configuration *types.Configurat |
| 513 | return err |
| 514 | } |
| 515 | } |
| 516 | + if opts.DgramConn != nil { |
| 517 | + serveDgram(ctx, vn, opts.DgramConn) |
| 518 | + } |
| 519 | return nil |
| 520 | } |
| 521 | |
| 522 | +// serveDgram serves the netstack on conn, until ctx ends. Frames are the |
| 523 | +// datagrams: there is no length prefix to lose track of, as with QEMU's |
| 524 | +// socket and stream netdevs. |
| 525 | +func serveDgram(ctx context.Context, vn *virtualnetwork.VirtualNetwork, conn net.Conn) { |
| 526 | + ctx, cancel := context.WithCancel(ctx) |
| 527 | + go func() { |
| 528 | + <-ctx.Done() |
| 529 | + conn.Close() |
| 530 | + }() |
| 531 | + go func() { |
| 532 | + defer cancel() |
| 533 | + if err := vn.AcceptBess(ctx, &UDPFileConn{Conn: conn}); err != nil && ctx.Err() == nil { |
| 534 | + logrus.Error("QEMU datagram connection closed with error: ", err) |
| 535 | + } |
| 536 | + }() |
| 537 | +} |
| 538 | + |
| 539 | func listenQEMU(ctx context.Context, vn *virtualnetwork.VirtualNetwork) error { |
| 540 | var lc net.ListenConfig |
| 541 | listener, err := lc.Listen(ctx, "unix", opts.QemuSocket) |