@@ -18,14 +18,21 @@ package currentalert
1818import (
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+
40217func Test_resizePvc (t * testing.T ) {
41218 testClient := fake .NewClientBuilder ().WithScheme (scheme .Scheme ).Build ()
42219
0 commit comments