forked from cloudnative-pg/cloudnative-pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup.go
595 lines (545 loc) · 16.3 KB
/
backup.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/*
Copyright The CloudNativePG Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
import (
"encoding/json"
"fmt"
"os"
volumesnapshot "github.com/kubernetes-csi/external-snapshotter/client/v6/apis/volumesnapshot/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
apiv1 "github.com/cloudnative-pg/cloudnative-pg/api/v1"
. "github.com/onsi/gomega" // nolint
)
// ExecuteBackup performs a backup and checks the backup status
func ExecuteBackup(
namespace,
backupFile string,
onlyTargetStandbys bool,
timeoutSeconds int,
env *TestingEnvironment,
) *apiv1.Backup {
backupName, err := env.GetResourceNameFromYAML(backupFile)
Expect(err).ToNot(HaveOccurred())
Eventually(func() error {
_, stderr, err := RunUnchecked("kubectl apply -n " + namespace + " -f " + backupFile)
if err != nil {
return fmt.Errorf("could not create backup.\nStdErr: %v\nError: %v", stderr, err)
}
return nil
}, RetryTimeout, PollingTime).Should(BeNil())
backupNamespacedName := types.NamespacedName{
Namespace: namespace,
Name: backupName,
}
backup := &apiv1.Backup{}
// Verifying backup status
Eventually(func() (apiv1.BackupPhase, error) {
err = env.Client.Get(env.Ctx, backupNamespacedName, backup)
return backup.Status.Phase, err
}, timeoutSeconds).Should(BeEquivalentTo(apiv1.BackupPhaseCompleted))
Eventually(func() (string, error) {
err = env.Client.Get(env.Ctx, backupNamespacedName, backup)
if err != nil {
return "", err
}
backupStatus := backup.GetStatus()
return backupStatus.BeginLSN, err
}, timeoutSeconds).ShouldNot(BeEmpty())
var cluster *apiv1.Cluster
Eventually(func() error {
var err error
cluster, err = env.GetCluster(namespace, backup.Spec.Cluster.Name)
return err
}, timeoutSeconds).ShouldNot(HaveOccurred())
backupStatus := backup.GetStatus()
if cluster.Spec.Backup != nil {
backupTarget := cluster.Spec.Backup.Target
if backup.Spec.Target != "" {
backupTarget = backup.Spec.Target
}
switch backupTarget {
case apiv1.BackupTargetPrimary, "":
Expect(backupStatus.InstanceID.PodName).To(BeEquivalentTo(cluster.Status.TargetPrimary))
case apiv1.BackupTargetStandby:
Expect(backupStatus.InstanceID.PodName).To(BeElementOf(cluster.Status.InstanceNames))
if onlyTargetStandbys {
Expect(backupStatus.InstanceID.PodName).NotTo(Equal(cluster.Status.TargetPrimary))
}
}
}
Expect(backupStatus.BeginWal).NotTo(BeEmpty())
Expect(backupStatus.EndLSN).NotTo(BeEmpty())
Expect(backupStatus.EndWal).NotTo(BeEmpty())
return backup
}
// CreateClusterFromBackupUsingPITR creates a cluster from backup, using the PITR
func CreateClusterFromBackupUsingPITR(
namespace,
clusterName,
backupFilePath,
targetTime string,
env *TestingEnvironment,
) (*apiv1.Cluster, error) {
backupName, err := env.GetResourceNameFromYAML(backupFilePath)
if err != nil {
return nil, err
}
storageClassName := os.Getenv("E2E_DEFAULT_STORAGE_CLASS")
restoreCluster := &apiv1.Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: clusterName,
Namespace: namespace,
},
Spec: apiv1.ClusterSpec{
Instances: 3,
StorageConfiguration: apiv1.StorageConfiguration{
Size: "1Gi",
StorageClass: &storageClassName,
},
PostgresConfiguration: apiv1.PostgresConfiguration{
Parameters: map[string]string{
"log_checkpoints": "on",
"log_lock_waits": "on",
"log_min_duration_statement": "1000",
"log_statement": "ddl",
"log_temp_files": "1024",
"log_autovacuum_min_duration": "1s",
"log_replication_commands": "on",
},
},
Bootstrap: &apiv1.BootstrapConfiguration{
Recovery: &apiv1.BootstrapRecovery{
Backup: &apiv1.BackupSource{
LocalObjectReference: apiv1.LocalObjectReference{
Name: backupName,
},
},
RecoveryTarget: &apiv1.RecoveryTarget{
TargetTime: targetTime,
},
},
},
},
}
obj, err := CreateObject(env, restoreCluster)
if err != nil {
return nil, err
}
cluster, ok := obj.(*apiv1.Cluster)
if !ok {
return nil, fmt.Errorf("created object is not of type cluster: %T, %v", obj, obj)
}
return cluster, nil
}
// CreateClusterFromExternalClusterBackupWithPITROnAzure creates a cluster on Azure, starting from an external cluster
// backup with PITR
func CreateClusterFromExternalClusterBackupWithPITROnAzure(
namespace,
externalClusterName,
sourceClusterName,
targetTime,
storageCredentialsSecretName,
azStorageAccount,
azBlobContainer string,
env *TestingEnvironment,
) (*apiv1.Cluster, error) {
storageClassName := os.Getenv("E2E_DEFAULT_STORAGE_CLASS")
destinationPath := fmt.Sprintf("https://%v.blob.core.windows.net/%v/",
azStorageAccount, azBlobContainer)
restoreCluster := &apiv1.Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: externalClusterName,
Namespace: namespace,
},
Spec: apiv1.ClusterSpec{
Instances: 3,
StorageConfiguration: apiv1.StorageConfiguration{
Size: "1Gi",
StorageClass: &storageClassName,
},
PostgresConfiguration: apiv1.PostgresConfiguration{
Parameters: map[string]string{
"log_checkpoints": "on",
"log_lock_waits": "on",
"log_min_duration_statement": "1000",
"log_statement": "ddl",
"log_temp_files": "1024",
"log_autovacuum_min_duration": "1s",
"log_replication_commands": "on",
},
},
Bootstrap: &apiv1.BootstrapConfiguration{
Recovery: &apiv1.BootstrapRecovery{
Source: sourceClusterName,
RecoveryTarget: &apiv1.RecoveryTarget{
TargetTime: targetTime,
},
},
},
ExternalClusters: []apiv1.ExternalCluster{
{
Name: sourceClusterName,
BarmanObjectStore: &apiv1.BarmanObjectStoreConfiguration{
DestinationPath: destinationPath,
BarmanCredentials: apiv1.BarmanCredentials{
Azure: &apiv1.AzureCredentials{
StorageAccount: &apiv1.SecretKeySelector{
LocalObjectReference: apiv1.LocalObjectReference{
Name: storageCredentialsSecretName,
},
Key: "ID",
},
StorageKey: &apiv1.SecretKeySelector{
LocalObjectReference: apiv1.LocalObjectReference{
Name: storageCredentialsSecretName,
},
Key: "KEY",
},
},
},
},
},
},
},
}
obj, err := CreateObject(env, restoreCluster)
if err != nil {
return nil, err
}
cluster, ok := obj.(*apiv1.Cluster)
if !ok {
return nil, fmt.Errorf("created object is not of type cluster: %T, %v", obj, obj)
}
return cluster, nil
}
// CreateClusterFromExternalClusterBackupWithPITROnMinio creates a cluster on Minio, starting from an external cluster
// backup with PITR
func CreateClusterFromExternalClusterBackupWithPITROnMinio(
namespace,
externalClusterName,
sourceClusterName,
targetTime string,
env *TestingEnvironment,
) (*apiv1.Cluster, error) {
storageClassName := os.Getenv("E2E_DEFAULT_STORAGE_CLASS")
restoreCluster := &apiv1.Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: externalClusterName,
Namespace: namespace,
},
Spec: apiv1.ClusterSpec{
Instances: 3,
StorageConfiguration: apiv1.StorageConfiguration{
Size: "1Gi",
StorageClass: &storageClassName,
},
PostgresConfiguration: apiv1.PostgresConfiguration{
Parameters: map[string]string{
"log_checkpoints": "on",
"log_lock_waits": "on",
"log_min_duration_statement": "1000",
"log_statement": "ddl",
"log_temp_files": "1024",
"log_autovacuum_min_duration": "1s",
"log_replication_commands": "on",
},
},
Bootstrap: &apiv1.BootstrapConfiguration{
Recovery: &apiv1.BootstrapRecovery{
Source: sourceClusterName,
RecoveryTarget: &apiv1.RecoveryTarget{
TargetTime: targetTime,
},
},
},
ExternalClusters: []apiv1.ExternalCluster{
{
Name: sourceClusterName,
BarmanObjectStore: &apiv1.BarmanObjectStoreConfiguration{
DestinationPath: "s3://cluster-backups/",
EndpointURL: "https://minio-service:9000",
EndpointCA: &apiv1.SecretKeySelector{
LocalObjectReference: apiv1.LocalObjectReference{
Name: "minio-server-ca-secret",
},
Key: "ca.crt",
},
BarmanCredentials: apiv1.BarmanCredentials{
AWS: &apiv1.S3Credentials{
AccessKeyIDReference: &apiv1.SecretKeySelector{
LocalObjectReference: apiv1.LocalObjectReference{
Name: "backup-storage-creds",
},
Key: "ID",
},
SecretAccessKeyReference: &apiv1.SecretKeySelector{
LocalObjectReference: apiv1.LocalObjectReference{
Name: "backup-storage-creds",
},
Key: "KEY",
},
},
},
},
},
},
},
}
obj, err := CreateObject(env, restoreCluster)
if err != nil {
return nil, err
}
cluster, ok := obj.(*apiv1.Cluster)
if !ok {
return nil, fmt.Errorf("created object is not of type cluster: %T, %v", obj, obj)
}
return cluster, nil
}
// CreateClusterFromExternalClusterBackupWithPITROnAzurite creates a cluster with Azurite, starting from an external
// cluster backup with PITR
func CreateClusterFromExternalClusterBackupWithPITROnAzurite(
namespace,
externalClusterName,
sourceClusterName,
targetTime string,
env *TestingEnvironment,
) (*apiv1.Cluster, error) {
storageClassName := os.Getenv("E2E_DEFAULT_STORAGE_CLASS")
DestinationPath := fmt.Sprintf("https://azurite:10000/storageaccountname/%v", sourceClusterName)
restoreCluster := &apiv1.Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: externalClusterName,
Namespace: namespace,
},
Spec: apiv1.ClusterSpec{
Instances: 3,
StorageConfiguration: apiv1.StorageConfiguration{
Size: "1Gi",
StorageClass: &storageClassName,
},
PostgresConfiguration: apiv1.PostgresConfiguration{
Parameters: map[string]string{
"log_checkpoints": "on",
"log_lock_waits": "on",
"log_min_duration_statement": "1000",
"log_statement": "ddl",
"log_temp_files": "1024",
"log_autovacuum_min_duration": "1s",
"log_replication_commands": "on",
},
},
Bootstrap: &apiv1.BootstrapConfiguration{
Recovery: &apiv1.BootstrapRecovery{
Source: sourceClusterName,
RecoveryTarget: &apiv1.RecoveryTarget{
TargetTime: targetTime,
},
},
},
ExternalClusters: []apiv1.ExternalCluster{
{
Name: sourceClusterName,
BarmanObjectStore: &apiv1.BarmanObjectStoreConfiguration{
DestinationPath: DestinationPath,
EndpointCA: &apiv1.SecretKeySelector{
LocalObjectReference: apiv1.LocalObjectReference{
Name: "azurite-ca-secret",
},
Key: "ca.crt",
},
BarmanCredentials: apiv1.BarmanCredentials{
Azure: &apiv1.AzureCredentials{
ConnectionString: &apiv1.SecretKeySelector{
LocalObjectReference: apiv1.LocalObjectReference{
Name: "azurite",
},
Key: "AZURE_CONNECTION_STRING",
},
},
},
},
},
},
},
}
obj, err := CreateObject(env, restoreCluster)
if err != nil {
return nil, err
}
cluster, ok := obj.(*apiv1.Cluster)
if !ok {
return nil, fmt.Errorf("created object is not of type cluster: %T, %v", obj, obj)
}
return cluster, nil
}
// ComposeAzBlobListAzuriteCmd builds the Azure storage blob list command for Azurite
func ComposeAzBlobListAzuriteCmd(clusterName, path string) string {
return fmt.Sprintf("az storage blob list --container-name %v --query \"[?contains(@.name, \\`%v\\`)].name\" "+
"--connection-string $AZURE_CONNECTION_STRING",
clusterName, path)
}
// ComposeAzBlobListCmd builds the Azure storage blob list command
func ComposeAzBlobListCmd(
configuration AzureConfiguration,
clusterName,
path string,
) string {
return fmt.Sprintf("az storage blob list --account-name %v "+
"--account-key %v "+
"--container-name %v "+
"--prefix %v/ "+
"--query \"[?contains(@.name, \\`%v\\`)].name\"",
configuration.StorageAccount, configuration.StorageKey, configuration.BlobContainer, clusterName, path)
}
// CountFilesOnAzureBlobStorage counts files on Azure Blob storage
func CountFilesOnAzureBlobStorage(
configuration AzureConfiguration,
clusterName,
path string,
) (int, error) {
azBlobListCmd := ComposeAzBlobListCmd(configuration, clusterName, path)
out, _, err := RunUnchecked(azBlobListCmd)
if err != nil {
return -1, err
}
var arr []string
err = json.Unmarshal([]byte(out), &arr)
return len(arr), err
}
// CountFilesOnAzuriteBlobStorage counts files on Azure Blob storage. using Azurite
func CountFilesOnAzuriteBlobStorage(
namespace,
clusterName,
path string,
) (int, error) {
azBlobListCmd := ComposeAzBlobListAzuriteCmd(clusterName, path)
out, _, err := RunUnchecked(fmt.Sprintf("kubectl exec -n %v az-cli "+
"-- /bin/bash -c '%v'", namespace, azBlobListCmd))
if err != nil {
return -1, err
}
var arr []string
err = json.Unmarshal([]byte(out), &arr)
return len(arr), err
}
// GetConditionsInClusterStatus get conditions values as given type from cluster object status
func GetConditionsInClusterStatus(
namespace,
clusterName string,
env *TestingEnvironment,
conditionType apiv1.ClusterConditionType,
) (*metav1.Condition, error) {
var cluster *apiv1.Cluster
var err error
cluster, err = env.GetCluster(namespace, clusterName)
if err != nil {
return nil, err
}
for _, cond := range cluster.Status.Conditions {
if cond.Type == string(conditionType) {
return &cond, nil
}
}
return nil, fmt.Errorf("no condition matching requested type found: %v", conditionType)
}
// CreateOnDemandBackupViaKubectlPlugin uses the kubectl plugin to create a backup
func CreateOnDemandBackupViaKubectlPlugin(
namespace,
clusterName,
backupName string,
target apiv1.BackupTarget,
method apiv1.BackupMethod,
) error {
command := fmt.Sprintf("kubectl cnpg backup %v -n %v", clusterName, namespace)
if backupName != "" {
command = fmt.Sprintf("%v --backup-name %v", command, backupName)
}
if target != "" {
command = fmt.Sprintf("%v --backup-target %v", command, target)
}
if method != "" {
command = fmt.Sprintf("%v --method %v", command, method)
}
_, _, err := Run(command)
return err
}
// CreateOnDemandBackup creates a Backup resource for a given cluster name
// Deprecated: Use CreateBackup.
// TODO: eradicate
func CreateOnDemandBackup(
namespace,
clusterName,
backupName string,
target apiv1.BackupTarget,
method apiv1.BackupMethod,
env *TestingEnvironment,
) (*apiv1.Backup, error) {
targetBackup := &apiv1.Backup{
ObjectMeta: metav1.ObjectMeta{
Name: backupName,
Namespace: namespace,
},
Spec: apiv1.BackupSpec{
Cluster: apiv1.LocalObjectReference{
Name: clusterName,
},
},
}
if target != "" {
targetBackup.Spec.Target = target
}
if method != "" {
targetBackup.Spec.Method = method
}
obj, err := CreateObject(env, targetBackup)
if err != nil {
return nil, err
}
backup, ok := obj.(*apiv1.Backup)
if !ok {
return nil, fmt.Errorf("created object is not of Backup type: %T %v", obj, obj)
}
return backup, nil
}
// CreateBackup creates a Backup resource for a given cluster name
func CreateBackup(
targetBackup apiv1.Backup,
env *TestingEnvironment,
) (*apiv1.Backup, error) {
obj, err := CreateObject(env, &targetBackup)
if err != nil {
return nil, err
}
backup, ok := obj.(*apiv1.Backup)
if !ok {
return nil, fmt.Errorf("created object is not of Backup type: %T %v", obj, obj)
}
return backup, nil
}
// GetVolumeSnapshot gets a VolumeSnapshot given name and namespace
func (env TestingEnvironment) GetVolumeSnapshot(
namespace,
name string,
) (*volumesnapshot.VolumeSnapshot, error) {
namespacedName := types.NamespacedName{
Namespace: namespace,
Name: name,
}
volumeSnapshot := &volumesnapshot.VolumeSnapshot{}
err := GetObject(&env, namespacedName, volumeSnapshot)
if err != nil {
return nil, err
}
return volumeSnapshot, nil
}