Skip to content

Commit 5b542a9

Browse files
Copilotrbtr
andcommitted
Implement server-side Pod filtering with indexer for status.phase
Co-authored-by: rbtr <[email protected]>
1 parent 12d2834 commit 5b542a9

File tree

5 files changed

+138
-3
lines changed

5 files changed

+138
-3
lines changed

cns/ipampool/v2/adapter.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,12 @@ func PodIPDemandListener(ch chan<- int) func([]v1.Pod) {
4242
ch <- activePods
4343
}
4444
}
45+
46+
// PodIPDemandListenerNoFilter counts all pods without client-side filtering.
47+
// This is used when server-side filtering has already excluded terminal pods.
48+
func PodIPDemandListenerNoFilter(ch chan<- int) func([]v1.Pod) {
49+
return func(pods []v1.Pod) {
50+
// All pods are already filtered server-side to exclude terminal phases
51+
ch <- len(pods)
52+
}
53+
}

cns/ipampool/v2/adapter_test.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,3 +98,63 @@ func TestPodIPDemandListener(t *testing.T) {
9898
})
9999
}
100100
}
101+
102+
func TestPodIPDemandListenerNoFilter(t *testing.T) {
103+
tests := []struct {
104+
name string
105+
pods []v1.Pod
106+
expected int
107+
}{
108+
{
109+
name: "empty pod list",
110+
pods: []v1.Pod{},
111+
expected: 0,
112+
},
113+
{
114+
name: "single pod",
115+
pods: []v1.Pod{
116+
{
117+
ObjectMeta: metav1.ObjectMeta{Name: "pod1"},
118+
Status: v1.PodStatus{Phase: v1.PodRunning},
119+
},
120+
},
121+
expected: 1,
122+
},
123+
{
124+
name: "multiple pods - counts all since filtering is done server-side",
125+
pods: []v1.Pod{
126+
{
127+
ObjectMeta: metav1.ObjectMeta{Name: "pod1"},
128+
Status: v1.PodStatus{Phase: v1.PodRunning},
129+
},
130+
{
131+
ObjectMeta: metav1.ObjectMeta{Name: "pod2"},
132+
Status: v1.PodStatus{Phase: v1.PodPending},
133+
},
134+
{
135+
ObjectMeta: metav1.ObjectMeta{Name: "pod3"},
136+
Status: v1.PodStatus{Phase: v1.PodUnknown},
137+
},
138+
},
139+
expected: 3, // All pods counted since server-side filtering already excluded terminal pods
140+
},
141+
}
142+
143+
for _, tt := range tests {
144+
t.Run(tt.name, func(t *testing.T) {
145+
ch := make(chan int, 1)
146+
listener := PodIPDemandListenerNoFilter(ch)
147+
148+
listener(tt.pods)
149+
150+
select {
151+
case result := <-ch:
152+
if result != tt.expected {
153+
t.Errorf("expected %d, got %d", tt.expected, result)
154+
}
155+
default:
156+
t.Error("expected value in channel")
157+
}
158+
})
159+
}
160+
}

cns/kubecontroller/pod/reconciler.go

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"github.com/pkg/errors"
88
"go.uber.org/zap"
99
v1 "k8s.io/api/core/v1"
10+
"k8s.io/apimachinery/pkg/fields"
1011
ctrl "sigs.k8s.io/controller-runtime"
1112
"sigs.k8s.io/controller-runtime/pkg/client"
1213
"sigs.k8s.io/controller-runtime/pkg/event"
@@ -50,7 +51,7 @@ type limiter interface {
5051
Allow() bool
5152
}
5253

53-
// NotifierFunc returns a reconcile.Func that lists Pods to get the latest
54+
// NewNotifierFunc returns a reconcile.Func that lists Pods to get the latest
5455
// state and notifies listeners of the resulting Pods.
5556
// listOpts are passed to the client.List call to filter the Pod list.
5657
// limiter is an optional rate limiter which may be used to limit the
@@ -80,6 +81,54 @@ func (p *watcher) NewNotifierFunc(listOpts *client.ListOptions, limiter limiter,
8081
}
8182
}
8283

84+
// NewPodIPDemandNotifierFunc returns a reconcile.Func optimized for IP demand calculation
85+
// that uses server-side filtering to exclude terminal Pods (Succeeded/Failed) from the results.
86+
// This avoids client-side iteration over all pods by using multiple targeted queries.
87+
func (p *watcher) NewPodIPDemandNotifierFunc(baseListOpts *client.ListOptions, limiter limiter, listeners ...func([]v1.Pod)) reconcile.Func {
88+
p.z.Info("adding pod IP demand notifier for listeners", zap.Int("listeners", len(listeners)))
89+
return func(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
90+
if !limiter.Allow() {
91+
// rate limit exceeded, requeue
92+
p.z.Info("rate limit exceeded")
93+
return ctrl.Result{Requeue: true}, nil
94+
}
95+
96+
// Create field selectors for active pod phases (exclude Succeeded and Failed)
97+
activePhases := []v1.PodPhase{v1.PodRunning, v1.PodPending, v1.PodUnknown}
98+
var allActivePods []v1.Pod
99+
100+
for _, phase := range activePhases {
101+
// Clone base list options and add phase filter
102+
listOpts := &client.ListOptions{}
103+
if baseListOpts.FieldSelector != nil {
104+
// Combine existing field selector with phase filter
105+
phaseSelector := fields.SelectorFromSet(fields.Set{"status.phase": string(phase)})
106+
combinedSelector := fields.AndSelectors(baseListOpts.FieldSelector, phaseSelector)
107+
listOpts.FieldSelector = combinedSelector
108+
} else {
109+
listOpts.FieldSelector = fields.SelectorFromSet(fields.Set{"status.phase": string(phase)})
110+
}
111+
112+
// Copy other options from base
113+
listOpts.LabelSelector = baseListOpts.LabelSelector
114+
listOpts.Namespace = baseListOpts.Namespace
115+
listOpts.Limit = baseListOpts.Limit
116+
listOpts.Continue = baseListOpts.Continue
117+
118+
podList := &v1.PodList{}
119+
if err := p.cli.List(ctx, podList, listOpts); err != nil {
120+
return ctrl.Result{}, errors.Wrapf(err, "failed to list pods with phase %s", phase)
121+
}
122+
allActivePods = append(allActivePods, podList.Items...)
123+
}
124+
125+
for _, l := range listeners {
126+
l(allActivePods)
127+
}
128+
return ctrl.Result{}, nil
129+
}
130+
}
131+
83132
var hostNetworkIndexer = client.IndexerFunc(func(o client.Object) []string {
84133
pod, ok := o.(*v1.Pod)
85134
if !ok {
@@ -88,12 +137,23 @@ var hostNetworkIndexer = client.IndexerFunc(func(o client.Object) []string {
88137
return []string{strconv.FormatBool(pod.Spec.HostNetwork)}
89138
})
90139

140+
var statusPhaseIndexer = client.IndexerFunc(func(o client.Object) []string {
141+
pod, ok := o.(*v1.Pod)
142+
if !ok {
143+
return nil
144+
}
145+
return []string{string(pod.Status.Phase)}
146+
})
147+
91148
// SetupWithManager Sets up the reconciler with a new manager, filtering using NodeNetworkConfigFilter on nodeName.
92149
func (p *watcher) SetupWithManager(ctx context.Context, mgr ctrl.Manager) error {
93150
p.cli = mgr.GetClient()
94151
if err := mgr.GetFieldIndexer().IndexField(ctx, &v1.Pod{}, "spec.hostNetwork", hostNetworkIndexer); err != nil {
95152
return errors.Wrap(err, "failed to set up hostNetwork indexer")
96153
}
154+
if err := mgr.GetFieldIndexer().IndexField(ctx, &v1.Pod{}, "status.phase", statusPhaseIndexer); err != nil {
155+
return errors.Wrap(err, "failed to set up status.phase indexer")
156+
}
97157
if err := ctrl.NewControllerManagedBy(mgr).
98158
For(&v1.Pod{}).
99159
WithEventFilter(predicate.Funcs{ // we only want create/delete events

cns/service/main.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1576,10 +1576,16 @@ func InitializeCRDState(ctx context.Context, httpRestService cns.HTTPService, cn
15761576
if cnsconfig.WatchPods {
15771577
pw := podctrl.New(z)
15781578
if cnsconfig.EnableIPAMv2 {
1579-
hostNetworkListOpt := &client.ListOptions{FieldSelector: fields.SelectorFromSet(fields.Set{"spec.hostNetwork": "false"})} // filter only podsubnet pods
1579+
// Create field selector to filter only podsubnet pods
1580+
fieldSet := fields.Set{
1581+
"spec.hostNetwork": "false",
1582+
}
1583+
hostNetworkSelector := fields.SelectorFromSet(fieldSet)
1584+
baseListOpts := &client.ListOptions{FieldSelector: hostNetworkSelector}
15801585
// don't relist pods more than every 500ms
15811586
limit := rate.NewLimiter(rate.Every(500*time.Millisecond), 1) //nolint:gomnd // clearly 500ms
1582-
pw.With(pw.NewNotifierFunc(hostNetworkListOpt, limit, ipampoolv2.PodIPDemandListener(ipDemandCh)))
1587+
// Use specialized notifier that filters terminal pods server-side
1588+
pw.With(pw.NewPodIPDemandNotifierFunc(baseListOpts, limit, ipampoolv2.PodIPDemandListenerNoFilter(ipDemandCh)))
15831589
}
15841590
if err := pw.SetupWithManager(ctx, manager); err != nil {
15851591
return errors.Wrapf(err, "failed to setup pod watcher with manager")

service

65.2 MB
Binary file not shown.

0 commit comments

Comments
 (0)