| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"flag" |
| 6 |
"fmt" |
| 7 |
"log" |
| 8 |
"os" |
| 9 |
"os/signal" |
| 10 |
"slices" |
| 11 |
"strings" |
| 12 |
"syscall" |
| 13 |
"time" |
| 14 |
|
| 15 |
"github.com/IBM/sarama" |
| 16 |
) |
| 17 |
|
| 18 |
var ( |
| 19 |
brokers = "" |
| 20 |
topic = "" |
| 21 |
replicationFactor = 0 |
| 22 |
version = "" |
| 23 |
pollInterval = 2 * time.Second |
| 24 |
pollTimeout = 2 * time.Minute |
| 25 |
verbose = false |
| 26 |
) |
| 27 |
|
| 28 |
func init() { |
| 29 |
flag.StringVar(&brokers, "brokers", "", "Kafka bootstrap brokers to connect to, as a comma separated list") |
| 30 |
flag.StringVar(&topic, "topic", "", "Topic whose partitions should be reassigned") |
| 31 |
flag.IntVar(&replicationFactor, "replication-factor", 0, "Target replication factor for every partition") |
| 32 |
flag.StringVar(&version, "version", sarama.DefaultVersion.String(), "Kafka cluster version (must be 2.4 or newer)") |
| 33 |
flag.DurationVar(&pollInterval, "poll-interval", 2*time.Second, "Interval between ListPartitionReassignments polls") |
| 34 |
flag.DurationVar(&pollTimeout, "poll-timeout", 2*time.Minute, "Maximum time to wait for an in-progress reassignment to complete") |
| 35 |
flag.BoolVar(&verbose, "verbose", false, "Enable sarama logging") |
| 36 |
flag.Parse() |
| 37 |
|
| 38 |
if len(brokers) == 0 { |
| 39 |
panic("no Kafka bootstrap brokers defined, please set the -brokers flag") |
| 40 |
} |
| 41 |
if len(topic) == 0 { |
| 42 |
panic("no topic given, please set the -topic flag") |
| 43 |
} |
| 44 |
if replicationFactor <= 0 { |
| 45 |
panic("invalid -replication-factor, must be > 0") |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
func main() { |
| 50 |
if verbose { |
| 51 |
sarama.Logger = log.New(os.Stdout, "[sarama] ", log.LstdFlags) |
| 52 |
} |
| 53 |
|
| 54 |
kafkaVersion, err := sarama.ParseKafkaVersion(version) |
| 55 |
if err != nil { |
| 56 |
log.Fatalf("parse kafka version: %v", err) |
| 57 |
} |
| 58 |
|
| 59 |
config := sarama.NewConfig() |
| 60 |
config.Version = kafkaVersion |
| 61 |
config.ClientID = "sarama-alter-partition-reassignments" |
| 62 |
|
| 63 |
admin, err := sarama.NewClusterAdmin(strings.Split(brokers, ","), config) |
| 64 |
if err != nil { |
| 65 |
log.Fatalf("create cluster admin: %v", err) |
| 66 |
} |
| 67 |
defer func() { |
| 68 |
if err := admin.Close(); err != nil { |
| 69 |
log.Printf("close cluster admin: %v", err) |
| 70 |
} |
| 71 |
}() |
| 72 |
|
| 73 |
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) |
| 74 |
defer cancel() |
| 75 |
|
| 76 |
current, err := describeTopic(admin, topic) |
| 77 |
if err != nil { |
| 78 |
log.Fatalf("describe topic %q: %v", topic, err) |
| 79 |
} |
| 80 |
log.Printf("current assignment for %q: %s", topic, formatAssignment(current)) |
| 81 |
|
| 82 |
clusterBrokers, _, err := admin.DescribeCluster() |
| 83 |
if err != nil { |
| 84 |
log.Fatalf("describe cluster: %v", err) |
| 85 |
} |
| 86 |
if len(clusterBrokers) < replicationFactor { |
| 87 |
log.Fatalf("cluster has %d brokers, cannot satisfy replication factor %d", len(clusterBrokers), replicationFactor) |
| 88 |
} |
| 89 |
brokerIDs := make([]int32, 0, len(clusterBrokers)) |
| 90 |
for _, b := range clusterBrokers { |
| 91 |
brokerIDs = append(brokerIDs, b.ID()) |
| 92 |
} |
| 93 |
slices.Sort(brokerIDs) |
| 94 |
|
| 95 |
target, changed := buildTargetAssignment(current, brokerIDs, replicationFactor) |
| 96 |
if !changed { |
| 97 |
log.Printf("topic %q is already at replication factor %d, nothing to do", topic, replicationFactor) |
| 98 |
return |
| 99 |
} |
| 100 |
log.Printf("target assignment for %q: %s", topic, formatAssignment(target)) |
| 101 |
|
| 102 |
if err := admin.AlterPartitionReassignments(topic, target); err != nil { |
| 103 |
log.Fatalf("alter partition reassignments: %v", err) |
| 104 |
} |
| 105 |
log.Printf("submitted reassignment for %q, waiting for it to complete (timeout %s)", topic, pollTimeout) |
| 106 |
|
| 107 |
if err := waitForReassignment(ctx, admin, topic, partitionIDs(target), pollInterval, pollTimeout); err != nil { |
| 108 |
log.Fatalf("wait for reassignment: %v", err) |
| 109 |
} |
| 110 |
|
| 111 |
final, err := describeTopic(admin, topic) |
| 112 |
if err != nil { |
| 113 |
log.Fatalf("describe topic after reassignment: %v", err) |
| 114 |
} |
| 115 |
log.Printf("final assignment for %q: %s", topic, formatAssignment(final)) |
| 116 |
} |
| 117 |
|
| 118 |
// describeTopic returns the current replica set for every partition, indexed by |
| 119 |
// partition ID. The inner slice mirrors what Kafka stores: an ordered list of |
| 120 |
// broker IDs where the first entry is the preferred leader and the rest are |
| 121 |
// followers. |
| 122 |
func describeTopic(admin sarama.ClusterAdmin, name string) ([][]int32, error) { |
| 123 |
meta, err := admin.DescribeTopics([]string{name}) |
| 124 |
if err != nil { |
| 125 |
return nil, err |
| 126 |
} |
| 127 |
if len(meta) == 0 { |
| 128 |
return nil, fmt.Errorf("topic %q not found", name) |
| 129 |
} |
| 130 |
t := meta[0] |
| 131 |
if t.Err != sarama.ErrNoError { |
| 132 |
return nil, t.Err |
| 133 |
} |
| 134 |
assignment := make([][]int32, len(t.Partitions)) |
| 135 |
for _, p := range t.Partitions { |
| 136 |
if int(p.ID) >= len(assignment) { |
| 137 |
return nil, fmt.Errorf("unexpected partition id %d for topic %q with %d partitions", p.ID, name, len(t.Partitions)) |
| 138 |
} |
| 139 |
assignment[p.ID] = slices.Clone(p.Replicas) |
| 140 |
} |
| 141 |
return assignment, nil |
| 142 |
} |
| 143 |
|
| 144 |
// buildTargetAssignment grows each partition's replica list to targetRF by |
| 145 |
// appending the least-used broker IDs not already in the partition's list. |
| 146 |
// Existing replicas are preserved in order so the preferred leader does not |
| 147 |
// move. Partitions that are already at or above the target RF are passed |
| 148 |
// through unchanged. |
| 149 |
func buildTargetAssignment(current [][]int32, brokerIDs []int32, targetRF int) ([][]int32, bool) { |
| 150 |
usage := make(map[int32]int, len(brokerIDs)) |
| 151 |
for _, replicas := range current { |
| 152 |
for _, id := range replicas { |
| 153 |
usage[id]++ |
| 154 |
} |
| 155 |
} |
| 156 |
|
| 157 |
target := make([][]int32, len(current)) |
| 158 |
changed := false |
| 159 |
for i, replicas := range current { |
| 160 |
target[i] = slices.Clone(replicas) |
| 161 |
for len(target[i]) < targetRF { |
| 162 |
id, ok := leastUsedBroker(brokerIDs, target[i], usage) |
| 163 |
if !ok { |
| 164 |
break |
| 165 |
} |
| 166 |
target[i] = append(target[i], id) |
| 167 |
usage[id]++ |
| 168 |
changed = true |
| 169 |
} |
| 170 |
} |
| 171 |
return target, changed |
| 172 |
} |
| 173 |
|
| 174 |
// leastUsedBroker returns the broker in brokerIDs (sorted ascending) that is |
| 175 |
// not already in exclude and currently hosts the fewest replicas, breaking |
| 176 |
// ties by lower broker ID. ok is false if every broker is excluded. |
| 177 |
func leastUsedBroker(brokerIDs, exclude []int32, usage map[int32]int) (int32, bool) { |
| 178 |
var best int32 |
| 179 |
bestUsage := -1 |
| 180 |
for _, id := range brokerIDs { |
| 181 |
if slices.Contains(exclude, id) { |
| 182 |
continue |
| 183 |
} |
| 184 |
if bestUsage == -1 || usage[id] < bestUsage { |
| 185 |
best = id |
| 186 |
bestUsage = usage[id] |
| 187 |
} |
| 188 |
} |
| 189 |
return best, bestUsage != -1 |
| 190 |
} |
| 191 |
|
| 192 |
// waitForReassignment polls ListPartitionReassignments until the broker stops |
| 193 |
// reporting any in-progress reassignment for the topic, or the timeout fires. |
| 194 |
// Kafka only returns partitions that are actively being reassigned, so an |
| 195 |
// empty TopicStatus entry means the move is complete. |
| 196 |
func waitForReassignment( |
| 197 |
ctx context.Context, |
| 198 |
admin sarama.ClusterAdmin, |
| 199 |
topic string, |
| 200 |
partitions []int32, |
| 201 |
interval, timeout time.Duration, |
| 202 |
) error { |
| 203 |
deadline := time.Now().Add(timeout) |
| 204 |
ticker := time.NewTicker(interval) |
| 205 |
defer ticker.Stop() |
| 206 |
|
| 207 |
for { |
| 208 |
status, err := admin.ListPartitionReassignments(topic, partitions) |
| 209 |
if err != nil { |
| 210 |
return fmt.Errorf("list partition reassignments: %w", err) |
| 211 |
} |
| 212 |
inProgress := status[topic] |
| 213 |
if len(inProgress) == 0 { |
| 214 |
return nil |
| 215 |
} |
| 216 |
log.Printf("%d partition(s) still reassigning", len(inProgress)) |
| 217 |
for p, s := range inProgress { |
| 218 |
log.Printf(" partition %d: adding=%v removing=%v current=%v", p, s.AddingReplicas, s.RemovingReplicas, s.Replicas) |
| 219 |
} |
| 220 |
if time.Now().After(deadline) { |
| 221 |
return fmt.Errorf("timed out waiting for reassignment of %q to complete", topic) |
| 222 |
} |
| 223 |
select { |
| 224 |
case <-ctx.Done(): |
| 225 |
return ctx.Err() |
| 226 |
case <-ticker.C: |
| 227 |
} |
| 228 |
} |
| 229 |
} |
| 230 |
|
| 231 |
func partitionIDs(assignment [][]int32) []int32 { |
| 232 |
ids := make([]int32, len(assignment)) |
| 233 |
for i := range assignment { |
| 234 |
ids[i] = int32(i) |
| 235 |
} |
| 236 |
return ids |
| 237 |
} |
| 238 |
|
| 239 |
func formatAssignment(assignment [][]int32) string { |
| 240 |
parts := make([]string, len(assignment)) |
| 241 |
for i, replicas := range assignment { |
| 242 |
parts[i] = fmt.Sprintf("p%d=%v", i, replicas) |
| 243 |
} |
| 244 |
return strings.Join(parts, " ") |
| 245 |
} |