-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathinit.go
358 lines (320 loc) · 10.4 KB
/
init.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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package storage
import (
"context"
"fmt"
"regexp"
"strings"
"time"
ydbCredentials "github.com/ydb-platform/ydb-go-sdk/v3/credentials"
"google.golang.org/grpc/metadata"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/ydb-platform/ydb-kubernetes-operator/api/v1alpha1"
. "github.com/ydb-platform/ydb-kubernetes-operator/internal/controllers/constants" //nolint:revive,stylecheck
"github.com/ydb-platform/ydb-kubernetes-operator/internal/resources"
)
var mismatchItemConfigGenerationRegexp = regexp.MustCompile(".*mismatch.*ItemConfigGenerationProvided# " +
"0.*ItemConfigGenerationExpected# 1.*")
func (r *Reconciler) setInitPipelineStatus(
ctx context.Context,
storage *resources.StorageClusterBuilder,
) (bool, ctrl.Result, error) {
if storage.Status.State == StoragePreparing {
meta.SetStatusCondition(&storage.Status.Conditions, metav1.Condition{
Type: StorageInitializedCondition,
Status: metav1.ConditionUnknown,
Reason: ReasonInProgress,
Message: "Storage has not been initialized yet",
})
storage.Status.State = StorageInitializing
return r.updateStatus(ctx, storage, StatusUpdateRequeueDelay)
}
// This block is special internal logic that skips all Storage initialization.
if value, ok := storage.Annotations[v1alpha1.AnnotationSkipInitialization]; ok && value == v1alpha1.AnnotationValueTrue {
r.Log.Info("Storage initialization disabled (with annotation), proceed with caution")
r.Recorder.Event(
storage,
corev1.EventTypeWarning,
"SkippingInit",
"Skipping initialization due to skip annotation present, be careful!",
)
return r.setInitStorageCompleted(ctx, storage, "Storage initialization not performed because initialization is skipped")
}
if meta.IsStatusConditionTrue(storage.Status.Conditions, OldStorageInitializedCondition) {
return r.setInitStorageCompleted(ctx, storage, "Storage initialized successfully")
}
return Continue, ctrl.Result{Requeue: false}, nil
}
func (r *Reconciler) setInitStorageCompleted(
ctx context.Context,
storage *resources.StorageClusterBuilder,
message string,
) (bool, ctrl.Result, error) {
meta.SetStatusCondition(&storage.Status.Conditions, metav1.Condition{
Type: StorageInitializedCondition,
Status: metav1.ConditionTrue,
Reason: ReasonCompleted,
Message: message,
})
return r.updateStatus(ctx, storage, StatusUpdateRequeueDelay)
}
func (r *Reconciler) initializeBlobstorage(
ctx context.Context,
storage *resources.StorageClusterBuilder,
) (bool, ctrl.Result, error) {
initJob := &batchv1.Job{}
err := r.Get(ctx, types.NamespacedName{
Name: fmt.Sprintf(resources.InitJobNameFormat, storage.Name),
Namespace: storage.Namespace,
}, initJob)
//nolint:nestif
if apierrors.IsNotFound(err) {
if storage.Spec.OperatorConnection != nil {
creds, err := resources.GetYDBCredentials(ctx, storage.Unwrap(), r.Config)
if err != nil {
r.Recorder.Event(
storage,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to get YDB credentials: %s", err),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, err
}
if err := r.createOrUpdateOperatorTokenSecret(ctx, storage, creds); err != nil {
r.Recorder.Event(
storage,
corev1.EventTypeWarning,
"InitializingStorage",
fmt.Sprintf("Failed to create operator token Secret, error: %s", err),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, err
}
}
if err := r.createInitBlobstorageJob(ctx, storage); err != nil {
r.Recorder.Event(
storage,
corev1.EventTypeWarning,
"InitializingStorage",
fmt.Sprintf("Failed to create init blobstorage Job, error: %s", err),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, err
}
r.Recorder.Event(
storage,
corev1.EventTypeNormal,
"InitializingStorage",
fmt.Sprintf("Successfully created Job %s", fmt.Sprintf(resources.InitJobNameFormat, storage.Name)),
)
return Stop, ctrl.Result{RequeueAfter: StorageInitializationRequeueDelay}, nil
}
if err != nil {
r.Recorder.Event(
storage,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to get Job: %s", err),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, err
}
if initJob.Status.Succeeded > 0 {
r.Log.Info("Init Job status succeeded")
r.Recorder.Event(
storage,
corev1.EventTypeNormal,
"InitializingStorage",
"Storage initialized successfully",
)
return r.setInitStorageCompleted(ctx, storage, "Storage initialized successfully")
}
var conditionFailed bool
for _, condition := range initJob.Status.Conditions {
if condition.Type == batchv1.JobFailed {
conditionFailed = true
break
}
}
initialized, err := r.checkFailedJob(ctx, storage, initJob)
if err != nil {
r.Recorder.Event(
storage,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to check logs for initBlobstorage Job: %s", err),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, err
}
if initialized {
r.Log.Info("Storage is already initialized, continuing...")
r.Recorder.Event(
storage,
corev1.EventTypeNormal,
"InitializingStorage",
"Storage initialization attempted and skipped, storage already initialized",
)
if err := r.Delete(ctx, initJob, client.PropagationPolicy(metav1.DeletePropagationForeground)); err != nil {
r.Recorder.Event(
storage,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to delete Job: %s", err),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, err
}
return r.setInitStorageCompleted(ctx, storage, "Storage already initialized")
}
if initJob.Status.Failed == *initJob.Spec.BackoffLimit || conditionFailed {
r.Recorder.Event(
storage,
corev1.EventTypeWarning,
"InitializingStorage",
"Failed initBlobstorage Job, check Pod logs for additional info",
)
meta.SetStatusCondition(&storage.Status.Conditions, metav1.Condition{
Type: StorageInitializedCondition,
Status: metav1.ConditionFalse,
Reason: ReasonInProgress,
})
if err := r.Delete(ctx, initJob, client.PropagationPolicy(metav1.DeletePropagationForeground)); err != nil {
r.Recorder.Event(
storage,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to delete initBlobstorage Job: %s", err),
)
return Stop, ctrl.Result{RequeueAfter: DefaultRequeueDelay}, err
}
return r.updateStatus(ctx, storage, StatusUpdateRequeueDelay)
}
r.Recorder.Event(
storage,
corev1.EventTypeNormal,
"InitializingStorage",
fmt.Sprintf("Waiting for Job %s status update", initJob.Name),
)
return Stop, ctrl.Result{RequeueAfter: StorageInitializationRequeueDelay}, nil
}
func (r *Reconciler) checkFailedJob(
ctx context.Context,
storage *resources.StorageClusterBuilder,
job *batchv1.Job,
) (bool, error) {
podList := &corev1.PodList{}
opts := []client.ListOption{
client.InNamespace(storage.Namespace),
client.MatchingLabels{
"job-name": job.Name,
},
}
if err := r.List(ctx, podList, opts...); err != nil {
r.Recorder.Event(
storage,
corev1.EventTypeWarning,
"ControllerError",
fmt.Sprintf("Failed to list pods for Job: %s", err),
)
return false, fmt.Errorf("failed to list pods for checkFailedJob, error: %w", err)
}
for _, pod := range podList.Items {
if pod.Status.Phase == corev1.PodFailed {
clientset, err := kubernetes.NewForConfig(r.Config)
if err != nil {
return false, fmt.Errorf("failed to initialize clientset for checkFailedJob, error: %w", err)
}
podLogs, err := getPodLogs(ctx, clientset, storage.Namespace, pod.Name)
if err != nil {
return false, fmt.Errorf("failed to get pod logs for checkFailedJob, error: %w", err)
}
if mismatchItemConfigGenerationRegexp.MatchString(podLogs) {
return true, nil
}
}
}
return false, nil
}
func getPodLogs(ctx context.Context, clientset *kubernetes.Clientset, namespace, name string) (string, error) {
var logsBuilder strings.Builder
streamCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
podLogs, err := clientset.CoreV1().
Pods(namespace).
GetLogs(name, &corev1.PodLogOptions{}).
Stream(streamCtx)
if err != nil {
return "", fmt.Errorf("failed to stream GetLogs from pod %s/%s, error: %w", namespace, name, err)
}
defer podLogs.Close()
buf := make([]byte, 4096)
for {
numBytes, err := podLogs.Read(buf)
if numBytes == 0 && err != nil {
break
}
logsBuilder.Write(buf[:numBytes])
}
return logsBuilder.String(), nil
}
func shouldIgnoreJobUpdate() resources.IgnoreChangesFunction {
return func(oldObj, newObj runtime.Object) bool {
if _, ok := oldObj.(*batchv1.Job); ok {
return true
}
return false
}
}
func (r *Reconciler) createInitBlobstorageJob(
ctx context.Context,
storage *resources.StorageClusterBuilder,
) error {
builder := storage.GetInitJobBuilder()
newResource := builder.Placeholder(storage)
_, err := resources.CreateOrUpdateOrMaybeIgnore(ctx, r.Client, newResource, func() error {
var err error
err = builder.Build(newResource)
if err != nil {
return err
}
err = ctrl.SetControllerReference(storage.Unwrap(), newResource, r.Scheme)
if err != nil {
return err
}
return nil
}, shouldIgnoreJobUpdate())
return err
}
func (r *Reconciler) createOrUpdateOperatorTokenSecret(
ctx context.Context,
storage *resources.StorageClusterBuilder,
creds ydbCredentials.Credentials,
) error {
ydbCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
token, err := creds.Token(
metadata.AppendToOutgoingContext(ydbCtx, "x-ydb-database", storage.Spec.Domain),
)
if err != nil {
return fmt.Errorf("failed to get token from ydb credentials for createOrUpdateOperatorTokenSecret, error: %w", err)
}
builder := resources.GetOperatorTokenSecretBuilder(storage, token)
newResource := builder.Placeholder(storage)
_, err = resources.CreateOrUpdateOrMaybeIgnore(ctx, r.Client, newResource, func() error {
var err error
err = builder.Build(newResource)
if err != nil {
return err
}
err = ctrl.SetControllerReference(storage.Unwrap(), newResource, r.Scheme)
if err != nil {
return err
}
return nil
}, resources.DoNotIgnoreChanges())
return err
}