Repository navigation
agent: k8s: coordinate kubelet pod list fetching - #7085
Conversation
There was a problem hiding this comment.
Pull request overview
This PR refactors the Kubernetes workload attestor’s kubelet pod-list polling to use a long-lived “pod list fetcher” that coordinates concurrent callers, versions responses, caches successful results, and enforces a minimum interval between kubelet request start times (replacing the prior singleflight+TTL approach). It also extracts kubelet HTTP client construction into a dedicated component and updates related error handling, logging, and tests.
Changes:
- Introduces
podListFetcherto coordinate pod-list fetching (shared inflight requests, versioned cached results, backoff timing, client reload handling). - Extracts kubelet HTTP client creation/verification into
kubeletclient.goand wires the plugin to configure/validate via the fetcher. - Updates attestation retry/error semantics and extends/adjusts unit tests accordingly.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| pkg/agent/plugin/workloadattestor/k8s/podlistfetcher.go | New long-lived fetcher coordinating pod-list fetch/caching/backoff/versioning and kubelet client reloads |
| pkg/agent/plugin/workloadattestor/k8s/podlistfetcher_test.go | New unit tests covering fetcher caching, sharing, timing, cancellation, reload, and parsing behavior |
| pkg/agent/plugin/workloadattestor/k8s/kubeletclient.go | New kubelet client + transport-config comparison to preserve connection pools when possible |
| pkg/agent/plugin/workloadattestor/k8s/k8s.go | Plugin updated to use the fetcher/client, revised retry flow and error codes, validate/configure integration |
| pkg/agent/plugin/workloadattestor/k8s/k8s_test.go | Test updates/additions to match new retry/backoff semantics and validation behavior |
| pkg/agent/plugin/workloadattestor/k8s/k8s_posix.go | Minor logging/spelling cleanup and small simplifications |
| } | ||
|
|
||
| func (f *podListFetcher) handleConfigResult(result podListConfigResult) { | ||
| f.config = new(result.config) |
| if podListErr != nil { | ||
| if ctx.Err() != nil { | ||
| return nil, ctx.Err() | ||
| } | ||
| // Otherwise, we'll log podListErr below, and we may retry. | ||
| } else { | ||
| podListVersion = podListResult.version | ||
| } |
There was a problem hiding this comment.
Should be unlikely to happen, but I've addressed it now.
28118c6 to
5d15fc3
Compare
|
Please hold this PR. The Broker API PR is changing many things in the k8s plugin, this PR should come on top of it. |
|
Hey @c4rlo, the Broker API is merged, pls rebase 🙏 |
|
Rebased, and included a few more small improvements; commit message & PR description updated accordingly. |
| func (f *podListFetcher) registerFetchRequest(afterVersion uint64, resultCh chan<- podListFetchResult) { | ||
| if f.cachedPodList.pods != nil && afterVersion < f.cachedPodList.version && | ||
| f.clock.Now().Before(f.cachedFetchStart.Add(f.config.pollRetryInterval)) { | ||
| resultCh <- podListFetchResult{versionedPodList: f.cachedPodList} | ||
| return | ||
| } | ||
|
|
||
| f.fetchWaiters[resultCh] = struct{}{} | ||
| f.scheduleFetch() | ||
| } |
There was a problem hiding this comment.
Shouldn't happen since Configure() gets called before any Attest() calls afaik, but still good to defend against this, hence addressed in cbf4385.
| for _, podValue := range items { | ||
| uid := string(podValue.Get("metadata", "uid").GetStringBytes()) | ||
| if uid == "" { | ||
| f.log.Warn("Pod has no UID", "pod", podValue) | ||
| continue | ||
| } | ||
| result[uid] = podValue | ||
| } |
There was a problem hiding this comment.
This can't happen because fastjson.Value.Get() and fastjson.Value.GetStringBytes() both have a check for whether they're being called on a nil value:
(Also, this isn't new code, it's just been moved around.)
|
Hey @c4rlo #7094 merged and introduced some conflicts, sorry about that, can you pls rebase again? 🙏 @sorindumitru We should try to review this one soon so @c4rlo doesn't have to keep solving conflicts 🙏 |
|
Rebased again. |
|
Rebased again. |
MarcosDY
left a comment
There was a problem hiding this comment.
Open questions:
- I appreciate that this is quite a lot of new code and complexity. Is it worth the gain, maybe counting only the improvements we could not get with the existing singleflight approach? I think so, as it is a more principled approach with more logical semantics, but it is probably debatable.
The versioned-pod-list core is worth it; it fixes a real bug that singleflight structurally cannot. However, the PR bundles ~10 unrelated improvements (IPv6 JoinHostPort, Validate hardening, gRPC code changes, doc fixes, strconv.Itoa → %d, isValidCGroupPathMatches simplification, the flaky-test fix).
That increment the complexity of reviewing and things we need to verify.
However good work :D
- If we go with this new approach, do we want to change the default value for the poll_retry_interval config setting? Currently it is 500 ms. But its meaning changes with this PR: it used to be the sleep time between retry attempts, with the cache TTL being set to half that value (250 ms); now it is the minimum interval between fetch start times for both new requests and retries, with the cache TTL also being the same. I would be tempted to reduce the default value now, perhaps to 250 ms, but I do not have a strong opinion either.
Yeap, semantic changed, so we need to change the default, 500ms is going to go against your changes.
250ms preserves the current cache freshness, another option is to decouple them: a separate cache TTL from the rate limit would be clearer than overloading one knob, but that's more config surface...
| // can match pod-specific fields like container images and service accounts | ||
| // that aren't present on a PartialObjectMetadata. | ||
| func (p *Plugin) attestByPodReference(ctx context.Context, brokerEntry *k8sBrokerEntry, objRef *broker.KubernetesObjectReference) (*attestReferenceResult, error) { | ||
| config, _, _, err := p.getConfig() |
There was a problem hiding this comment.
get config can return return nil, nil, nil, status.Error(codes.FailedPrecondition, "not configured") thi s internal can cause backcompat since we are expecting another error in that case
can you revert return the returned error instead? (plz verify if there are more cases like this)
There was a problem hiding this comment.
Apologies, this was an unintentional change. Undone.
| clock: pluginClock, | ||
| getenv: os.Getenv, | ||
| } | ||
| p.podListFetcher = newPodListFetcher(pluginClock, p.rootDir) |
There was a problem hiding this comment.
it is not a bug "now" but we are creating fetcher on new, no in configure,
in a possible scenario we allow rootDIr to be configurable, fetcher is not going to get the updated value
There was a problem hiding this comment.
I can't really see a reason why we'd ever want to change rootDir at runtime. Hence I'd prefer to keep this unchanged for simplicity.
| _, notes, err := pluginconf.Build(req, p.buildConfig) | ||
| newConfig, notes, err := pluginconf.Build(req, p.buildConfig) | ||
| if err == nil && !newConfig.DisableKubeletClient { | ||
| err = p.podListFetcher.validate(newConfig.podListFetcherConfig) |
There was a problem hiding this comment.
It looks to me like validate no longer only validates but can performs disk I/O and can mutate fetcher state.
am i right?
so 2 topics here:
- Validate now reads CA/token/cert files from disk. For spire-agent validate run outside a pod,
/var/run/secrets/kubernetes.io/serviceaccount/tokendoes not exist, so a config that is perfectly valid for the runtime environment will report Valid:false. This is a behavior change for the CLI validate path that isn't mentioned in the PR description. Is that intended? - Validate reads f.buildClient — a field owned by the run goroutine per the struct comment. In production nothing else writes it, but it breaks the stated ownership invariant, and the tests do reassign fetcher.buildClient from the test goroutine. May we make validate a free function over podListFetcherConfig + rootDir so it never touches fetcher state.
There was a problem hiding this comment.
To your first point: I had assumed that Plugin.Validate() is something that would only be called on a real running agent, i.e. where it would be expected to have access to all its key material. However, on reflection one could imagine it also getting called in other scenarios. It looks like spire-agent validate does not actually call it, however spire-server validate does and so in future it seems quite possible spire-agent validate may also. And in that context one would probably expect validation to not require the key material to be in the configured locations.
Moreover, it looks like other plugins also don't do this kind of thing.
I've therefore changed it to not attempt to load any key material and only validate the config in the more usual less-thorough way.
| } | ||
|
|
||
| func (p *Plugin) Close() error { | ||
| p.podListFetcher.close() |
There was a problem hiding this comment.
this may panic if we call twice, may we run int inside a sync.Once?
There was a problem hiding this comment.
Done as defence-in-depth.
| } | ||
| // Otherwise, we'll log podListErr below, and we may retry. | ||
| } else { | ||
| podListVersion = podList.version |
There was a problem hiding this comment.
is there a guaranty of that podList is not nil after an error?
when error podList is the zero versionedPodList, so podList.pods is nil and ranging is a no-op.
So it depends on fetchNext always returning the zero value on error.
Worth an explicit continue-style guard or at least a comment, since a future change returning a partial list would silently attest against stale data.
There was a problem hiding this comment.
I've expanded the comment to hopefully clarify it. I wanted to avoid making the loop conditional because that would add another level of indentation there, or cause other code complications.
| case attempt >= config.MaxPollAttempts: | ||
| if podListErr != nil { | ||
| log.Warn("Unable to get pod list; giving up", telemetry.Error, podListErr) | ||
| return nil, status.Error(codes.Unavailable, podListErr.Error()) |
There was a problem hiding this comment.
is this catching context cancelation? (we used to return no selector found in that case)
There was a problem hiding this comment.
Yes: see the error handling just after fetchNext above.
| if ctx.Err() != nil { | ||
| return nil, ctx.Err() | ||
| } | ||
| return nil, status.Errorf(codes.PermissionDenied, "error verifying sigstore image signature for imageID %s: %v", containerStatus.ImageID, err) |
There was a problem hiding this comment.
QQ: why to update the error code? can the change cause a regresion?
There was a problem hiding this comment.
I though it would be a little more correct, but it's probably debatable since the error could signify various different things. I've therefore undone this change to be conservative.
| | `use_anonymous_authentication` | If true, use anonymous authentication for kubelet communication. | | ||
| | `node_name_env` | The environment variable used to obtain the node name for kubelet requests. Defaults to `MY_NODE_NAME`. | | ||
| | `node_name` | The node name used for kubelet requests. Overrides the value obtained from the env var specified by `node_name_env`. | | ||
| | `max_poll_attempts` | The maximum number of kubelet polling attempts while locating the workload container/pod. Defaults to `60`. | |
There was a problem hiding this comment.
Previously max_poll_attempts counted "pod not yet found" polls, and a kubelet error returned immediately. Now kubelet errors consume attempts too.
But the interaction is worth flagging: with the default 60 × 500ms, a kubelet that's down for 30s will now hold an attestation request open for the full 30s instead of failing fast.
That's a behavior change for the "kubelet is genuinely broken" case, and it multiplies across concurrent workloads.
I think we need to mention that behavior or try to catch kubelet unrecoverable errors)
There was a problem hiding this comment.
Yes, that is an intentional change; I feel it makes more sense to keep trying both if the pod isn't in the list, and if we couldn't talk to the kubelet.
In principle it would be nice if we could tell whether a kubelet error was recoverable or not. But I don't think we can:
- Connection failure? Maybe temporary network glitch.
- Authentication failure? Maybe our token expired but it's about to be renewed (via the
ReloadIntervaltimer of due to aConfigure()call). - Internal Server Error? Maybe someone broke Kubernetes but is already close to unbreaking it.
So given we have the retry loop, doesn't it make sense to use it for any such errors, for as long as the client's context isn't cancelled?
I'll admit this is a noteworthy change in behaviour and should perhaps be called out in the release notes...
I don't think the behaviour has changed that much that we completely need new config settings for this. On reflection, perhaps it would be best to leave the default poll interval at 500 ms in order to minimise user-observable changes:
I feel like the first option is the more minimal one and hence preferable. If we want to tune behaviour further, that can wait for another PR. |
Move kubelet pod-list fetching, caching and backoff timing into a long-lived fetcher that versions pod-list responses, instead of using the singleflight package. This now enables us to cache successful kubelet responses until another request is eligible to start, which makes more sense. Previously, they were cached for _half_ the polling interval, which could lead to the following situation (illustrated with the default polling interval of 500 ms): - T = 0 ms: Attestation request 1 makes pod-list request, finds no result, sleeps for 500 ms. - T = 300 ms: Attestation request 2 finds cache expired, makes pod-list request that contains an entry that request 1 was looking for. - T = 500 ms: Only now does request 1 wake up and find the desired entry in the cached pod list. Fixing this with the singleflight approach would not have been easily possible, as it could cause retries to re-use the same cached pod list response as in the previous iteration. The new approach also enforces a minimum interval between kubelet request _start times_ across concurrent attestations. Unlike the previous fixed delay after each request, this allows the next request to start immediately when the previous one took longer than the configured interval. In addition, several other improvements (that could also have been implemented with the old singleflight mechanism): - kubelet requests: do not cancel an inflight request just because its _original_ caller is no longer interested, as other callers may be waiting for it. (With singleflight, this could have been fixed via the Group.DoChan method.) - kubelet requests: retry failed fetches via the same backoff mechanism, rather than immediately returning a failure response. Previously, it was only used when the pod list did not contain the workload. - kubelet requests: when reloading the client (whether through explicit Configure call or periodically via reload_interval), only create a fresh http.Transport object if necessary based on config/certificate changes, ensuring we don't trash its connection pool unnecessarily. - kubelet requests: treat invalid "items" JSON type in reponse as error instead of empty. - kubelet requests: replace "attempt" log value rather than appending a new one with each attempt. - kubelet requests: report kubelet and malformed-response failures as Unavailable instead of Internal. (Failure to find the workload in the pod list after attempts exhausted continues to be DeadlineExceeded.) - kubelet requests: use net.JoinHostPort for endpoints (enables IPv6 support). - kube API server requests: correctly reflect runtime changes to api_server.cache.enabled setting via Configure(). - Validate(): more thorough implementation that checks it can read and parse kubelet certificates, etc. - gRPC return codes: preserve whether caller termination was cancellation or deadline expiry. - gRPC return codes: report failed Sigstore policy verification as PermissionDenied instead of Internal. - tests: fix a flakey (order-dependent) Sigstore selector test failure caused by mutating shared expected selectors. - misc: small code cleanups. - docs: add missing descriptions of max_poll_attempts, poll_retry_interval, reload_interval. - docs: assorted fixes. Signed-off-by: Carlo Teubner <[email protected]>
Signed-off-by: Carlo Teubner <[email protected]>
Signed-off-by: Carlo Teubner <[email protected]>
Signed-off-by: Carlo Teubner <[email protected]>
Signed-off-by: Carlo Teubner <[email protected]>
Signed-off-by: Carlo Teubner <[email protected]>
|
Btw, I've addressed all the comments via additional commits, per contribution guidelines. The original commit is unchanged except for a (conflict-free) rebase against main. |
Move kubelet pod-list fetching, caching and backoff timing into a long-lived fetcher that versions pod-list responses, instead of using the
singleflightpackage.This now enables us to cache successful kubelet responses until another request is eligible to start, which makes more sense. Previously, they were cached for half the polling interval, which could lead to the following situation (illustrated with the default polling interval of 500 ms):
Fixing this with the
singleflightapproach would not have been easily possible, as it could cause retries to re-use the same cached pod list response as in the previous iteration.The new approach also enforces a minimum interval between kubelet request start times across concurrent attestations. Unlike the previous fixed delay after each request, this allows the next request to start immediately when the previous one took longer than the configured interval.
In addition, several other improvements (that could also have been implemented with the old
singleflightmechanism):singleflight, this could have been fixed via theGroup.DoChanmethod.)Configure()call or periodically viareload_interval, only create a freshhttp.Transportobject if necessary based on config or certificate changes, ensuring we do not trash its connection pool unnecessarily.itemsJSON type in the response as an error instead of empty.attemptlog value rather than appending a new one with each attempt.Unavailableinstead ofInternal. (Failure to find the workload in the pod list after attempts are exhausted continues to beDeadlineExceeded.)net.JoinHostPortfor endpoints, enabling IPv6 support.api_server.cache.enabledsetting viaConfigure().Validate(): perform more thorough validation, including checking that kubelet certificates can be read and parsed.PermissionDeniedinstead ofInternal.max_poll_attempts,poll_retry_interval, andreload_interval.Open questions:
singleflightapproach? I think so, as it is a more principled approach with more logical semantics, but it is probably debatable.poll_retry_intervalconfig setting? Currently it is 500 ms. But its meaning changes with this PR: it used to be the sleep time between retry attempts, with the cache TTL being set to half that value (250 ms); now it is the minimum interval between fetch start times for both new requests and retries, with the cache TTL also being the same. I would be tempted to reduce the default value now, perhaps to 250 ms, but I do not have a strong opinion either.