/
mover.go
430 lines (381 loc) · 14.3 KB
/
mover.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
Copyright 2021 The VolSync authors.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package rclone
import (
"context"
"errors"
"path"
"github.com/go-logr/logr"
snapv1 "github.com/kubernetes-csi/external-snapshotter/client/v6/apis/volumesnapshot/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/events"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
volsyncv1alpha1 "github.com/backube/volsync/api/v1alpha1"
vserrors "github.com/backube/volsync/controllers/errors"
"github.com/backube/volsync/controllers/mover"
"github.com/backube/volsync/controllers/utils"
"github.com/backube/volsync/controllers/volumehandler"
)
const (
mountPath = "/data"
dataVolumeName = "data"
rcloneSecret = "rclone-secret"
rcloneCAMountPath = "/customCA"
rcloneCAFilename = "ca.crt"
)
// Mover is the reconciliation logic for the Rclone-based data mover.
type Mover struct {
client client.Client
logger logr.Logger
eventRecorder events.EventRecorder
owner client.Object
vh *volumehandler.VolumeHandler
saHandler utils.SAHandler
containerImage string
rcloneConfigSection *string
rcloneDestPath *string
rcloneConfig *string
isSource bool
paused bool
mainPVCName *string
customCASpec volsyncv1alpha1.CustomCASpec
privileged bool // true if the mover should have elevated privileges
latestMoverStatus *volsyncv1alpha1.MoverStatus
moverConfig volsyncv1alpha1.MoverConfig
}
var _ mover.Mover = &Mover{}
// All object types that are temporary/per-iteration should be listed here. The
// individual objects to be cleaned up must also be marked.
var cleanupTypes = []client.Object{
&corev1.PersistentVolumeClaim{},
&snapv1.VolumeSnapshot{},
&batchv1.Job{},
}
func (m *Mover) Name() string { return "rclone" }
func (m *Mover) Synchronize(ctx context.Context) (mover.Result, error) {
var err error
err = m.validateSpec()
if err != nil {
return mover.InProgress(), err
}
// Validate rCloneConfig Secret
rcloneConfigSecret, err := m.validateRcloneConfig(ctx)
if rcloneConfigSecret == nil || err != nil {
return mover.InProgress(), err
}
// Allocate temporary data PVC
var dataPVC *corev1.PersistentVolumeClaim
if m.isSource {
dataPVC, err = m.ensureSourcePVC(ctx)
} else {
dataPVC, err = m.ensureDestinationPVC(ctx)
}
if dataPVC == nil || err != nil {
return mover.InProgress(), err
}
// Prepare ServiceAccount, role, rolebinding
sa, err := m.saHandler.Reconcile(ctx, m.logger)
if sa == nil || err != nil {
return mover.InProgress(), err
}
// Validate custom CA if in spec
customCAObj, err := utils.ValidateCustomCA(ctx, m.client, m.logger,
m.owner.GetNamespace(), m.customCASpec)
// nil customCAObj is ok (indicates we're not using a custom CA)
if err != nil {
return mover.InProgress(), err
}
// Start mover Job
job, err := m.ensureJob(ctx, dataPVC, sa, rcloneConfigSecret, customCAObj)
if job == nil || err != nil {
return mover.InProgress(), err
}
// On the destination, preserve the image and return it
if !m.isSource {
image, err := m.vh.EnsureImage(ctx, m.logger, dataPVC)
if image == nil || err != nil {
return mover.InProgress(), err
}
return mover.CompleteWithImage(image), nil
}
// On the source, just signal completion
return mover.Complete(), nil
}
func (m *Mover) Cleanup(ctx context.Context) (mover.Result, error) {
m.logger.V(1).Info("Starting cleanup", "m.mainPVCName", m.mainPVCName, "m.isSource", m.isSource)
if !m.isSource {
m.logger.V(1).Info("removing snapshot annotations from pvc")
// Cleanup the snapshot annotation on pvc for replicationDestination scenario so that
// on the next sync (if snapshot CopyMethod is being used) a new snapshot will be created rather than re-using
_, destPVCName := m.getDestinationPVCName()
err := m.vh.RemoveSnapshotAnnotationFromPVC(ctx, m.logger, destPVCName)
if err != nil {
return mover.InProgress(), err
}
}
err := utils.CleanupObjects(ctx, m.client, m.logger, m.owner, cleanupTypes)
if err != nil {
return mover.InProgress(), err
}
m.logger.V(1).Info("Cleanup complete")
return mover.Complete(), nil
}
func (m *Mover) ensureSourcePVC(ctx context.Context) (*corev1.PersistentVolumeClaim, error) {
srcPVC := &corev1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: *m.mainPVCName,
Namespace: m.owner.GetNamespace(),
},
}
if err := m.client.Get(ctx, client.ObjectKeyFromObject(srcPVC), srcPVC); err != nil {
m.logger.Error(err, "unable to get source PVC", "PVC", client.ObjectKeyFromObject(srcPVC))
return nil, err
}
dataName := mover.VolSyncPrefix + m.owner.GetName() + "-src"
pvc, err := m.vh.EnsurePVCFromSrc(ctx, m.logger, srcPVC, dataName, true)
if err != nil {
// If the error was a copy TriggerTimeoutError, update the latestMoverStatus to indicate error
var copyTriggerTimeoutError *vserrors.CopyTriggerTimeoutError
if errors.As(err, ©TriggerTimeoutError) {
utils.UpdateMoverStatusFailed(m.latestMoverStatus, copyTriggerTimeoutError.Error())
// Don't return error - we want to keep reconciling at the normal in-progress rate
// but just indicate in the latestMoverStatus that there is an error (we've been waiting
// for the user to update the copy Trigger for too long)
return pvc, nil
}
}
return pvc, nil
}
// this is so far is common to rclone & restic
func (m *Mover) ensureDestinationPVC(ctx context.Context) (*corev1.PersistentVolumeClaim, error) {
isProvidedPVC, dataPVCName := m.getDestinationPVCName()
if isProvidedPVC {
return m.vh.UseProvidedPVC(ctx, dataPVCName)
}
// Need to allocate the incoming data volume
return m.vh.EnsureNewPVC(ctx, m.logger, dataPVCName)
}
func (m *Mover) getDestinationPVCName() (bool, string) {
if m.mainPVCName == nil {
newPvcName := mover.VolSyncPrefix + m.owner.GetName() + "-dest"
return false, newPvcName
}
return true, *m.mainPVCName
}
//nolint:funlen
func (m *Mover) ensureJob(ctx context.Context, dataPVC *corev1.PersistentVolumeClaim,
sa *corev1.ServiceAccount, rcloneConfigSecret *corev1.Secret,
customCAObj utils.CustomCAObject) (*batchv1.Job, error) {
dir := "dst"
direction := "destination"
readOnlyVolume := false
if m.isSource {
dir = "src"
direction = "source"
// Set read-only for volume in source mover job spec if the PVC only supports read-only
readOnlyVolume = utils.PvcIsReadOnly(dataPVC)
}
job := &batchv1.Job{
ObjectMeta: metav1.ObjectMeta{
Name: mover.VolSyncPrefix + "rclone-" + dir + "-" + m.owner.GetName(),
Namespace: m.owner.GetNamespace(),
},
}
logger := m.logger.WithValues("job", client.ObjectKeyFromObject(job))
_, err := utils.CreateOrUpdateDeleteOnImmutableErr(ctx, m.client, job, logger, func() error {
if err := ctrl.SetControllerReference(m.owner, job, m.client.Scheme()); err != nil {
logger.Error(err, utils.ErrUnableToSetControllerRef)
return err
}
utils.SetOwnedByVolSync(job)
utils.MarkForCleanup(m.owner, job)
job.Spec.Template.ObjectMeta.Name = job.Name
utils.SetOwnedByVolSync(&job.Spec.Template)
backoffLimit := int32(2) //TODO: backofflimit was 8 for restic
job.Spec.BackoffLimit = &backoffLimit
parallelism := int32(1)
if m.paused {
parallelism = int32(0)
}
job.Spec.Parallelism = ¶llelism
envVars := []corev1.EnvVar{}
// Rclone env vars if they are in the secret
envVars = utils.AppendRCloneEnvVars(rcloneConfigSecret, envVars)
defaultEnvVars := []corev1.EnvVar{
{Name: "RCLONE_CONFIG", Value: "/rclone-config/rclone.conf"},
{Name: "RCLONE_DEST_PATH", Value: *m.rcloneDestPath},
{Name: "DIRECTION", Value: direction},
{Name: "MOUNT_PATH", Value: mountPath},
{Name: "RCLONE_CONFIG_SECTION", Value: *m.rcloneConfigSection},
}
// Add our defaults after RCLONE_ env vars so any duplicates will be
// overridden by the defaults
envVars = append(envVars, defaultEnvVars...)
// Cluster-wide proxy settings
envVars = utils.AppendEnvVarsForClusterWideProxy(envVars)
job.Spec.Template.Spec.Containers = []corev1.Container{{
Name: "rclone",
Env: envVars,
Command: []string{"/bin/bash", "-c", "/mover-rclone/active.sh"},
Image: m.containerImage,
SecurityContext: &corev1.SecurityContext{
AllowPrivilegeEscalation: ptr.To(false),
Capabilities: &corev1.Capabilities{
Drop: []corev1.Capability{"ALL"},
},
Privileged: ptr.To(false),
ReadOnlyRootFilesystem: ptr.To(true),
},
VolumeMounts: []corev1.VolumeMount{
{Name: dataVolumeName, MountPath: mountPath},
{Name: rcloneSecret, MountPath: "/rclone-config/"},
{Name: "tempdir", MountPath: "/tmp"},
},
}}
job.Spec.Template.Spec.RestartPolicy = corev1.RestartPolicyNever
job.Spec.Template.Spec.ServiceAccountName = sa.Name
job.Spec.Template.Spec.Volumes = []corev1.Volume{
{Name: dataVolumeName, VolumeSource: corev1.VolumeSource{
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: dataPVC.Name,
ReadOnly: readOnlyVolume,
}},
},
{Name: rcloneSecret, VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: rcloneConfigSecret.Name,
DefaultMode: ptr.To[int32](0600),
}},
},
{Name: "tempdir", VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{
Medium: corev1.StorageMediumMemory,
}},
},
}
if m.vh.IsCopyMethodDirect() {
affinity, err := utils.AffinityFromVolume(ctx, m.client, logger, dataPVC)
if err != nil {
logger.Error(err, "unable to determine proper affinity", "PVC", client.ObjectKeyFromObject(dataPVC))
return err
}
job.Spec.Template.Spec.NodeSelector = affinity.NodeSelector
job.Spec.Template.Spec.Tolerations = affinity.Tolerations
}
logger.V(1).Info("Job has PVC", "PVC", dataPVC, "DS", dataPVC.Spec.DataSource)
podSpec := &job.Spec.Template.Spec
if customCAObj != nil {
// Tell mover where to find the cert
podSpec.Containers[0].Env = append(podSpec.Containers[0].Env, corev1.EnvVar{
Name: "CUSTOM_CA",
Value: path.Join(rcloneCAMountPath, rcloneCAFilename),
})
// Mount the custom CA certificate
podSpec.Containers[0].VolumeMounts =
append(podSpec.Containers[0].VolumeMounts, corev1.VolumeMount{
Name: "custom-ca",
MountPath: rcloneCAMountPath,
})
podSpec.Volumes = append(podSpec.Volumes, corev1.Volume{
Name: "custom-ca",
VolumeSource: customCAObj.GetVolumeSource(rcloneCAFilename),
})
}
// Update the job securityContext, podLabels and resourceRequirements from moverConfig (if specified)
utils.UpdatePodTemplateSpecFromMoverConfig(&job.Spec.Template, m.moverConfig, corev1.ResourceRequirements{})
// Adjust the Job based on whether the mover should be running as privileged
logger.Info("mover permissions", "privileged-mover", m.privileged)
if m.privileged {
podSpec.Containers[0].Env = append(podSpec.Containers[0].Env, corev1.EnvVar{
Name: "PRIVILEGED_MOVER",
Value: "1",
})
podSpec.Containers[0].SecurityContext.Capabilities.Add = []corev1.Capability{
"DAC_OVERRIDE", // Read/write all files
"CHOWN", // chown files
"FOWNER", // Set permission bits & times
}
podSpec.Containers[0].SecurityContext.RunAsUser = ptr.To[int64](0)
} else {
podSpec.Containers[0].Env = append(podSpec.Containers[0].Env, corev1.EnvVar{
Name: "PRIVILEGED_MOVER",
Value: "0",
})
}
return nil
})
// If Job had failed, delete it so it can be recreated
if job.Status.Failed >= *job.Spec.BackoffLimit {
// Update status with mover logs from failed job
utils.UpdateMoverStatusForFailedJob(ctx, m.logger, m.latestMoverStatus, job.GetName(), job.GetNamespace(),
utils.AllLines)
logger.Info("deleting job -- backoff limit reached")
err = m.client.Delete(ctx, job, client.PropagationPolicy(metav1.DeletePropagationBackground))
return nil, err
}
if err != nil {
logger.Error(err, "reconcile failed")
return nil, err
}
// Stop here if the job hasn't completed yet
if job.Status.Succeeded == 0 {
return nil, nil
}
logger.Info("job completed")
// update status with mover logs from successful job
utils.UpdateMoverStatusForSuccessfulJob(ctx, m.logger, m.latestMoverStatus, job.GetName(), job.GetNamespace(),
LogLineFilterSuccess)
// We only continue reconciling if the rclone job has completed
return job, nil
}
func (m *Mover) validateSpec() error {
m.logger.V(1).Info("Initiate Rclone Spec validation")
if m.rcloneConfig == nil || len(*m.rcloneConfig) == 0 {
err := errors.New("unable to get Rclone config secret name")
m.logger.Error(err, "Rclone Spec validation error")
return err
}
if m.rcloneConfigSection == nil || len(*m.rcloneConfigSection) == 0 {
err := errors.New("unable to get Rclone config section name")
m.logger.Error(err, "Rclone Spec validation error")
return err
}
if m.rcloneDestPath == nil || len(*m.rcloneDestPath) == 0 {
err := errors.New("unable to get Rclone destination name")
m.logger.Error(err, "Rclone Spec validation error")
return err
}
m.logger.V(1).Info("Rclone Spec validation complete.")
return nil
}
func (m *Mover) validateRcloneConfig(ctx context.Context) (*corev1.Secret, error) {
// Validate user provided rcloneConfig Secret exists and has the proper field
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: *m.rcloneConfig,
Namespace: m.owner.GetNamespace(),
},
}
logger := m.logger.WithValues("rcloneConfig Secret", client.ObjectKeyFromObject(secret))
if err := utils.GetAndValidateSecret(ctx, m.client, logger, secret, "rclone.conf"); err != nil {
logger.Error(err, "Rclone config secret does not contain the proper fields")
return nil, err
}
m.logger.Info("RcloneConfig reconciled")
return secret, nil
}