-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathtopic.go
More file actions
344 lines (297 loc) · 10.2 KB
/
Copy pathtopic.go
File metadata and controls
344 lines (297 loc) · 10.2 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package config
import (
"errors"
"fmt"
"github.com/ghodss/yaml"
"github.com/hashicorp/go-multierror"
"github.com/segmentio/kafka-go"
"github.com/segmentio/topicctl/pkg/admin"
log "github.com/sirupsen/logrus"
)
// PlacementStrategy is a string type that stores a replica placement strategy for a topic.
type PlacementStrategy string
const (
// PlacementStrategyAny allows any partition placement.
PlacementStrategyAny PlacementStrategy = "any"
// PlacementStrategyBalancedLeaders is a strategy that ensures the leaders of
// each partition are balanced by rack, but does not care about the placements
// of the non-leader replicas.
PlacementStrategyBalancedLeaders PlacementStrategy = "balanced-leaders"
// PlacementStrategyInRack is a strategy in which the leaders are balanced
// and the replicas for each partition are in the same rack as the leader.
PlacementStrategyInRack PlacementStrategy = "in-rack"
// PlacementStrategyCrossRack is a strategy in which the leaders are balanced
// and the replicas in each partition are spread to separate racks.
PlacementStrategyCrossRack PlacementStrategy = "cross-rack"
// PlacementStrategyStatic uses a static placement defined in the config. This is for
// testing only and should generally not be used in production.
PlacementStrategyStatic PlacementStrategy = "static"
// PlacementStrategyStaticInRack is a strategy in which the replicas in each partition
// are chosen from the rack in a static list, but the specific replicas within each partition
// aren't specified.
PlacementStrategyStaticInRack PlacementStrategy = "static-in-rack"
)
var allPlacementStrategies = []PlacementStrategy{
PlacementStrategyAny,
PlacementStrategyBalancedLeaders,
PlacementStrategyInRack,
PlacementStrategyCrossRack,
PlacementStrategyStatic,
PlacementStrategyStaticInRack,
}
// PickerMethod is a string type that stores a picker method for breaking ties when choosing
// the replica placements for a topic.
type PickerMethod string
const (
// PickerMethodClusterUse uses broker frequency in the topic, breaking ties by
// looking at the total number of replicas across the entire cluster that each broker
// appears in.
PickerMethodClusterUse PickerMethod = "cluster-use"
// PickerMethodLowestIndex uses broker frequency in the topic, breaking ties by
// choosing the broker with the lowest index.
PickerMethodLowestIndex PickerMethod = "lowest-index"
// PickerMethodRandomized uses broker frequency in the topic, breaking ties by
// using a repeatably random choice from the options.
PickerMethodRandomized PickerMethod = "randomized"
)
var allPickerMethods = []PickerMethod{
PickerMethodClusterUse,
PickerMethodLowestIndex,
PickerMethodRandomized,
}
// TopicConfig represents the desired configuration of a topic.
type TopicConfig struct {
Meta ResourceMeta `json:"meta"`
Spec TopicSpec `json:"spec"`
}
// TopicSpec stores the (mutable) specification for a topic.
type TopicSpec struct {
Partitions int `json:"partitions"`
ReplicationFactor int `json:"replicationFactor"`
RetentionMinutes int `json:"retentionMinutes,omitempty"`
Settings TopicSettings `json:"settings,omitempty"`
PlacementConfig TopicPlacementConfig `json:"placement"`
MigrationConfig *TopicMigrationConfig `json:"migration,omitempty"`
}
// TopicPlacementConfig describes how the partition replicas in a topic
// should be chosen.
type TopicPlacementConfig struct {
Strategy PlacementStrategy `json:"strategy"`
Picker PickerMethod `json:"picker,omitempty"`
// StaticAssignments is a list of lists of desired replica assignments. It's used
// for the "static" strategy only.
StaticAssignments [][]int `json:"staticAssignments,omitempty"`
// StaticRackAssignments is a list of list of desired replica assignments. It's used
// for the "static-in-rack" strategy only.
StaticRackAssignments []string `json:"staticRackAssignments,omitempty"`
}
// TopicMigrationConfig configures the throttles and batch sizes used when
// running a partition migration. If these are left unset, resonable defaults
// will be used instead.
type TopicMigrationConfig struct {
ThrottleMB int64 `json:"throttleMB"`
PartitionBatchSize int `json:"partitionBatchSize"`
}
// ToNewTopicConfig converts a TopicConfig to a kafka.TopicConfig that can be
// used by kafka-go to create a new topic.
func (t TopicConfig) ToNewTopicConfig() (kafka.TopicConfig, error) {
config := kafka.TopicConfig{
Topic: t.Meta.Name,
NumPartitions: t.Spec.Partitions,
ReplicationFactor: t.Spec.ReplicationFactor,
}
if len(t.Spec.Settings) > 0 {
entries, err := t.Spec.Settings.ToConfigEntries(nil)
if err != nil {
return config, err
}
config.ConfigEntries = entries
}
if t.Spec.RetentionMinutes > 0 {
config.ConfigEntries = append(
config.ConfigEntries,
kafka.ConfigEntry{
ConfigName: admin.RetentionKey,
ConfigValue: fmt.Sprintf("%d", t.Spec.RetentionMinutes*60*1000),
},
)
}
return config, nil
}
// SetDefaults sets the default migration and placement settings in a topic config
// if these aren't set.
func (t *TopicConfig) SetDefaults() {
if t.Spec.MigrationConfig == nil {
t.Spec.MigrationConfig = &TopicMigrationConfig{}
}
if t.Spec.MigrationConfig.PartitionBatchSize == 0 {
// Migration partitions one at a time
t.Spec.MigrationConfig.PartitionBatchSize = 1
}
if t.Spec.PlacementConfig.Picker == "" {
t.Spec.PlacementConfig.Picker = PickerMethodRandomized
}
}
// Validate evaluates whether the topic config is valid.
func (t TopicConfig) Validate(numRacks int) error {
var err error
err = t.Meta.Validate()
if t.Spec.Partitions <= 0 {
err = multierror.Append(err, errors.New("Partitions must be a positive number"))
}
if t.Spec.ReplicationFactor <= 0 {
err = multierror.Append(err, errors.New("ReplicationFactor must be > 0"))
}
if settingsErr := t.Spec.Settings.Validate(); settingsErr != nil {
err = multierror.Append(err, settingsErr)
}
if t.Spec.RetentionMinutes < 0 {
err = multierror.Append(err, errors.New("RetentionMinutes must be >= 0"))
}
if t.Spec.RetentionMinutes > 0 && t.Spec.Settings["retention.ms"] != nil {
err = multierror.Append(
err,
errors.New("Cannot set both RetentionMinutes and retention.ms in settings"),
)
}
if (t.Spec.Settings["local.retention.bytes"] != nil || t.Spec.Settings["local.retention.ms"] != nil) && t.Spec.Settings["remote.storage.enable"] == nil {
err = multierror.Append(
err,
errors.New("Setting local retention parameters requires remote.storage.enable to be set in settings"),
)
}
placement := t.Spec.PlacementConfig
strategyIndex := -1
for s, strategy := range allPlacementStrategies {
if strategy == placement.Strategy {
strategyIndex = s
break
}
}
if strategyIndex == -1 {
err = multierror.Append(
err,
fmt.Errorf(
"PlacementStrategy must in %+v",
allPlacementStrategies,
),
)
}
pickerIndex := -1
for p, pickerMethod := range allPickerMethods {
if pickerMethod == placement.Picker {
pickerIndex = p
break
}
}
if pickerIndex == -1 {
err = multierror.Append(
err,
fmt.Errorf(
"PickerMethod must in %+v",
allPickerMethods,
),
)
}
switch placement.Strategy {
case PlacementStrategyBalancedLeaders:
if numRacks > 0 && t.Spec.Partitions%numRacks != 0 {
// The balanced-leaders strategy requires that the
// partitions be a multiple of the number of racks, otherwise it's impossible
// to find a placement that satisfies the strategy.
err = multierror.Append(
err,
fmt.Errorf(
"Number of partitions (%d) is not a multiple of the number of racks (%d)",
t.Spec.Partitions,
numRacks,
),
)
}
case PlacementStrategyCrossRack:
if numRacks > 0 && t.Spec.ReplicationFactor > numRacks {
err = multierror.Append(
err,
fmt.Errorf(
"Replication factor (%d) cannot be larger than the number of racks (%d)",
t.Spec.ReplicationFactor,
numRacks,
),
)
}
case PlacementStrategyInRack:
case PlacementStrategyStatic:
if len(placement.StaticAssignments) != t.Spec.Partitions {
err = multierror.Append(
err,
errors.New("Static assignments must be same length as partitions"),
)
} else {
for _, replicas := range placement.StaticAssignments {
if len(replicas) != t.Spec.ReplicationFactor {
err = multierror.Append(
err,
errors.New("Static assignment rows must match replication factor"),
)
break
}
}
}
case PlacementStrategyStaticInRack:
if len(placement.StaticRackAssignments) != t.Spec.Partitions {
err = multierror.Append(
err,
errors.New("Static rack assignments must be same length as partitions"),
)
}
}
// Warn about the partition count in the non-balanced-leaders case
if numRacks > 0 &&
placement.Strategy != PlacementStrategyBalancedLeaders &&
t.Spec.Partitions%numRacks != 0 {
log.Warnf("Number of partitions (%d) is not a multiple of the number of racks (%d)",
t.Spec.Partitions,
numRacks,
)
}
return err
}
// ToYAML converts the current TopicConfig to a YAML string.
func (t TopicConfig) ToYAML() (string, error) {
outBytes, err := yaml.Marshal(t)
if err != nil {
return "", err
}
return string(outBytes), nil
}
// TopicConfigFromTopicInfo generates a TopicConfig from a ClusterConfig and admin.TopicInfo
// struct generated from the cluster state.
func TopicConfigFromTopicInfo(
clusterConfig ClusterConfig,
topicInfo admin.TopicInfo,
placementStrategy PlacementStrategy,
) TopicConfig {
topicConfig := TopicConfig{
Meta: ResourceMeta{
Name: topicInfo.Name,
Cluster: clusterConfig.Meta.Name,
Region: clusterConfig.Meta.Region,
Environment: clusterConfig.Meta.Environment,
Description: "Bootstrapped via topicctl bootstrap",
},
Spec: TopicSpec{
Partitions: len(topicInfo.Partitions),
ReplicationFactor: len(topicInfo.Partitions[0].Replicas),
PlacementConfig: TopicPlacementConfig{
Strategy: placementStrategy,
},
},
}
topicConfig.Spec.Settings = FromConfigMap(topicInfo.Config)
retentionMinutes := topicInfo.Retention().Minutes()
if retentionMinutes >= 1.0 && float64(int(retentionMinutes)) == retentionMinutes {
topicConfig.Spec.RetentionMinutes = int(retentionMinutes)
delete(topicConfig.Spec.Settings, admin.RetentionKey)
}
return topicConfig
}