-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathkafka_admin.go
More file actions
290 lines (260 loc) · 10.9 KB
/
Copy pathkafka_admin.go
File metadata and controls
290 lines (260 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Copyright 2026 Google LLC
//
// 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
//
// https://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 pscompat
import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/IBM/sarama"
)
// metadataRetry is used by TopicPartitionCount, GetTopic, and ListTopics to
// tolerate the brief window after CreateTopic where Kafka metadata has not yet
// propagated to all brokers.
const (
metadataRetryAttempts = 6
metadataRetryDelay = 500 * time.Millisecond
)
// ErrUnsupported indicates an operation that has no meaningful Kafka analogue.
// Callers should either omit the operation or handle this error explicitly.
var ErrUnsupported = errors.New("gmk: operation unsupported on Managed Kafka backend")
// KafkaAdminClientConfig configures a KafkaAdminClient.
type KafkaAdminClientConfig struct {
// BootstrapServers is the Kafka bootstrap server address.
// Use BuildGMKBootstrapServer() to construct this for GMK clusters.
BootstrapServers string
// SaramaConfig is an optional pre-built Sarama configuration. If nil,
// NewGMKSaramaConfig() is called to build one with GCP OAUTHBEARER auth.
SaramaConfig *sarama.Config
}
// KafkaAdminClient is a Managed Kafka-backed admin client providing PSL-style
// topic and subscription management. Subscriptions map to Kafka consumer
// groups; topics map to Kafka topics.
//
// Methods that have no Kafka analogue (updateSubscription, reservation ops,
// seekSubscription) either return ErrUnsupported or log a WARNING and succeed
// as a no-op, matching the documented degraded-behavior contract.
type KafkaAdminClient struct {
admin sarama.ClusterAdmin
}
// NewKafkaAdminClient creates an admin client connected to Managed Kafka.
func NewKafkaAdminClient(ctx context.Context, cfg *KafkaAdminClientConfig) (*KafkaAdminClient, error) {
if cfg == nil || cfg.BootstrapServers == "" {
return nil, fmt.Errorf("gmk: KafkaAdminClientConfig.BootstrapServers must not be empty")
}
saramaCfg := cfg.SaramaConfig
if saramaCfg == nil {
var err error
saramaCfg, err = NewGMKSaramaConfig(ctx)
if err != nil {
return nil, fmt.Errorf("gmk: failed to create Sarama config: %w", err)
}
}
admin, err := sarama.NewClusterAdmin([]string{cfg.BootstrapServers}, saramaCfg)
if err != nil {
return nil, fmt.Errorf("gmk: failed to create cluster admin: %w", err)
}
return &KafkaAdminClient{admin: admin}, nil
}
// Close releases the underlying connection.
func (c *KafkaAdminClient) Close() error {
return c.admin.Close()
}
// CreateTopic creates a Kafka topic with the given partition count and
// replication factor.
func (c *KafkaAdminClient) CreateTopic(_ context.Context, topic string, numPartitions int32, replicationFactor int16) error {
return c.admin.CreateTopic(topic, &sarama.TopicDetail{
NumPartitions: numPartitions,
ReplicationFactor: replicationFactor,
}, false)
}
// DeleteTopic deletes a Kafka topic.
func (c *KafkaAdminClient) DeleteTopic(_ context.Context, topic string) error {
return c.admin.DeleteTopic(topic)
}
// TopicPartitionCount returns the number of partitions for the given topic.
// Retries briefly to tolerate post-CreateTopic metadata propagation.
func (c *KafkaAdminClient) TopicPartitionCount(_ context.Context, topic string) (int, error) {
var lastErr error
for i := 0; i < metadataRetryAttempts; i++ {
meta, err := c.admin.DescribeTopics([]string{topic})
if err == nil && len(meta) > 0 && meta[0] != nil && meta[0].Err == sarama.ErrNoError {
return len(meta[0].Partitions), nil
}
if err != nil {
lastErr = err
} else if len(meta) > 0 && meta[0] != nil {
lastErr = meta[0].Err
} else {
lastErr = fmt.Errorf("topic %q not found", topic)
}
time.Sleep(metadataRetryDelay)
}
return 0, fmt.Errorf("gmk: describe topic %q after %d attempts: %w", topic, metadataRetryAttempts, lastErr)
}
// GetTopic returns metadata for a single topic.
func (c *KafkaAdminClient) GetTopic(_ context.Context, topic string) (*sarama.TopicMetadata, error) {
meta, err := c.admin.DescribeTopics([]string{topic})
if err != nil {
return nil, err
}
if len(meta) == 0 || meta[0] == nil {
return nil, fmt.Errorf("gmk: topic %q not found", topic)
}
if meta[0].Err != sarama.ErrNoError {
return nil, fmt.Errorf("gmk: describe topic %q: %w", topic, meta[0].Err)
}
return meta[0], nil
}
// ListTopics returns all non-internal topic names in the cluster.
// Internal topics (those starting with "__") are filtered out, matching the
// Java KafkaAdminClient behavior. Optionally accepts an "expect" topic that
// must be present; retries briefly to tolerate post-CreateTopic metadata
// propagation.
func (c *KafkaAdminClient) ListTopics(_ context.Context) ([]string, error) {
topics, err := c.admin.ListTopics()
if err != nil {
return nil, err
}
var out []string
for name := range topics {
if strings.HasPrefix(name, "__") {
continue
}
out = append(out, name)
}
return out, nil
}
// ListTopicsAwait is like ListTopics but retries until the named topic shows
// up in the listing or attempts are exhausted. Useful for workflows that
// create a topic and then immediately list it.
func (c *KafkaAdminClient) ListTopicsAwait(ctx context.Context, expect string) ([]string, error) {
var lastErr error
for i := 0; i < metadataRetryAttempts; i++ {
topics, err := c.ListTopics(ctx)
if err != nil {
lastErr = err
time.Sleep(metadataRetryDelay)
continue
}
for _, t := range topics {
if t == expect {
return topics, nil
}
}
lastErr = fmt.Errorf("topic %q not yet visible in listing", expect)
time.Sleep(metadataRetryDelay)
}
return nil, fmt.Errorf("gmk: ListTopicsAwait %q: %w", expect, lastErr)
}
// UpdateTopic is a no-op on Managed Kafka. Kafka does not support mutable
// topic configurations. A WARNING is logged for visibility.
func (c *KafkaAdminClient) UpdateTopic(_ context.Context, topic string) error {
log.Printf("WARNING: gmk: UpdateTopic is a no-op on Managed Kafka (topic=%q)", topic)
return nil
}
// IncreasePartitions grows a topic's partition count. Kafka only supports
// monotonically increasing partition counts; shrinking is not possible.
//
// Note: increasing partitions on a live topic does not redistribute existing
// data. Producers using the default partitioner will start routing keys to
// the new partition layout immediately, which can break per-key ordering
// guarantees for keys whose hash now maps to a different partition. Existing
// records remain on their original partitions and are not rebalanced. Most
// callers will want to coordinate this with their producers/consumers (and
// any downstream stateful processors) before calling.
func (c *KafkaAdminClient) IncreasePartitions(_ context.Context, topic string, newCount int32) error {
log.Printf("WARNING: gmk: IncreasePartitions(%q, %d): existing data is not rebalanced across the new partitions, "+
"and key→partition assignments will change for any keys whose hash now maps to a different partition; "+
"per-key ordering may be broken until you manually rebalance", topic, newCount)
return c.admin.CreatePartitions(topic, newCount, nil, false)
}
// SeekSubscription returns ErrUnsupported. Admin-level seeks are not exposed
// by the Kafka admin surface; use KafkaCursorClient for offset management.
func (c *KafkaAdminClient) SeekSubscription(_ context.Context, _ string) error {
return fmt.Errorf("gmk: SeekSubscription not supported; use KafkaCursorClient.ResetOffsets: %w", ErrUnsupported)
}
// CreateSubscription is a no-op on Managed Kafka. Consumer groups are created
// implicitly when a consumer joins them for the first time.
func (c *KafkaAdminClient) CreateSubscription(_ context.Context, groupID string) error {
log.Printf("INFO: gmk: CreateSubscription is a no-op on Managed Kafka (groupID=%q); groups are created implicitly", groupID)
return nil
}
// UpdateSubscription is a no-op on Managed Kafka. Kafka consumer groups lack
// centralized mutable configuration.
func (c *KafkaAdminClient) UpdateSubscription(_ context.Context, groupID string) error {
log.Printf("WARNING: gmk: UpdateSubscription is a no-op on Managed Kafka (groupID=%q)", groupID)
return nil
}
// DeleteSubscription deletes a Kafka consumer group.
func (c *KafkaAdminClient) DeleteSubscription(_ context.Context, groupID string) error {
return c.admin.DeleteConsumerGroup(groupID)
}
// GetSubscription returns the offsets currently committed for a consumer
// group on a given topic. Matches PSL's GetSubscription semantics insofar as
// Kafka offers an analogue.
func (c *KafkaAdminClient) GetSubscription(_ context.Context, groupID, topic string) (map[int32]int64, error) {
resp, err := c.admin.ListConsumerGroupOffsets(groupID, map[string][]int32{topic: nil})
if err != nil {
return nil, err
}
out := make(map[int32]int64)
for p, block := range resp.Blocks[topic] {
out[p] = block.Offset
}
return out, nil
}
// ListSubscriptions returns all Kafka consumer group names in the cluster.
func (c *KafkaAdminClient) ListSubscriptions(_ context.Context) ([]string, error) {
groups, err := c.admin.ListConsumerGroups()
if err != nil {
return nil, err
}
var out []string
for name := range groups {
out = append(out, name)
}
return out, nil
}
// --- Reservation operations (no-ops) ---------------------------------------
//
// PSL reservation concepts (throughput capacity units) have no Kafka analogue.
// These methods exist for PSL surface parity and simply log at INFO level.
// CreateReservation is a no-op on Managed Kafka.
func (c *KafkaAdminClient) CreateReservation(_ context.Context, name string) error {
log.Printf("INFO: gmk: CreateReservation is a no-op on Managed Kafka (name=%q)", name)
return nil
}
// GetReservation is a no-op on Managed Kafka.
func (c *KafkaAdminClient) GetReservation(_ context.Context, name string) error {
log.Printf("INFO: gmk: GetReservation is a no-op on Managed Kafka (name=%q)", name)
return nil
}
// ListReservations is a no-op on Managed Kafka.
func (c *KafkaAdminClient) ListReservations(_ context.Context) ([]string, error) {
log.Printf("INFO: gmk: ListReservations is a no-op on Managed Kafka")
return nil, nil
}
// UpdateReservation is a no-op on Managed Kafka.
func (c *KafkaAdminClient) UpdateReservation(_ context.Context, name string) error {
log.Printf("INFO: gmk: UpdateReservation is a no-op on Managed Kafka (name=%q)", name)
return nil
}
// DeleteReservation is a no-op on Managed Kafka.
func (c *KafkaAdminClient) DeleteReservation(_ context.Context, name string) error {
log.Printf("INFO: gmk: DeleteReservation is a no-op on Managed Kafka (name=%q)", name)
return nil
}