-
Notifications
You must be signed in to change notification settings - Fork 20
/
kafkaconnector_controller.go
232 lines (197 loc) · 7.32 KB
/
kafkaconnector_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
// Copyright (c) 2024 Aiven, Helsinki, Finland. https://aiven.io/
package controllers
import (
"bytes"
"context"
"fmt"
"strconv"
"text/template"
"github.com/aiven/aiven-go-client/v2"
avngen "github.com/aiven/go-client-codegen"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aiven/aiven-operator/api/v1alpha1"
)
// KafkaConnectorReconciler reconciles a KafkaConnector object
type KafkaConnectorReconciler struct {
Controller
}
func newKafkaConnectorReconciler(c Controller) reconcilerType {
return &KafkaConnectorReconciler{Controller: c}
}
type KafkaConnectorHandler struct {
k8s client.Client
}
//+kubebuilder:rbac:groups=aiven.io,resources=kafkaconnectors,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=aiven.io,resources=kafkaconnectors/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=aiven.io,resources=kafkaconnectors/finalizers,verbs=get;create;update
func (r *KafkaConnectorReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
return r.reconcileInstance(ctx, req, KafkaConnectorHandler{k8s: r.Client}, &v1alpha1.KafkaConnector{})
}
// SetupWithManager sets up the controller with the Manager.
func (r *KafkaConnectorReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&v1alpha1.KafkaConnector{}).
Complete(r)
}
func (h KafkaConnectorHandler) createOrUpdate(ctx context.Context, avn *aiven.Client, avnGen avngen.Client, obj client.Object, refs []client.Object) error {
conn, err := h.convert(obj)
if err != nil {
return err
}
exists, err := h.exists(ctx, avn, conn)
if err != nil {
return fmt.Errorf("unable to check if kafka connector exists: %w", err)
}
connCfg, err := h.buildConnectorConfig(conn)
if err != nil {
return fmt.Errorf("unable to build connector config: %w", err)
}
var reason string
if !exists {
err = avn.KafkaConnectors.Create(ctx, conn.Spec.Project, conn.Spec.ServiceName, connCfg)
if err != nil && !isAlreadyExists(err) {
return err
}
reason = "Created"
} else {
_, err = avn.KafkaConnectors.Update(ctx, conn.Spec.Project, conn.Spec.ServiceName, conn.Name, connCfg)
if err != nil {
return err
}
reason = "Updated"
}
meta.SetStatusCondition(&conn.Status.Conditions,
getInitializedCondition(reason,
"Successfully created or updated the instance in Aiven"))
meta.SetStatusCondition(&conn.Status.Conditions,
getRunningCondition(metav1.ConditionUnknown, reason,
"Successfully created or updated the instance in Aiven, status remains unknown"))
metav1.SetMetaDataAnnotation(&conn.ObjectMeta,
processedGenerationAnnotation, strconv.FormatInt(conn.GetGeneration(), formatIntBaseDecimal))
return nil
}
// buildConnectorConfig joins mandatory fields with additional connector specific config
func (h KafkaConnectorHandler) buildConnectorConfig(conn *v1alpha1.KafkaConnector) (aiven.KafkaConnectorConfig, error) {
const (
configFieldConnectorName = "name"
configFieldConnectorClass = "connector.class"
)
var (
templateFuncFromSecret = func(name, key string) (string, error) {
var secret corev1.Secret
if err := h.k8s.Get(context.Background(), types.NamespacedName{Namespace: conn.GetNamespace(), Name: name}, &secret); err != nil {
return "", fmt.Errorf("unable to fetch secret: '%w'", err)
}
v, ok := secret.Data[key]
if !ok {
return "", fmt.Errorf("no such key in secret '%s': '%s'", name, key)
}
return string(v), nil
}
funcMap = template.FuncMap{
"fromSecret": templateFuncFromSecret,
}
)
m := make(map[string]string)
m[configFieldConnectorName] = conn.GetName()
m[configFieldConnectorClass] = conn.Spec.ConnectorClass
for k, v := range conn.Spec.UserConfig {
t, err := template.New(k).Funcs(funcMap).Parse(v)
if err != nil {
return nil, fmt.Errorf("unable to parse template for key '%s': '%w'", k, err)
}
templateRes := new(bytes.Buffer)
if err := t.Execute(templateRes, nil); err != nil {
return nil, fmt.Errorf("unable to execute template for key '%s': '%w'", k, err)
}
m[k] = templateRes.String()
}
return m, nil
}
func (h KafkaConnectorHandler) delete(ctx context.Context, avn *aiven.Client, avnGen avngen.Client, obj client.Object) (bool, error) {
conn, err := h.convert(obj)
if err != nil {
return false, err
}
err = avn.KafkaConnectors.Delete(ctx, conn.Spec.Project, conn.Spec.ServiceName, conn.Name)
if err != nil && !isNotFound(err) {
return false, fmt.Errorf("unable to delete kafka connector: %w", err)
}
return true, nil
}
func (h KafkaConnectorHandler) exists(ctx context.Context, avn *aiven.Client, conn *v1alpha1.KafkaConnector) (bool, error) {
connector, err := avn.KafkaConnectors.Status(ctx, conn.Spec.Project, conn.Spec.ServiceName, conn.Name)
if err != nil && !isNotFound(err) {
return false, err
}
return connector != nil, nil
}
func (h KafkaConnectorHandler) get(ctx context.Context, avn *aiven.Client, avnGen avngen.Client, obj client.Object) (*corev1.Secret, error) {
conn, err := h.convert(obj)
if err != nil {
return nil, err
}
connAtAiven, err := avn.KafkaConnectors.GetByName(ctx, conn.Spec.Project, conn.Spec.ServiceName, conn.Name)
if err != nil {
return nil, err
}
conn.Status.PluginStatus = v1alpha1.KafkaConnectorPluginStatus{
Author: connAtAiven.Plugin.Author,
Class: connAtAiven.Plugin.Class,
DocURL: connAtAiven.Plugin.DocumentationURL,
Title: connAtAiven.Plugin.Title,
Type: connAtAiven.Plugin.Type,
Version: connAtAiven.Plugin.Version,
}
connStat, err := avn.KafkaConnectors.Status(ctx, conn.Spec.Project, conn.Spec.ServiceName, conn.Name)
if err != nil {
return nil, err
}
conn.Status.State = connStat.Status.State
conn.Status.TasksStatus = v1alpha1.KafkaConnectorTasksStatus{}
for i := range connStat.Status.Tasks {
conn.Status.TasksStatus.Total++
switch connStat.Status.Tasks[i].State {
case "RUNNING":
conn.Status.TasksStatus.Running++
case "PAUSED":
conn.Status.TasksStatus.Paused++
case "UNASSIGNED":
conn.Status.TasksStatus.Unassigned++
case "FAILED":
// in case we have a failed task, we just use the last failed stacktrace
conn.Status.TasksStatus.Failed++
conn.Status.TasksStatus.StackTrace = connStat.Status.Tasks[i].Trace
default:
conn.Status.TasksStatus.Unknown++
}
}
if connStat.Status.State == "RUNNING" {
meta.SetStatusCondition(&conn.Status.Conditions,
getRunningCondition(metav1.ConditionTrue, "CheckRunning",
"Instance is running on Aiven side"))
metav1.SetMetaDataAnnotation(&conn.ObjectMeta, instanceIsRunningAnnotation, "true")
}
return nil, nil
}
func (h KafkaConnectorHandler) checkPreconditions(ctx context.Context, avn *aiven.Client, avnGen avngen.Client, obj client.Object) (bool, error) {
conn, err := h.convert(obj)
if err != nil {
return false, err
}
meta.SetStatusCondition(&conn.Status.Conditions,
getInitializedCondition("Preconditions", "Checking preconditions"))
return checkServiceIsOperational(ctx, avnGen, conn.Spec.Project, conn.Spec.ServiceName)
}
func (h KafkaConnectorHandler) convert(o client.Object) (*v1alpha1.KafkaConnector, error) {
conn, ok := o.(*v1alpha1.KafkaConnector)
if !ok {
return nil, fmt.Errorf("cannot convert object to KafkaConnector")
}
return conn, nil
}