Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 38 additions & 16 deletions internal/alertmanager/currentalert/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,27 +322,49 @@ func downScale(ctx context.Context, log logr.Logger, labels model.LabelSet, clie
return nil
}

var brokerID string
if broker, ok := labels[v1beta1.BrokerIdLabelKey]; ok {
brokerID = string(broker)
} else {
cruiseControlURL := scale.CruiseControlURLFromKafkaCluster(cr)
cc, err := scale.NewCruiseControlScaler(ctx, cruiseControlURL)
if err != nil {
return errors.WrapIfWithDetails(err, "failed to initialize Cruise Control Scaler",
"cruise control url", cruiseControlURL)
}
brokerID, err = cc.BrokerWithLeastPartitionReplicas(ctx)
if err != nil {
return err
}
return k8sutil.RemoveBrokerFromCr(string(broker), cr.Name, cr.Namespace, client)
}

err = k8sutil.RemoveBrokerFromCr(brokerID, string(labels[v1beta1.KafkaCRLabelKey]), string(labels["namespace"]), client)
cruiseControlURL := scale.CruiseControlURLFromKafkaCluster(cr)
cc, err := scale.NewCruiseControlScaler(ctx, cruiseControlURL)
if err != nil {
return err
return errors.WrapIfWithDetails(err, "failed to initialize Cruise Control Scaler",
"cruise control url", cruiseControlURL)
}
return nil
replicaCounts, err := cc.PartitionReplicasByBroker(ctx)
if err != nil {
return errors.WrapIf(err, "could not retrieve partition replica counts for downscale")
}

selected := -1
var fewestReplicas int32
for i, broker := range cr.Spec.Brokers {
replicas, reported := replicaCounts[strconv.Itoa(int(broker.Id))]
if !reported || (selected >= 0 && replicas >= fewestReplicas) {
continue
}
if cr.Spec.KRaftMode {
config, err := broker.GetBrokerConfig(cr.Spec)
if err != nil {
return errors.WrapIfWithDetails(err, "failed to determine broker role for downscale", "brokerId", broker.Id)
}
if config == nil || !config.IsBrokerNode() {
continue
}
}
selected, fewestReplicas = i, replicas
}
if selected < 0 {
return errors.New("no desired data broker has a reported replica count for downscale")
}

// Retain the original resource version so the update fails if the cluster changed during lookup.
brokerID := cr.Spec.Brokers[selected].Id
cr.Spec.Brokers = slices.DeleteFunc(cr.Spec.Brokers, func(broker v1beta1.Broker) bool {
return broker.Id == brokerID
})
return k8sutil.UpdateCr(cr, client)
}

func upScale(log logr.Logger, labels model.LabelSet, annotations model.LabelSet, client client.Client) error {
Expand Down
177 changes: 177 additions & 0 deletions internal/alertmanager/currentalert/process_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,21 @@ package currentalert
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"

"github.com/go-logr/logr"
"github.com/onsi/gomega"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"
Expand All @@ -37,6 +44,176 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)

func TestDownScaleWithoutBrokerID(t *testing.T) {
for _, tc := range []struct {
name string
statusCode int
body string
kraft bool
duplicate bool
wantErr bool
wantBrokers []int32
}{
{
name: "removes only the least replicated broker",
statusCode: http.StatusOK,
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"101":18,"102":9,"303":0},"LeaderCountByBrokerId":{"101":0,"102":3,"303":6}}}`,
wantBrokers: []int32{101, 102},
},
{
name: "removes all spec entries for the selected broker ID",
statusCode: http.StatusOK,
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"101":18,"102":9,"303":0}}}`,
duplicate: true,
wantBrokers: []int32{101, 102},
},
{
name: "ignores stale IDs and brokers with no reported count",
statusCode: http.StatusOK,
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"102":9,"999":0}}}`,
wantBrokers: []int32{101, 303},
},
{
name: "stale-only replica map leaves brokers unchanged",
statusCode: http.StatusOK,
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"999":0}}}`,
wantErr: true,
wantBrokers: []int32{101, 102, 303},
},
{
name: "chooses a combined broker over a controller-only node",
statusCode: http.StatusOK,
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"101":9,"102":18,"303":0}}}`,
kraft: true,
wantBrokers: []int32{102, 303},
},
{
name: "accepts the largest replica count",
statusCode: http.StatusOK,
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"102":2147483647}}}`,
wantBrokers: []int32{101, 303},
},
{
name: "lookup failure leaves brokers unchanged",
statusCode: http.StatusInternalServerError,
body: `{"errorMessage":"cluster state unavailable"}`,
wantErr: true,
wantBrokers: []int32{101, 102, 303},
},
{
name: "empty replica map leaves brokers unchanged",
statusCode: http.StatusOK,
body: `{"KafkaBrokerState":{"ReplicaCountByBrokerId":{}}}`,
wantErr: true,
wantBrokers: []int32{101, 102, 303},
},
{
name: "missing replica map leaves brokers unchanged",
statusCode: http.StatusOK,
body: `{"KafkaBrokerState":{}}`,
wantErr: true,
wantBrokers: []int32{101, 102, 303},
},
} {
t.Run(tc.name, func(t *testing.T) {
var requests atomic.Int32
mux := http.NewServeMux()
mux.HandleFunc("GET /kafkacruisecontrol/kafka_cluster_state", func(w http.ResponseWriter, _ *http.Request) {
requests.Add(1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(tc.statusCode)
_, _ = w.Write([]byte(tc.body))
})
server := httptest.NewServer(mux)
defer server.Close()

cluster := newDownScaleTestCluster()
cluster.Spec.CruiseControlConfig.CruiseControlEndpoint = strings.TrimPrefix(server.URL, "http://")
if tc.duplicate {
cluster.Spec.Brokers = append(cluster.Spec.Brokers, v1beta1.Broker{Id: 303})
}
if tc.kraft {
cluster.Spec.KRaftMode = true
cluster.Spec.Brokers[0].BrokerConfig = &v1beta1.BrokerConfig{Roles: []string{v1beta1.BrokerNodeProcessRole, v1beta1.ControllerNodeProcessRole}}
cluster.Spec.Brokers[1].BrokerConfig = &v1beta1.BrokerConfig{Roles: []string{v1beta1.BrokerNodeProcessRole}}
cluster.Spec.BrokerConfigGroups = map[string]v1beta1.BrokerConfig{"controller": {Roles: []string{v1beta1.ControllerNodeProcessRole}}}
cluster.Spec.Brokers[2].BrokerConfigGroup = "controller"
}
kubeClient := newDownScaleTestClient(t, cluster)

err := downScale(context.Background(), logr.Discard(), model.LabelSet{
"namespace": "kafka",
v1beta1.KafkaCRLabelKey: "kafka",
}, kubeClient)
if tc.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
}
require.Equal(t, int32(1), requests.Load())
assertDownScaleBrokers(t, kubeClient, tc.wantBrokers)
})
}
}

func TestDownScaleWithoutBrokerIDRejectsConcurrentSpecChange(t *testing.T) {
server := httptest.NewUnstartedServer(nil)
defer server.Close()
cluster := newDownScaleTestCluster()
cluster.Spec.CruiseControlConfig.CruiseControlEndpoint = server.Listener.Addr().String()
kubeClient := newDownScaleTestClient(t, cluster)
server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
latest := &v1beta1.KafkaCluster{}
if err := kubeClient.Get(r.Context(), client.ObjectKeyFromObject(cluster), latest); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
latest.Spec.Brokers = latest.Spec.Brokers[:2]
if err := kubeClient.Update(r.Context(), latest); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"KafkaBrokerState":{"ReplicaCountByBrokerId":{"101":18,"102":9,"303":0}}}`))
})
server.Start()

err := downScale(t.Context(), logr.Discard(), model.LabelSet{
"namespace": "kafka",
v1beta1.KafkaCRLabelKey: "kafka",
}, kubeClient)
require.True(t, apierrors.IsConflict(err), "expected a conflict, got %v", err)
assertDownScaleBrokers(t, kubeClient, []int32{101, 102})
}

func newDownScaleTestCluster() *v1beta1.KafkaCluster {
return &v1beta1.KafkaCluster{
ObjectMeta: v1.ObjectMeta{Name: "kafka", Namespace: "kafka"},
Spec: v1beta1.KafkaClusterSpec{
Brokers: []v1beta1.Broker{{Id: 101}, {Id: 102}, {Id: 303}},
},
}
}

func newDownScaleTestClient(t *testing.T, cluster *v1beta1.KafkaCluster) client.Client {
t.Helper()
testScheme := runtime.NewScheme()
require.NoError(t, v1beta1.AddToScheme(testScheme))
return fake.NewClientBuilder().WithScheme(testScheme).
WithStatusSubresource(&v1beta1.KafkaCluster{}).WithObjects(cluster).Build()
}

func assertDownScaleBrokers(t *testing.T, kubeClient client.Client, want []int32) {
t.Helper()
cluster := &v1beta1.KafkaCluster{}
require.NoError(t, kubeClient.Get(context.Background(), types.NamespacedName{Name: "kafka", Namespace: "kafka"}, cluster))
var ids []int32
for _, broker := range cluster.Spec.Brokers {
ids = append(ids, broker.Id)
}
require.Equal(t, want, ids)
}

func Test_resizePvc(t *testing.T) {
testClient := fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()

Expand Down
122 changes: 122 additions & 0 deletions internal/alertmanager/receiver/http_handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
// Copyright 2026 Adobe. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package receiver

import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/go-logr/logr"
"github.com/prometheus/common/model"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client/fake"

"github.com/banzaicloud/koperator/api/v1beta1"
"github.com/banzaicloud/koperator/internal/alertmanager/currentalert"
)

func TestHTTPReceiverPayloads(t *testing.T) {
for _, tc := range []struct {
name string
envelope bool
invalid string
wantStatus int
}{
{name: "Prometheus array", wantStatus: http.StatusAccepted},
{name: "Alertmanager webhook", envelope: true, wantStatus: http.StatusAccepted},
{name: "malformed JSON", invalid: "{", wantStatus: http.StatusBadRequest},
{name: "missing webhook alerts", invalid: `{"receiver":"actions"}`, wantStatus: http.StatusBadRequest},
{name: "invalid webhook alerts", invalid: `{"alerts":{}}`, wantStatus: http.StatusBadRequest},
} {
t.Run(tc.name, func(t *testing.T) {
scheme := runtime.NewScheme()
require.NoError(t, v1beta1.AddToScheme(scheme))
cluster := &v1beta1.KafkaCluster{
ObjectMeta: metav1.ObjectMeta{Name: "kafka", Namespace: "kafka"},
Spec: v1beta1.KafkaClusterSpec{
Brokers: []v1beta1.Broker{{Id: 100}, {Id: 101}, {Id: 102}, {Id: 103}},
},
Status: v1beta1.KafkaClusterStatus{State: v1beta1.KafkaClusterRunning},
}
kubeClient := fake.NewClientBuilder().WithScheme(scheme).
WithStatusSubresource(cluster).WithObjects(cluster).Build()
labels := model.LabelSet{
"alertname": model.LabelValue(tc.name), "namespace": "kafka",
"kafka_cr": "kafka", "brokerId": "103",
}
t.Cleanup(func() {
require.NoError(t, currentalert.GetCurrentAlerts().DeleteAlert(labels.Fingerprint()))
})
now := time.Now()
alerts := []model.Alert{{
Labels: labels,
Annotations: model.LabelSet{"command": "downScale"},
StartsAt: now.Add(-time.Hour),
EndsAt: now.Add(time.Hour),
}}
var payload interface{} = alerts
if tc.envelope {
payload = map[string]interface{}{
"version": "4", "receiver": "actions", "status": "firing", "alerts": alerts,
}
}
body, err := json.Marshal(payload)
require.NoError(t, err)
if tc.invalid != "" {
body = []byte(tc.invalid)
}
request := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(body))
response := httptest.NewRecorder()
NewHTTPHandler(logr.Discard(), kubeClient).ServeHTTP(response, request)
require.Equal(t, tc.wantStatus, response.Code, response.Body.String())

actual := &v1beta1.KafkaCluster{}
require.NoError(t, kubeClient.Get(context.Background(),
types.NamespacedName{Name: "kafka", Namespace: "kafka"}, actual))
want := []int32{100, 101, 102, 103}
if tc.wantStatus == http.StatusAccepted {
want = []int32{100, 101, 102}
}
var ids []int32
for _, broker := range actual.Spec.Brokers {
ids = append(ids, broker.Id)
}
require.Equal(t, want, ids)
if tc.wantStatus == http.StatusAccepted {
require.Contains(t, currentalert.GetCurrentAlerts().ListAlerts(), labels.Fingerprint())
alerts[0].EndsAt = now.Add(-time.Minute)
var resolved interface{} = alerts
if tc.envelope {
resolved = map[string]interface{}{"status": "resolved", "alerts": alerts}
}
body, err := json.Marshal(resolved)
require.NoError(t, err)
response = httptest.NewRecorder()
NewHTTPHandler(logr.Discard(), kubeClient).ServeHTTP(response,
httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(body)))
require.Equal(t, http.StatusAccepted, response.Code)
require.NotContains(t, currentalert.GetCurrentAlerts().ListAlerts(), labels.Fingerprint())
}
})
}
}
Loading