Skip to content

Commit d10bcf4

Browse files
committed
fix(alerts): restore broker downscale without brokerId
Implement the Cruise Control replica lookup on the concrete scaler. For inferred downscale, choose from desired data brokers with reported counts and keep the original KafkaCluster resource version through the update.
1 parent 7e41e25 commit d10bcf4

3 files changed

Lines changed: 227 additions & 19 deletions

File tree

‎internal/alertmanager/currentalert/process.go‎

Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -322,27 +322,49 @@ func downScale(ctx context.Context, log logr.Logger, labels model.LabelSet, clie
322322
return nil
323323
}
324324

325-
var brokerID string
326325
if broker, ok := labels[v1beta1.BrokerIdLabelKey]; ok {
327-
brokerID = string(broker)
328-
} else {
329-
cruiseControlURL := scale.CruiseControlURLFromKafkaCluster(cr)
330-
cc, err := scale.NewCruiseControlScaler(ctx, cruiseControlURL)
331-
if err != nil {
332-
return errors.WrapIfWithDetails(err, "failed to initialize Cruise Control Scaler",
333-
"cruise control url", cruiseControlURL)
334-
}
335-
brokerID, err = cc.BrokerWithLeastPartitionReplicas(ctx)
336-
if err != nil {
337-
return err
338-
}
326+
return k8sutil.RemoveBrokerFromCr(string(broker), cr.Name, cr.Namespace, client)
339327
}
340328

341-
err = k8sutil.RemoveBrokerFromCr(brokerID, string(labels[v1beta1.KafkaCRLabelKey]), string(labels["namespace"]), client)
329+
cruiseControlURL := scale.CruiseControlURLFromKafkaCluster(cr)
330+
cc, err := scale.NewCruiseControlScaler(ctx, cruiseControlURL)
342331
if err != nil {
343-
return err
332+
return errors.WrapIfWithDetails(err, "failed to initialize Cruise Control Scaler",
333+
"cruise control url", cruiseControlURL)
344334
}
345-
return nil
335+
replicaCounts, err := cc.PartitionReplicasByBroker(ctx)
336+
if err != nil {
337+
return errors.WrapIf(err, "could not retrieve partition replica counts for downscale")
338+
}
339+
340+
selected := -1
341+
var fewestReplicas int32
342+
for i, broker := range cr.Spec.Brokers {
343+
replicas, reported := replicaCounts[strconv.Itoa(int(broker.Id))]
344+
if !reported || (selected >= 0 && replicas >= fewestReplicas) {
345+
continue
346+
}
347+
if cr.Spec.KRaftMode {
348+
config, err := broker.GetBrokerConfig(cr.Spec)
349+
if err != nil {
350+
return errors.WrapIfWithDetails(err, "failed to determine broker role for downscale", "brokerId", broker.Id)
351+
}
352+
if config == nil || !config.IsBrokerNode() {
353+
continue
354+
}
355+
}
356+
selected, fewestReplicas = i, replicas
357+
}
358+
if selected < 0 {
359+
return errors.New("no desired data broker has a reported replica count for downscale")
360+
}
361+
362+
// Retain the original resource version so the update fails if the cluster changed during lookup.
363+
brokerID := cr.Spec.Brokers[selected].Id
364+
cr.Spec.Brokers = slices.DeleteFunc(cr.Spec.Brokers, func(broker v1beta1.Broker) bool {
365+
return broker.Id == brokerID
366+
})
367+
return k8sutil.UpdateCr(cr, client)
346368
}
347369

348370
func upScale(log logr.Logger, labels model.LabelSet, annotations model.LabelSet, client client.Client) error {

‎internal/alertmanager/currentalert/process_test.go‎

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,21 @@ package currentalert
1818
import (
1919
"context"
2020
"fmt"
21+
"net/http"
22+
"net/http/httptest"
23+
"strings"
24+
"sync/atomic"
2125
"testing"
2226

2327
"github.com/go-logr/logr"
2428
"github.com/onsi/gomega"
2529
"github.com/prometheus/common/model"
30+
"github.com/stretchr/testify/require"
2631
corev1 "k8s.io/api/core/v1"
32+
apierrors "k8s.io/apimachinery/pkg/api/errors"
2733
"k8s.io/apimachinery/pkg/api/resource"
2834
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
35+
"k8s.io/apimachinery/pkg/runtime"
2936
"k8s.io/apimachinery/pkg/types"
3037
"k8s.io/client-go/kubernetes/scheme"
3138
"sigs.k8s.io/controller-runtime/pkg/client"
@@ -37,6 +44,176 @@ import (
3744
"sigs.k8s.io/controller-runtime/pkg/client/fake"
3845
)
3946

47+
func TestDownScaleWithoutBrokerID(t *testing.T) {
48+
for _, tc := range []struct {
49+
name string
50+
statusCode int
51+
body string
52+
kraft bool
53+
duplicate bool
54+
wantErr bool
55+
wantBrokers []int32
56+
}{
57+
{
58+
name: "removes only the least replicated broker",
59+
statusCode: http.StatusOK,
60+
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"101":18,"102":9,"303":0},"LeaderCountByBrokerId":{"101":0,"102":3,"303":6}}}`,
61+
wantBrokers: []int32{101, 102},
62+
},
63+
{
64+
name: "removes all spec entries for the selected broker ID",
65+
statusCode: http.StatusOK,
66+
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"101":18,"102":9,"303":0}}}`,
67+
duplicate: true,
68+
wantBrokers: []int32{101, 102},
69+
},
70+
{
71+
name: "ignores stale IDs and brokers with no reported count",
72+
statusCode: http.StatusOK,
73+
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"102":9,"999":0}}}`,
74+
wantBrokers: []int32{101, 303},
75+
},
76+
{
77+
name: "stale-only replica map leaves brokers unchanged",
78+
statusCode: http.StatusOK,
79+
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"999":0}}}`,
80+
wantErr: true,
81+
wantBrokers: []int32{101, 102, 303},
82+
},
83+
{
84+
name: "chooses a combined broker over a controller-only node",
85+
statusCode: http.StatusOK,
86+
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"101":9,"102":18,"303":0}}}`,
87+
kraft: true,
88+
wantBrokers: []int32{102, 303},
89+
},
90+
{
91+
name: "accepts the largest replica count",
92+
statusCode: http.StatusOK,
93+
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"102":2147483647}}}`,
94+
wantBrokers: []int32{101, 303},
95+
},
96+
{
97+
name: "lookup failure leaves brokers unchanged",
98+
statusCode: http.StatusInternalServerError,
99+
body: `{"errorMessage":"cluster state unavailable"}`,
100+
wantErr: true,
101+
wantBrokers: []int32{101, 102, 303},
102+
},
103+
{
104+
name: "empty replica map leaves brokers unchanged",
105+
statusCode: http.StatusOK,
106+
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{}}}`,
107+
wantErr: true,
108+
wantBrokers: []int32{101, 102, 303},
109+
},
110+
{
111+
name: "missing replica map leaves brokers unchanged",
112+
statusCode: http.StatusOK,
113+
body: `{"KafkaBrokerState":{}}`,
114+
wantErr: true,
115+
wantBrokers: []int32{101, 102, 303},
116+
},
117+
} {
118+
t.Run(tc.name, func(t *testing.T) {
119+
var requests atomic.Int32
120+
mux := http.NewServeMux()
121+
mux.HandleFunc("GET /kafkacruisecontrol/kafka_cluster_state", func(w http.ResponseWriter, _ *http.Request) {
122+
requests.Add(1)
123+
w.Header().Set("Content-Type", "application/json")
124+
w.WriteHeader(tc.statusCode)
125+
_, _ = w.Write([]byte(tc.body))
126+
})
127+
server := httptest.NewServer(mux)
128+
defer server.Close()
129+
130+
cluster := newDownScaleTestCluster()
131+
cluster.Spec.CruiseControlConfig.CruiseControlEndpoint = strings.TrimPrefix(server.URL, "http://")
132+
if tc.duplicate {
133+
cluster.Spec.Brokers = append(cluster.Spec.Brokers, v1beta1.Broker{Id: 303})
134+
}
135+
if tc.kraft {
136+
cluster.Spec.KRaftMode = true
137+
cluster.Spec.Brokers[0].BrokerConfig = &v1beta1.BrokerConfig{Roles: []string{v1beta1.BrokerNodeProcessRole, v1beta1.ControllerNodeProcessRole}}
138+
cluster.Spec.Brokers[1].BrokerConfig = &v1beta1.BrokerConfig{Roles: []string{v1beta1.BrokerNodeProcessRole}}
139+
cluster.Spec.BrokerConfigGroups = map[string]v1beta1.BrokerConfig{"controller": {Roles: []string{v1beta1.ControllerNodeProcessRole}}}
140+
cluster.Spec.Brokers[2].BrokerConfigGroup = "controller"
141+
}
142+
kubeClient := newDownScaleTestClient(t, cluster)
143+
144+
err := downScale(context.Background(), logr.Discard(), model.LabelSet{
145+
"namespace": "kafka",
146+
v1beta1.KafkaCRLabelKey: "kafka",
147+
}, kubeClient)
148+
if tc.wantErr {
149+
require.Error(t, err)
150+
} else {
151+
require.NoError(t, err)
152+
}
153+
require.Equal(t, int32(1), requests.Load())
154+
assertDownScaleBrokers(t, kubeClient, tc.wantBrokers)
155+
})
156+
}
157+
}
158+
159+
func TestDownScaleWithoutBrokerIDRejectsConcurrentSpecChange(t *testing.T) {
160+
server := httptest.NewUnstartedServer(nil)
161+
defer server.Close()
162+
cluster := newDownScaleTestCluster()
163+
cluster.Spec.CruiseControlConfig.CruiseControlEndpoint = server.Listener.Addr().String()
164+
kubeClient := newDownScaleTestClient(t, cluster)
165+
server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
166+
latest := &v1beta1.KafkaCluster{}
167+
if err := kubeClient.Get(r.Context(), client.ObjectKeyFromObject(cluster), latest); err != nil {
168+
http.Error(w, err.Error(), http.StatusInternalServerError)
169+
return
170+
}
171+
latest.Spec.Brokers = latest.Spec.Brokers[:2]
172+
if err := kubeClient.Update(r.Context(), latest); err != nil {
173+
http.Error(w, err.Error(), http.StatusInternalServerError)
174+
return
175+
}
176+
w.Header().Set("Content-Type", "application/json")
177+
_, _ = w.Write([]byte(`{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"101":18,"102":9,"303":0}}}`))
178+
})
179+
server.Start()
180+
181+
err := downScale(t.Context(), logr.Discard(), model.LabelSet{
182+
"namespace": "kafka",
183+
v1beta1.KafkaCRLabelKey: "kafka",
184+
}, kubeClient)
185+
require.True(t, apierrors.IsConflict(err), "expected a conflict, got %v", err)
186+
assertDownScaleBrokers(t, kubeClient, []int32{101, 102})
187+
}
188+
189+
func newDownScaleTestCluster() *v1beta1.KafkaCluster {
190+
return &v1beta1.KafkaCluster{
191+
ObjectMeta: v1.ObjectMeta{Name: "kafka", Namespace: "kafka"},
192+
Spec: v1beta1.KafkaClusterSpec{
193+
Brokers: []v1beta1.Broker{{Id: 101}, {Id: 102}, {Id: 303}},
194+
},
195+
}
196+
}
197+
198+
func newDownScaleTestClient(t *testing.T, cluster *v1beta1.KafkaCluster) client.Client {
199+
t.Helper()
200+
testScheme := runtime.NewScheme()
201+
require.NoError(t, v1beta1.AddToScheme(testScheme))
202+
return fake.NewClientBuilder().WithScheme(testScheme).
203+
WithStatusSubresource(&v1beta1.KafkaCluster{}).WithObjects(cluster).Build()
204+
}
205+
206+
func assertDownScaleBrokers(t *testing.T, kubeClient client.Client, want []int32) {
207+
t.Helper()
208+
cluster := &v1beta1.KafkaCluster{}
209+
require.NoError(t, kubeClient.Get(context.Background(), types.NamespacedName{Name: "kafka", Namespace: "kafka"}, cluster))
210+
var ids []int32
211+
for _, broker := range cluster.Spec.Brokers {
212+
ids = append(ids, broker.Id)
213+
}
214+
require.Equal(t, want, ids)
215+
}
216+
40217
func Test_resizePvc(t *testing.T) {
41218
testClient := fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()
42219

‎pkg/scale/scale.go‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,12 @@ func createNewDefaultCruiseControlScaler(ctx context.Context, serverURL string)
102102
}
103103

104104
type cruiseControlScaler struct {
105-
CruiseControlScaler
106-
107105
log logr.Logger
108106
client *client.Client
109107
}
110108

109+
var _ CruiseControlScaler = (*cruiseControlScaler)(nil)
110+
111111
// Status returns a StatusTaskResult describing the internal state of Cruise Control.
112112
func (cc *cruiseControlScaler) Status(ctx context.Context) (StatusTaskResult, error) {
113113
req := api.StateRequestWithDefaults()
@@ -792,7 +792,13 @@ func (cc *cruiseControlScaler) KafkaClusterState(ctx context.Context) (*types.Ka
792792
return clusterStateResp.Result, nil
793793
}
794794

795-
// PartitionLeadersReplicasByBroker returns the number of partition replicas for every broker in the Kafka cluster.
795+
// PartitionReplicasByBroker returns the number of partition replicas for every broker in the Kafka cluster.
796+
func (cc *cruiseControlScaler) PartitionReplicasByBroker(ctx context.Context) (map[string]int32, error) {
797+
replicas, _, err := cc.PartitionLeadersReplicasByBroker(ctx)
798+
return replicas, err
799+
}
800+
801+
// PartitionLeadersReplicasByBroker returns the partition replica and leader counts for every broker in the Kafka cluster.
796802
func (cc *cruiseControlScaler) PartitionLeadersReplicasByBroker(ctx context.Context) (brokerIDReplicaCounts map[string]int32, brokerIDLeaderCounts map[string]int32, err error) {
797803
clusterStateReq := api.KafkaClusterStateRequestWithDefaults()
798804
clusterStateResp, err := cc.client.KafkaClusterState(ctx, clusterStateReq)
@@ -811,6 +817,9 @@ func (cc *cruiseControlScaler) BrokerWithLeastPartitionReplicas(ctx context.Cont
811817
cc.log.Error(err, "could not retrieve partition map for brokers")
812818
return brokerWithLeastPartitionReplicas, err
813819
}
820+
if len(brokerPartitions) == 0 {
821+
return "", errors.New("no broker replica counts available for downscale selection")
822+
}
814823

815824
replicaCount := int32(math.MaxInt32)
816825
for brokerID, replica := range brokerPartitions {

0 commit comments

Comments
 (0)