-
Notifications
You must be signed in to change notification settings - Fork 20
/
kafkatopic_controller.go
251 lines (209 loc) · 8.3 KB
/
kafkatopic_controller.go
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
// Copyright (c) 2024 Aiven, Helsinki, Finland. https://aiven.io/
package controllers
import (
"context"
"fmt"
"strconv"
"github.com/aiven/aiven-go-client/v2"
avngen "github.com/aiven/go-client-codegen"
"github.com/aiven/go-client-codegen/handler/service"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aiven/aiven-operator/api/v1alpha1"
)
// KafkaTopicReconciler reconciles a KafkaTopic object
type KafkaTopicReconciler struct {
Controller
}
func newKafkaTopicReconciler(c Controller) reconcilerType {
return &KafkaTopicReconciler{Controller: c}
}
type KafkaTopicHandler struct{}
//+kubebuilder:rbac:groups=aiven.io,resources=kafkatopics,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=aiven.io,resources=kafkatopics/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=aiven.io,resources=kafkatopics/finalizers,verbs=get;create;update
func (r *KafkaTopicReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
return r.reconcileInstance(ctx, req, KafkaTopicHandler{}, &v1alpha1.KafkaTopic{})
}
func (r *KafkaTopicReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.KafkaTopic{}).
Complete(r)
}
func (h KafkaTopicHandler) createOrUpdate(ctx context.Context, avn *aiven.Client, avnGen avngen.Client, obj client.Object, refs []client.Object) error {
topic, err := h.convert(obj)
if err != nil {
return err
}
var tags []aiven.KafkaTopicTag
for _, t := range topic.Spec.Tags {
tags = append(tags, aiven.KafkaTopicTag{
Key: t.Key,
Value: t.Value,
})
}
exists, err := h.exists(ctx, avn, topic)
if err != nil {
return err
}
var reason string
if !exists {
err = avn.KafkaTopics.Create(ctx, topic.Spec.Project, topic.Spec.ServiceName, aiven.CreateKafkaTopicRequest{
Partitions: &topic.Spec.Partitions,
Replication: &topic.Spec.Replication,
TopicName: topic.GetTopicName(),
Tags: tags,
Config: convertKafkaTopicConfig(topic),
})
if err != nil && !isAlreadyExists(err) {
return err
}
reason = "Created"
} else {
err = avn.KafkaTopics.Update(ctx, topic.Spec.Project, topic.Spec.ServiceName, topic.GetTopicName(),
aiven.UpdateKafkaTopicRequest{
Partitions: &topic.Spec.Partitions,
Replication: &topic.Spec.Replication,
Tags: tags,
Config: convertKafkaTopicConfig(topic),
})
if err != nil {
return fmt.Errorf("cannot update Kafka Topic: %w", err)
}
reason = "Updated"
}
meta.SetStatusCondition(&topic.Status.Conditions,
getInitializedCondition(reason,
"Successfully created or updated the instance in Aiven"))
meta.SetStatusCondition(&topic.Status.Conditions,
getRunningCondition(metav1.ConditionUnknown, reason,
"Successfully created or updated the instance in Aiven, status remains unknown"))
metav1.SetMetaDataAnnotation(&topic.ObjectMeta,
processedGenerationAnnotation, strconv.FormatInt(topic.GetGeneration(), formatIntBaseDecimal))
return nil
}
func (h KafkaTopicHandler) delete(ctx context.Context, avn *aiven.Client, avnGen avngen.Client, obj client.Object) (bool, error) {
topic, err := h.convert(obj)
if err != nil {
return false, err
}
if fromAnyPointer(topic.Spec.TerminationProtection) {
return false, errTerminationProtectionOn
}
// Delete project on Aiven side
err = avn.KafkaTopics.Delete(ctx, topic.Spec.Project, topic.Spec.ServiceName, topic.GetTopicName())
if err != nil && !isNotFound(err) {
return false, err
}
return true, nil
}
func (h KafkaTopicHandler) exists(ctx context.Context, avn *aiven.Client, topic *v1alpha1.KafkaTopic) (bool, error) {
t, err := avn.KafkaTopics.Get(ctx, topic.Spec.Project, topic.Spec.ServiceName, topic.GetTopicName())
if err != nil && !isNotFound(err) {
if aivenError, ok := err.(aiven.Error); ok {
// Getting topic info can sometimes temporarily fail with 501 and 502. Don't
// treat that as fatal error but keep on retrying instead.
if aivenError.Status == 501 || aivenError.Status == 502 {
return true, nil
}
}
return false, err
}
return t != nil, nil
}
func (h KafkaTopicHandler) get(ctx context.Context, avn *aiven.Client, avnGen avngen.Client, obj client.Object) (*corev1.Secret, error) {
topic, err := h.convert(obj)
if err != nil {
return nil, err
}
state, err := h.getState(ctx, avn, topic)
if err != nil {
return nil, err
}
topic.Status.State = state
if state == "ACTIVE" {
meta.SetStatusCondition(&topic.Status.Conditions,
getRunningCondition(metav1.ConditionTrue, "CheckRunning",
"Instance is running on Aiven side"))
metav1.SetMetaDataAnnotation(&topic.ObjectMeta, instanceIsRunningAnnotation, "true")
}
return nil, err
}
func (h KafkaTopicHandler) checkPreconditions(ctx context.Context, avn *aiven.Client, avnGen avngen.Client, obj client.Object) (bool, error) {
topic, err := h.convert(obj)
if err != nil {
return false, err
}
meta.SetStatusCondition(&topic.Status.Conditions,
getInitializedCondition("Preconditions", "Checking preconditions"))
s, err := avnGen.ServiceGet(ctx, topic.Spec.Project, topic.Spec.ServiceName)
if isNotFound(err) {
return false, nil
}
if err != nil {
return false, err
}
running := 0
for _, node := range s.NodeStates {
if node.State == service.NodeStateTypeRunning {
running++
}
}
// Replication factor requires enough nodes running.
// But we want to get the backend validation error if the value is too high
return running >= min(len(s.NodeStates), topic.Spec.Replication), nil
}
func (h KafkaTopicHandler) getState(ctx context.Context, avn *aiven.Client, topic *v1alpha1.KafkaTopic) (string, error) {
t, err := avn.KafkaTopics.Get(ctx, topic.Spec.Project, topic.Spec.ServiceName, topic.GetTopicName())
if err != nil {
if aivenError, ok := err.(aiven.Error); ok {
// Getting topic info can sometimes temporarily fail with 501 and 502. Don't
// treat that as fatal error but keep on retrying instead.
if aivenError.Status == 501 || aivenError.Status == 502 {
return "", nil
}
}
return "", err
}
return t.State, nil
}
func (h KafkaTopicHandler) convert(i client.Object) (*v1alpha1.KafkaTopic, error) {
topic, ok := i.(*v1alpha1.KafkaTopic)
if !ok {
return nil, fmt.Errorf("cannot convert object to KafkaTopic")
}
return topic, nil
}
func convertKafkaTopicConfig(topic *v1alpha1.KafkaTopic) aiven.KafkaTopicConfig {
return aiven.KafkaTopicConfig{
CleanupPolicy: topic.Spec.Config.CleanupPolicy,
CompressionType: topic.Spec.Config.CompressionType,
DeleteRetentionMs: topic.Spec.Config.DeleteRetentionMs,
FileDeleteDelayMs: topic.Spec.Config.FileDeleteDelayMs,
FlushMessages: topic.Spec.Config.FlushMessages,
FlushMs: topic.Spec.Config.FlushMs,
IndexIntervalBytes: topic.Spec.Config.IndexIntervalBytes,
LocalRetentionBytes: topic.Spec.Config.LocalRetentionBytes,
LocalRetentionMs: topic.Spec.Config.LocalRetentionMs,
MaxCompactionLagMs: topic.Spec.Config.MaxCompactionLagMs,
MaxMessageBytes: topic.Spec.Config.MaxMessageBytes,
MessageDownconversionEnable: topic.Spec.Config.MessageDownconversionEnable,
MessageFormatVersion: topic.Spec.Config.MessageFormatVersion,
MessageTimestampDifferenceMaxMs: topic.Spec.Config.MessageTimestampDifferenceMaxMs,
MessageTimestampType: topic.Spec.Config.MessageTimestampType,
MinCleanableDirtyRatio: topic.Spec.Config.MinCleanableDirtyRatio,
MinCompactionLagMs: topic.Spec.Config.MinCompactionLagMs,
MinInsyncReplicas: topic.Spec.Config.MinInsyncReplicas,
Preallocate: topic.Spec.Config.Preallocate,
RemoteStorageEnable: topic.Spec.Config.RemoteStorageEnable,
RetentionBytes: topic.Spec.Config.RetentionBytes,
RetentionMs: topic.Spec.Config.RetentionMs,
SegmentBytes: topic.Spec.Config.SegmentBytes,
SegmentIndexBytes: topic.Spec.Config.SegmentIndexBytes,
SegmentJitterMs: topic.Spec.Config.SegmentJitterMs,
SegmentMs: topic.Spec.Config.SegmentMs,
}
}