-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathadmin_transactions.go
More file actions
295 lines (258 loc) · 9.09 KB
/
Copy pathadmin_transactions.go
File metadata and controls
295 lines (258 loc) · 9.09 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
291
292
293
294
295
package sarama
import (
"errors"
"fmt"
"io"
"strings"
"sync"
)
// TransactionClusterAdmin extends ClusterAdmin with the read-only KIP-664
// transaction-detection APIs: DescribeProducers, DescribeTransactions, and
// ListTransactions. Values returned by NewClusterAdmin and
// NewClusterAdminFromClient implement TransactionClusterAdmin.
type TransactionClusterAdmin interface {
ClusterAdmin
// DescribeProducers lists the active producers for the given topic
// partitions, querying each partition's leader. Requires Kafka 2.8.0.0 or
// higher.
DescribeProducers(topicPartitions map[string][]int32) (map[string]map[int32]DescribeProducersResponsePartition, error)
// DescribeTransactions returns the current state of the given transactional
// ids, querying each transaction's coordinator. Requires Kafka 3.0.0.0 or
// higher.
DescribeTransactions(transactionalIDs []string) (map[string]TransactionState, error)
// ListTransactions lists the transactions known to the cluster, optionally
// filtered by state, producer id, or (Kafka 3.8.0.0+) minimum duration in
// milliseconds. Requires Kafka 3.0.0.0 or higher. A durationFilterMs less
// than 0 disables the duration filter.
ListTransactions(stateFilters []string, producerIDFilters []int64, durationFilterMs int64) ([]ListTransactionsResponseTransactionState, error)
}
var _ TransactionClusterAdmin = (*clusterAdmin)(nil)
func (ca *clusterAdmin) DescribeProducers(topicPartitions map[string][]int32) (map[string]map[int32]DescribeProducersResponsePartition, error) {
if len(topicPartitions) == 0 {
return nil, nil
}
type topicPartition struct {
topic string
partition int32
}
// Group the requested partitions by their leader broker so a single request
// is sent to each leader.
partitionsPerBroker := make(map[*Broker][]topicPartition)
var errs []error
for topic, partitions := range topicPartitions {
for _, partition := range partitions {
leader, err := ca.client.Leader(topic, partition)
if err != nil {
errs = append(errs, fmt.Errorf("describe producers: find leader for partition %d of topic %s: %w", partition, topic, err))
continue
}
partitionsPerBroker[leader] = append(partitionsPerBroker[leader], topicPartition{topic, partition})
}
}
// Query each leader in parallel and merge the results.
type queryResult struct {
topics []DescribeProducersResponseTopic
err error
}
results := make(chan queryResult)
var wg sync.WaitGroup
for broker, topicPartitions := range partitionsPerBroker {
wg.Go(func() {
partitionsPerTopic := make(map[string][]int32)
for _, tp := range topicPartitions {
partitionsPerTopic[tp.topic] = append(partitionsPerTopic[tp.topic], tp.partition)
}
request := &DescribeProducersRequest{}
for topic, partitions := range partitionsPerTopic {
request.Topics = append(request.Topics, DescribeProducersRequestTopic{
Name: topic,
PartitionIndexes: partitions,
})
}
response, err := broker.DescribeProducers(request)
if err != nil {
results <- queryResult{err: fmt.Errorf("describe producers on broker %s: %w", broker.Addr(), err)}
return
}
results <- queryResult{topics: response.Topics}
})
}
go func() {
wg.Wait()
close(results)
}()
var result map[string]map[int32]DescribeProducersResponsePartition
for r := range results {
if r.err != nil {
errs = append(errs, r.err)
continue
}
for _, topic := range r.topics {
for _, partition := range topic.Partitions {
if result == nil {
result = make(map[string]map[int32]DescribeProducersResponsePartition)
}
if result[topic.Name] == nil {
result[topic.Name] = make(map[int32]DescribeProducersResponsePartition)
}
result[topic.Name][partition.PartitionIndex] = partition
}
}
}
return result, errors.Join(errs...)
}
func (ca *clusterAdmin) DescribeTransactions(transactionalIDs []string) (map[string]TransactionState, error) {
if len(transactionalIDs) == 0 {
return nil, nil
}
// Group the transactional ids by their coordinating broker so a single
// request is sent to each coordinator.
idsPerCoordinator := make(map[*Broker][]string)
var errs []error
for _, id := range transactionalIDs {
coordinator, err := ca.client.TransactionCoordinator(id)
if err != nil {
errs = append(errs, fmt.Errorf("describe transactions: find coordinator for transactional id %s: %w", id, err))
continue
}
idsPerCoordinator[coordinator] = append(idsPerCoordinator[coordinator], id)
}
// Query each coordinator in parallel and merge the results.
type queryResult struct {
states []TransactionState
err error
}
results := make(chan queryResult)
var wg sync.WaitGroup
for _, ids := range idsPerCoordinator {
wg.Go(func() {
var states []TransactionState
err := ca.retryOnError(isRetriableTransactionCoordinatorError, func() (err error) {
defer func() {
if err != nil && isRetriableTransactionCoordinatorError(err) {
for _, id := range ids {
_ = ca.client.RefreshTransactionCoordinator(id)
}
}
}()
perCoordinator := make(map[*Broker][]string)
for _, id := range ids {
coordinator, err := ca.client.TransactionCoordinator(id)
if err != nil {
return err
}
perCoordinator[coordinator] = append(perCoordinator[coordinator], id)
}
var attemptStates []TransactionState
for coordinator, groupIDs := range perCoordinator {
response, err := coordinator.DescribeTransactions(&DescribeTransactionsRequest{TransactionalIDs: groupIDs})
if err != nil {
return err
}
// A moved or loading coordinator answers successfully but tags the
// affected transactions with a retriable coordinator code; lift it so
// the coordinator is refreshed and the request retried.
for _, state := range response.TransactionStates {
if isRetriableTransactionCoordinatorError(state.ErrorCode) {
return state.ErrorCode
}
attemptStates = append(attemptStates, state)
}
}
states = attemptStates
return nil
})
if err != nil {
results <- queryResult{err: fmt.Errorf("describe transactions for %s: %w", strings.Join(ids, ", "), err)}
return
}
results <- queryResult{states: states}
})
}
go func() {
wg.Wait()
close(results)
}()
var result map[string]TransactionState
for r := range results {
if r.err != nil {
errs = append(errs, r.err)
continue
}
for _, state := range r.states {
if result == nil {
result = make(map[string]TransactionState)
}
result[state.TransactionalID] = state
}
}
return result, errors.Join(errs...)
}
// isRetriableTransactionCoordinatorError reports whether the given error is a
// transaction-coordinator error that refreshing the coordinator and retrying can
// resolve. It mirrors the set the transaction manager treats as retriable
// (COORDINATOR_NOT_AVAILABLE, NOT_COORDINATOR, COORDINATOR_LOAD_IN_PROGRESS) plus
// EOF for a dropped connection.
func isRetriableTransactionCoordinatorError(err error) bool {
switch {
case errors.Is(err, ErrConsumerCoordinatorNotAvailable):
return true
case errors.Is(err, ErrNotCoordinatorForConsumer):
return true
case errors.Is(err, ErrOffsetsLoadInProgress):
return true
case errors.Is(err, io.EOF):
return true
default:
return false
}
}
func (ca *clusterAdmin) ListTransactions(stateFilters []string, producerIDFilters []int64, durationFilterMs int64) ([]ListTransactionsResponseTransactionState, error) {
// The DurationFilter field was added in ListTransactions v1 (Kafka 3.8.0.0).
// Reject an explicit filter up front rather than silently ignoring it; a
// negative value disables the filter and is safe against any broker.
if durationFilterMs >= 0 && !ca.conf.Version.IsAtLeast(V3_8_0_0) {
return nil, ConfigurationError("ListTransactions durationFilterMs requires Version >= V3_8_0_0")
}
// Transactions may be listed by any broker, so query all brokers in parallel
// and merge the results.
brokers := ca.client.Brokers()
type queryResult struct {
states []ListTransactionsResponseTransactionState
err error
}
results := make(chan queryResult)
var wg sync.WaitGroup
for _, b := range brokers {
wg.Go(func() {
_ = b.Open(ca.conf) // Ensure that broker is opened
request := NewListTransactionsRequest(ca.conf.Version)
request.StateFilters = stateFilters
request.ProducerIDFilters = producerIDFilters
request.DurationFilter = durationFilterMs
response, err := b.ListTransactions(request)
switch {
case err != nil:
results <- queryResult{err: fmt.Errorf("list transactions on broker %s: %w", b.Addr(), err)}
case !errors.Is(response.ErrorCode, ErrNoError):
results <- queryResult{err: fmt.Errorf("list transactions on broker %s: %w", b.Addr(), response.ErrorCode)}
default:
results <- queryResult{states: response.TransactionStates}
}
})
}
go func() {
wg.Wait()
close(results)
}()
var allTransactions []ListTransactionsResponseTransactionState
var errs []error
for r := range results {
if r.err != nil {
errs = append(errs, r.err)
continue
}
allTransactions = append(allTransactions, r.states...)
}
return allTransactions, errors.Join(errs...)
}