Fail RunPodSandbox before NRI timeout expires and optimize multi-NIC attachment #370
<span aria-hidden="true">✅</span> Deploy Preview for dranet canceled.
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | b4111d2507b866196b18c8271c6952cacfa5b8ea |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/dranet/deploys/6ac4f3969170c700081324fd |
[APPROVALNOTIFIER] This PR is APPROVED
This pull-request has been approved by: <a href="https://github.com/kubernetes-sigs/dranet/pull/370#" title="Author self-approved">aojea</a>
The full list of commands accepted by this bot can be found here.
The pull request process is described here
<details >
Needs approval from an approver in each of these files:
Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment
</details>
<!-- META={"approvers":[]} -->
/assign @dkennetzoracle @gauravkghildiyal
Allowing to move forward without binding all interfaces when we were told to you so is terrible , it also adds better instrumentation to be able to detect problems and create alerst in case the budget for attaching is close to the limit.
As today if the budget is low the official solution is to configure containerd or crio to increase the per plugin timeout ... we still can find a better solution long term but I do not want us to put into a temporary hack that later will bit us and we no longer can get rid of it ... I have some ideas but we need to work with the runtime and NRI folks
this flakes since it depends on the cdn
WARNING: updating and opening https://dl-cdn.alpinelinux.org/alpine/v3.19/main: temporary error (try again later)
/priority important-soon
Does the first device ever get checked?
Additionnally, a device that runs 200ms more than the average still finishes past the runtime deadline. Based on my simulations (nics in the meta comment) spread between 218-284ms per NIC.
Rec: project with the longest device seen so far instead of average (I have an example with attachBudget in #371 that does this).
rec: pass the budget context into the per-device work down on 221, right?
Should you skip this when attached == total? IE can this fail a sandbox that's already fully attached?
Devices here stay in the pod netns and getting them back depends on the runtime calling NRI StopPodSandbox before it deletes the netns. Crio 1.36 does this, but I think this was the initial problem I hit with crio right? Teardown out of order or error in StopPodSandbox orphaned devices?
I think we should detach what this request attached before returnning would make the fail-closed guarantee independent of the runtime..
I also noticed in testing that this tries to detach every device of the claim, including ones the budget never gets to. In one of my runs, I got 28 link not found errors for devices still on the host. If we keep track of attached devices, this and the rollback I mentioned at the failTimeout funnc get easier.
Setting these as "down" during NodePrepareResources can cause race conditions with our health checks. I'm not sure we will use passthrough though.. @OguzPastirmaci what do you think here?
this brings up any down passthrough host link of the claim. Prepare only takes down links that were up, but doesn't record which ones, so a link an admin had down before prepare gets brought up here. Persisting a "downed by prepare" flag in the DeviceConfig checkpoint and only restoring that would fix it.
description says this runs before but looks like it still runs after re: nri_hooks.go:420
should we make this configurable? Seems like we could make 200ms the default but add an option to increase it?
I think in crio this is called nri_plugin_request_timeout so we could either make it agnostic "runtime NRI plugin request timeout" or mention both?
This is set at nri_hooks.go from time.Until(deadline) when the hook starts, so this would be the time left in the request, not the configured timeout. Maybe rename to something like request_remaining_seconds or say more accurately what it measures in the help text.
nit: these are sequential now right?
nit: unrelated?
Thanks for this, tested it pretty heavily on OKE (k8s 1.36.4, CRI-O 1.36.3,) with passthrough dummy interfaces up to 40 per pod, with up to 1800 addresses each so attach is slow enough to hit the limit.
FailedCreatePodSandbox with the new error, the kubelet retried, and the pod never started with missing devices. CRI-O also called StopPodSandbox before removing the netns on this path, so the devices that had been moved came back.A few things below, the main ones are the budget check (one device can still overrun), the post-loop check throwing away a complete attach, and the side-effects of taking NICs down in PrepareResourceClaims. The description also mentions the ethool reorder that doesn't appear in the diff.
Some additional recs below, but overall small changes requested and solid PR for the work.
This doesn't reach OKE RDMA NICs because we reject passthrough in OKE provider. If we do the same thing in the IPv6 side, we should be safe.
yeah, but speeds up CI , I hate slow CIs, is a separate commit so we can land it here or independnetly
Works for me, I did not know what it was - thanks for sharing!
One side effect of taking the link down here that might bite on retries: when an interface goes down, the kernel flushes its IPv4 routes, and its IPv6 addresses too unless keep_addr_on_down=1. prepareDevice reads addresses and routes from the live host interface every time it runs, and nothing skips devices that were already prepared
So if a claim has devices A and B, A is taken down and saved, and then B fails, the kubelet retries NodePrepareResources. A gets prepared again from its down state, and the saved config ends up without its routes and IPv6 addresses. The pod then starts with A but no routing
Two options:
skip devices that are already saved for this podUID/claim, or
only take links down once every device in the claim has prepared successfully
WDYT?
Related to the comment at L521: this brings the link back up only when SetDeviceConfig fails for this device. If a later device in the same claim fails in prepareResourceClaim, the devices already taken down stay down until the claim is unprepared or a retry succeeds. That leaves the host NIC unusable in the meantime, and it creates the retry problem above
One idea: have prepareDevice return the links it took down, and either bring them all back up in prepareResourceClaim when errorList isn’t empty, or run the link-down in a second pass after every device in the claim has prepared. A second pass would also keep all the state capture ahead of any changes
+1. The option exists now, but as far as I can tell nothing in cmd/ calls WithNRIReplyMargin, so it’s always the 200ms default. A flag like --nri-reply-margin would let operators tune it for slow NICs
+1 on persisting the flag. Minor nit while you’re in here: this calls the plain netlink.LinkSetUp instead of the nlwrap handle used everywhere else, so it skips the dump-interrupted retry handling
Thanks @aojea, this is a really valuable fix: failing closed before the runtime deadline is clearly better than starting a pod without its NICs, and the benchmarks make the reasoning easy to follow. @dkennetzoracle’s comments cover the time-budget side well. I left a couple of notes on what happens when prepare is retried after the link has already been taken down, since that looks like it can quietly lose routes and IPv6 addresses. Happy to help test on CoreWeave hardware once those are sorted
Small thing: a margin of 0 or less silently becomes 200ms, so there’s no way to opt out of the early cutoff. That could be handy for runtimes that don’t set a deadline, or for debugging. Maybe only fall back to the default when the value is unset, or document the behavior on WithNRIReplyMargin?
can you expand on how this health checks are performed?
interesting scenario, but IIRC (I need to verify) you don't go back to the kubelet retries NodePrepareResources , you do the RunPodSandbox and StopPodSandbox dance only
That leaves the host NIC unusable in the meantime,
we implement a clear separation of concerns, the NIC on the host are a host problem, DRANET takes them and move them with the additional configuration, but is responsibility from the host process to ensure they are configured correctly, using systemd or custom process
For the system to be resilient we can not workaround the problem of "the host may not do what is supposed to do", for DRANET the configuration in the host is not a problem and it will be also surprising that if the host depend on that interface that is not already managed
good point, we should not change the behavior now , let me figure out what we were doing before
good call, I was trying to start minimalistic for feedback, but seems the operator feedback is clear here
it is effectively the timeout for the request, and seconds is also wrong, it should be milliseconds, let's try to find a more clear name., remaining does not really represent the metrics ... maybe we should introduce the number of the hook to ... the interescting things here will be the efficiency as "time it takes to execute the request" vs "total time it has allocated to execute", this is the later
the problem is that it does not error and Pod start, this is a bug we can not have, if you don't get the things in the Pod that Pod can not run ... unfortunately is hard to change this in NRI today, but people running in production expect the Pod when is running to be fully operational
we should fix this in https://github.com/containerd/nri/pull/329 , this solution is racy and hacky
/hold
PR needs rebase.
<details>
Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
</details>
I will break this down in pieces now that we have https://github.com/kubernetes-sigs/dranet/pull/401 to solve it natively
/close
aojea
What type of PR is this?
/kind bug
What this PR does / why we need it:
NRI plugins run under a strict per-request timeout enforced by the container runtime (
plugin_request_timeout, 2 seconds by default in containerd). WhenRunPodSandboxexceeds this deadline while attaching multiple network interfaces (such as 8 RDMA NICs ona4-highgpu-8g/a3-megagpu-8gnodes), the NRI adaptation library returnscontext deadline exceeded(errPluginTimedOut), disconnects the NRI plugin, and allows the Pod sandbox to start with only a subset of its requested network devices attached.This PR addresses the problem in two ways:
1. Fail closed before the NRI request deadline expires:
RunPodSandboxinspects the incoming NRI context deadline (ctx.Deadline()), reserves a reply margin (200msby default), and aborts/returns an error before the container runtime's NRI deadline expires if device attachment is about to run out of time (elapsed/completed > remaining). This guarantees containerd receives the error response and tears down the sandbox instead of disconnecting the plugin and starting a broken Pod with missing NICs.2. Optimize 8-NIC
RunPodSandboxlatency to fit comfortably within the 2-second NRI budget:- Brings passthrough host network interfaces
DOWNduringNodePrepareResources(which runs under kubelet's 30s gRPC timeout) after host addresses/routes/neighbors have been read, rather than duringRunPodSandbox(which runs under NRI's 2s timeout). If a prepared claim is unprepared beforeRunPodSandboxever moves the interface,UnprepareResourceClaimsrestores the host interface backUP.- Reuses a single
podNetnsHandle(hostHandle,hostSocket, open podcontainerNsFD, andpodHandle) as well as the attachednsLinkacross all devices and post-attach configuration inRunPodSandbox, avoiding repeated namespace opens, threadsetnstransitions, and netlink socket allocations per device.- Moves
applyEthtoolConfigbeforeLinkSetUpinnsAttachNetdevWithHandleso hardware drivers (mlx5_core) do not execute a second channel teardown/reopen cycle (mlx5e_safe_switch_params) when features or private flags are changed.---
1. Production Evidence (
a4-highgpu-8g, 8 × Mellanox ConnectX-7 NICs)From
networking-dra-driverlogs on ana4-highgpu-8gGKE cluster (kernel 6.12.90+,containerd://2.2.3, 8 × Mellanox ConnectX-7gpu0rdma0..gpu7rdma0per node):PrepareResourceClaim(KubeletNodePrepareResourcesphase)RunPodSandbox(Container Runtime NRI hook phase — 2.0s timeout)Each ConnectX-7 NIC takes
218 ms – 284 msinRunPodSandbox, putting 8 NICs at1.75 s – 1.96 sunder ideal conditions and >2.0 s whenever there is scheduling/lock jitter or additional interface configuration.---
2. Root-Cause Measurements & Benchmarks
A. Software
dummyInterface Microbenchmarks (pkg/driver/attach_bench_test.go)Command:
##### Per-Phase Breakdown (
BenchmarkAttachNetdevPhases, 96-vCPU node)| Benchmark Sub-test | Latency (
ns/op) | Latency (ms) | What it measures || :--- | ---: | ---: | :--- |
|
1_LinkByName_Host|75,765|0.076 ms| NetlinkRTM_GETLINKin host netns ||
2_LinkSetDown_And_Up_Host|207,417|0.207 ms| SoftwaredummylinkDOWN+UP||
3_NetnsMove_IFLA_NET_NS_FD_RoundTrip|100,861,603|100.86 ms|50.00 mshost $\to$ pod +50.33 mspod $\to$ host ||
4_NewHandleAt_And_LinkByName_PodNS|152,290|0.152 ms|setns+ netlink socket +RTM_GETLINKin pod netns ||
5_Sysctl_PodNS|205,670|0.206 ms| Unshare mount ns + mount/proc/sys+ writeaccept_ra||
6_Ethtool_FeaturesSet_PodNS|227,502|0.228 ms|ETHTOOL_MSG_FEATURES_GET+SETin pod netns ||
7_FullAttachConfigureAndDetach_1NIC|95,361,329|95.36 ms|46.33 msattach +0.33 msconfig +48.33 msdetach |##### Sequential vs. Parallel vs. Pre-Downed + Shared Handle (
BenchmarkAttachManyDevices, 1 to 8dummyNICs)| NIC Count | Sequential Total (
ms/nic) | Parallel Goroutines Total (ms/nic) | Pre-Downed + SharedpodNetnsHandle(ms/nic) || :--- | ---: | ---: | ---: |
| 1 NIC |
94.5 ms(94.5 ms/nic) |67.0 ms(67.0 ms/nic) |50.5 ms(50.5 ms/nic) || 2 NICs |
93.5 ms(46.8 ms/nic) |111.0 ms(55.5 ms/nic) |86.0 ms(43.0 ms/nic) || 4 NICs |
215.0 ms(53.8 ms/nic) |239.5 ms(59.9 ms/nic) |226.0 ms(56.5 ms/nic) || 8 NICs |
446.5 ms(55.81 ms/nic) |408.0 ms(51.00 ms/nic) |397.0 ms(49.62 ms/nic) |---
B. Hardware Measurements on
a4-highgpu-8g(8 × Mellanox ConnectX-7 NICs)Measured on an idle
a4-highgpu-8gnode (kernel 6.12.90+,gpu0rdma0..gpu7rdma0, PCIe0000:91:00.0..0000:ce:00.0,mtu 8896,numtxqueues 96,numrxqueues 11):##### 1. Single Mellanox ConnectX-7 NIC (
gpu0rdma0) Phase BreakdownLinkSetDowntakes56–65 msandLinkSetUptakes124–136 mson ConnectX-7:- Each
gpuNrdma0interface has 11 RX queues and 96 TX queues.-
LinkSetDowncallsmlx5e_close_locked(), which issues synchronous PCIe firmware commands (mlx5_cmd_exec) to the ConnectX-7 HCA to tear down all TIRs, RQT, RQs, SQs, and CQs while holdingrtnl_lock().-
LinkSetUpcallsmlx5e_open_locked(), which allocates ring buffers and issues synchronous PCIe firmware commands to create all 11 RX + 96 TX queues, CQs, RQs, SQs, and TIRs while holdingrtnl_lock().- Moving
gpu0rdma0while stillUP(99.8 ms) takes the same time asLinkSetDown(56.5 ms) +Netns move while DOWN(35.8 ms) =92.3 msbecausedev_change_net_namespace()callsdev_close_many()(mlx5e_close_locked()) inside the kernel.- Furthermore, if
applyEthtoolConfigis called afterLinkSetUp(asdranetpreviously did),mlx5_coreexecutesmlx5e_safe_switch_params(), closing (56 ms) and reopening (132 ms) all channels a second time (+188 ms/NIC = +1.5 sfor 8 NICs).##### 2. All 8 Mellanox ConnectX-7 NICs (
gpu0rdma0..gpu7rdma0) Across 3 Scenarios###### Scenario A: Unoptimized DraNet Flow (
1,917 msinRunPodSandbox)###### Scenario B: Pre-Downing Passthrough NICs in
NodePrepareResources(1,444 msinRunPodSandbox)Moving
LinkSetDownto the end ofprepareDeviceinNodePrepareResources(aftergetDHCP,AddrList,getRouteInfo, andNeighListhave already captured the host state) shifts463 ms(8 × ~58 ms) out of the 2-second NRIRunPodSandboxhook into the kubeletNodePrepareResourcesgRPC call:###### Scenario C: Pre-Downing in
NodePrepareResources+ SharedpodNetnsHandleinRunPodSandbox(1,277–1,284 msinRunPodSandbox)Combining pre-downed interfaces with a single shared
podNetnsHandle(hostHandle,hostSocket,containerNs,podHandle) across the 8 NICs inpkg/driver(avoiding 40+LockOSThread+setns+ netlink socket creations and redundantLinkByNamelookups) reducesRunPodSandboxfor 8 ConnectX-7 NICs to1,277–1,284 ms:| Scenario (8 × Mellanox ConnectX-7 on
a4-highgpu-8g) |NodePrepareResources|RunPodSandbox| Margin Before1,800 msBudget (2.0sNRI Timeout) || :--- | ---: | ---: | :--- |
| A. Unoptimized Flow |
69 ms|1,740 – 1,917 ms|-117 ms to +60 ms(Fails budget / times out under jitter) || B.
LinkSetDowninNodePrepareResources|532 ms|1,444 ms|+356 ms(+556 msbefore 2.0s) || C.
LinkSetDowninNodePrepareResources+ SharedpodNetnsHandle|514 – 532 ms|1,277 – 1,284 ms|+516 – 523 ms(+716 – 723 msbefore 2.0s) |Which issue(s) this PR is related to:
Fixes #310
Special notes for your reviewer:
Structured into 3 commits for easy review:
1.
driver: benchmark NIC netns attachment and skip empty route/rule/neighbor netlink calls(66fcdea)- Adds
BenchmarkAttachNetdevPhasesandBenchmarkAttachManyDevicesinpkg/driver/attach_bench_test.go(usinguserns.RunBenchmarkininternal/testutils/userns.go) to measure per-phase netlink/kernel costs and demonstrate whyrtnl_lockserialization prevents parallel goroutine speedups.- Skips opening the pod netns and netlink handles in
applyRoutingConfig,applyRulesConfig, andapplyNeighborConfigwhen the corresponding config slice is empty.2.
driver: fail RunPodSandbox before the NRI request timeout expires(2813ece)- Keeps
RunPodSandboxcompletely synchronous (no background goroutines or OCI hook binary).-
RunPodSandboxderives abudgetCtxfromctx.Deadline()minusdefaultNRIReplyMargin(200ms). Before starting each device (and after each device completes),runPodSandboxchecks whetherbudgetCtxhas expired or whether the remaining budget is smaller than the average time spent per device so far (elapsed / completed > remaining).- If the budget is exceeded,
RunPodSandboxemits aNetworkDeviceAttachTimeoutWarning event on the Pod, incrementsdranet_driver_sandbox_attach_total{result="rejected_timeout"}, and returns an error before containerd's NRI timer expires.3.
driver: set passthrough NICs down in PrepareResourceClaims and reuse pod netlink handle(7c9f172)- Sets passthrough host interfaces
DOWNat the end ofprepareDeviceinNodePrepareResources(after addresses, routes, permanent neighbors, and device snapshots have been captured) so hardware queue teardown (mlx5e_close_locked,~56 ms/NIC) runs under kubelet's 30s gRPC timeout instead of NRI's 2sRunPodSandboxtimeout, and restores the host interface toUPinunprepareResourceClaimif the pod never moved it.- Skips redundant
LinkSetDowncalls innsAttachNetdevWithHandlewhen the host device is alreadyDOWN.- Introduces
podNetnsHandleto reuse a single host netlink handle, host netlink route socket, open pod netns FD, and pod netlink handle (as well as the attachednsLink) across all devices andconfigureNetdevInNSWithHandleinRunPodSandbox.Does this PR introduce a user-facing change?
``
release-noteRunPodSandboxDRANET now fails
before the container runtime's NRI request timeout expires (emitting aNetworkDeviceAttachTimeoutWarning event on the Pod) instead of letting the runtime disconnect the NRI plugin and start a Pod with missing network interfaces. Additionally,PrepareResourceClaimsnow sets passthrough host interfaces down ahead ofRunPodSandboxandRunPodSandboxreuses a single netlink handle across all devices for a Pod, reducing 8-NIC ConnectX-7 attachment time from ~1.92s to ~1.28s. Newdranet_driver_nri_request_timeout_seconds,dranet_driver_device_attach_duration_seconds, anddranet_driver_sandbox_attach_totalPrometheus metrics report NRI timeout and device attachment latencies.
``