-
Notifications
You must be signed in to change notification settings - Fork 75
/
main.go
1421 lines (1298 loc) · 39.5 KB
/
main.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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"archive/zip"
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
const (
backupBaseDir = "/backup"
defaultBackupRetries = 4
clusterStateExtension = "rkestate"
compressedExtension = "zip"
contentType = "application/zip"
k8sBaseDir = "/etc/kubernetes"
defaultS3Retries = 3
serverPort = "2379"
s3Endpoint = "s3.amazonaws.com"
tmpStateFilePath = "/tmp/cluster.rkestate"
failureInterval = 15 * time.Second
)
var (
backupRetries uint = defaultBackupRetries
s3Retries uint = defaultS3Retries
)
var commonFlags = []cli.Flag{
cli.StringFlag{
Name: "endpoints",
Usage: "Etcd endpoints",
Value: "127.0.0.1:2379",
},
cli.BoolFlag{
Name: "debug",
Usage: "Verbose logging information for debugging purposes",
EnvVar: "RANCHER_DEBUG",
},
cli.StringFlag{
Name: "name",
Usage: "Backup name to take once",
},
cli.StringFlag{
Name: "cacert",
Usage: "Etcd CA client certificate path",
EnvVar: "ETCD_CACERT",
},
cli.StringFlag{
Name: "cert",
Usage: "Etcd client certificate path",
EnvVar: "ETCD_CERT",
},
cli.StringFlag{
Name: "key",
Usage: "Etcd client key path",
EnvVar: "ETCD_KEY",
},
cli.StringFlag{
Name: "local-endpoint",
Usage: "Local backup download endpoint",
EnvVar: "LOCAL_ENDPOINT",
},
cli.BoolFlag{
Name: "s3-backup",
Usage: "Backup etcd snapshot to your s3 server, set true or false",
EnvVar: "S3_BACKUP",
},
cli.StringFlag{
Name: "s3-endpoint",
Usage: "Specify s3 endpoint address",
EnvVar: "S3_ENDPOINT",
},
cli.StringFlag{
Name: "s3-accessKey",
Usage: "Specify s3 access key",
EnvVar: "S3_ACCESS_KEY",
},
cli.StringFlag{
Name: "s3-secretKey",
Usage: "Specify s3 secret key",
EnvVar: "S3_SECRET_KEY",
},
cli.StringFlag{
Name: "s3-bucketName",
Usage: "Specify s3 bucket name",
EnvVar: "S3_BUCKET_NAME",
},
cli.StringFlag{
Name: "s3-region",
Usage: "Specify s3 bucket region",
EnvVar: "S3_BUCKET_REGION",
},
cli.StringFlag{
Name: "s3-endpoint-ca",
Usage: "Specify custom CA for S3 endpoint. Can be a file path or a base64 string",
EnvVar: "S3_ENDPOINT_CA",
},
cli.StringFlag{
Name: "s3-folder",
Usage: "Specify folder for snapshots",
EnvVar: "S3_FOLDER",
},
}
var deleteFlags = []cli.Flag{
cli.StringFlag{
Name: "name",
Usage: "snapshot name to delete",
},
cli.BoolFlag{
Name: "s3-backup",
Usage: "delete snapshot from s3",
},
cli.BoolFlag{
Name: "cleanup",
Usage: "delete uncompressed files only",
},
cli.StringFlag{
Name: "s3-endpoint",
Usage: "Specify s3 endpoint address",
EnvVar: "S3_ENDPOINT",
},
cli.StringFlag{
Name: "s3-accessKey",
Usage: "Specify s3 access key",
EnvVar: "S3_ACCESS_KEY",
},
cli.StringFlag{
Name: "s3-secretKey",
Usage: "Specify s3 secret key",
EnvVar: "S3_SECRET_KEY",
},
cli.StringFlag{
Name: "s3-bucketName",
Usage: "Specify s3 bucket name",
EnvVar: "S3_BUCKET_NAME",
},
cli.StringFlag{
Name: "s3-region",
Usage: "Specify s3 bucket region",
EnvVar: "S3_BUCKET_REGION",
},
cli.StringFlag{
Name: "s3-endpoint-ca",
Usage: "Specify custom CA for S3 endpoint. Can be a file path or a base64 string",
EnvVar: "S3_ENDPOINT_CA",
},
cli.StringFlag{
Name: "s3-folder",
Usage: "Specify folder for snapshots",
EnvVar: "S3_FOLDER",
},
}
type backupConfig struct {
Backup bool
Endpoint string
AccessKey string
SecretKey string
BucketName string
Region string
EndpointCA string
Folder string
}
func init() {
log.SetOutput(os.Stderr)
}
func main() {
err := os.Setenv("ETCDCTL_API", "3")
if err != nil {
log.Fatal(err)
}
app := cli.NewApp()
app.Name = "Etcd Wrapper"
app.Usage = "Utility services for Etcd cluster backup"
app.Commands = []cli.Command{
BackupCommand(),
}
err = app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func BackupCommand() cli.Command {
snapshotFlags := []cli.Flag{
cli.DurationFlag{
Name: "creation",
Usage: "Create backups after this time interval in minutes",
Value: 5 * time.Minute,
},
cli.DurationFlag{
Name: "retention",
Usage: "Retain backups within this time interval in hours",
Value: 24 * time.Hour,
},
cli.BoolFlag{
Name: "once",
Usage: "Take backup only once",
},
}
snapshotFlags = append(snapshotFlags, commonFlags...)
return cli.Command{
Name: "etcd-backup",
Usage: "Perform etcd backup tools",
Subcommands: []cli.Command{
{
Name: "save",
Usage: "Take snapshot on all etcd hosts and backup to s3 compatible storage",
Flags: append(snapshotFlags, cli.UintFlag{
Name: "backup-retries",
Usage: "Number of times to attempt the backup",
Destination: &backupRetries,
}, cli.UintFlag{
Name: "s3-retries",
Usage: "Number of times to attempt the upload to s3",
Destination: &s3Retries,
}),
Action: SaveBackupAction,
},
{
Name: "delete",
Usage: "Delete snapshot from etcd hosts or s3 compatible storage",
Flags: deleteFlags,
Action: DeleteBackupAction,
},
{
Name: "download",
Usage: "Download specified snapshot from s3 compatible storage or another local endpoint",
Flags: commonFlags,
Action: DownloadBackupAction,
},
{
Name: "extractstatefile",
Usage: "Extract statefile for specified snapshot (if it is included in the archive)",
Flags: snapshotFlags,
Action: ExtractStateFileAction,
},
{
Name: "serve",
Usage: "Provide HTTPS endpoint to pull local snapshot",
Flags: []cli.Flag{
cli.StringFlag{
Name: "name",
Usage: "Backup name to take once",
},
cli.StringFlag{
Name: "cacert",
Usage: "Etcd CA client certificate path",
EnvVar: "ETCD_CACERT",
},
cli.StringFlag{
Name: "cert",
Usage: "Etcd client certificate path",
EnvVar: "ETCD_CERT",
},
cli.StringFlag{
Name: "key",
Usage: "Etcd client key path",
EnvVar: "ETCD_KEY",
},
},
Action: ServeBackupAction,
},
},
}
}
func SetLoggingLevel(debug bool) {
if debug {
log.SetLevel(log.DebugLevel)
log.Debug("Log level set to debug")
} else {
log.SetLevel(log.InfoLevel)
}
}
func SaveBackupAction(c *cli.Context) error {
SetLoggingLevel(c.Bool("debug"))
creationPeriod := c.Duration("creation")
retentionPeriod := c.Duration("retention")
etcdCert := c.String("cert")
etcdCACert := c.String("cacert")
etcdKey := c.String("key")
etcdEndpoints := c.String("endpoints")
if creationPeriod == 0 || retentionPeriod == 0 {
log.WithFields(log.Fields{
"creation": creationPeriod,
"retention": retentionPeriod,
}).Errorf("Creation period and/or retention are not set")
return fmt.Errorf("Creation period and/or retention are not set")
}
if len(etcdCert) == 0 || len(etcdCACert) == 0 || len(etcdKey) == 0 {
log.WithFields(log.Fields{
"etcdCert": etcdCert,
"etcdCACert": etcdCACert,
"etcdKey": etcdKey,
}).Errorf("Failed to find etcd cert or key paths")
return fmt.Errorf("Failed to find etcd cert or key paths")
}
s3Backup := c.Bool("s3-backup")
bc := &backupConfig{
Backup: s3Backup,
Endpoint: c.String("s3-endpoint"),
AccessKey: c.String("s3-accessKey"),
SecretKey: c.String("s3-secretKey"),
BucketName: c.String("s3-bucketName"),
Region: c.String("s3-region"),
EndpointCA: c.String("s3-endpoint-ca"),
Folder: c.String("s3-folder"),
}
if c.Bool("once") {
backupName := c.String("name")
log.WithFields(log.Fields{
"name": backupName,
}).Info("Initializing Onetime Backup")
compressedFilePath, err := CreateBackup(backupName, etcdCACert, etcdCert, etcdKey, etcdEndpoints, backupRetries)
if err != nil {
return err
}
if bc.Backup {
err = CreateS3Backup(backupName, compressedFilePath, bc)
if err != nil {
return err
}
}
prefix := getNamePrefix(backupName)
// we only clean named backups if we have a retention period and a cluster name prefix
if retentionPeriod != 0 && len(prefix) != 0 {
if err := DeleteNamedBackups(retentionPeriod, prefix); err != nil {
return err
}
}
return nil
}
log.WithFields(log.Fields{
"creation": creationPeriod,
"retention": retentionPeriod,
}).Info("Initializing Rolling Backups")
backupTicker := time.NewTicker(creationPeriod)
for {
select {
case backupTime := <-backupTicker.C:
backupName := fmt.Sprintf("%s_etcd", backupTime.Format(time.RFC3339))
err := retrieveAndWriteStatefile(backupName)
if err != nil {
// An error on statefile retrieval is not a reason to bail out
// Having a snapshot without a statefile is more valuable than not having a snapshot at all
log.WithFields(log.Fields{
"name": backupName,
"error": err,
}).Warn("Error while trying to retrieve cluster state from cluster")
}
compressedFilePath, err := CreateBackup(backupName, etcdCACert, etcdCert, etcdKey, etcdEndpoints, backupRetries)
if err != nil {
continue
}
DeleteBackups(backupTime, retentionPeriod)
if !bc.Backup {
continue
}
err = CreateS3Backup(backupName, compressedFilePath, bc)
if err != nil {
continue
}
DeleteS3Backups(backupTime, retentionPeriod, bc)
}
}
}
func minioClientFromConfig(bc *backupConfig) (*minio.Client, error) {
client, err := setS3Service(bc, true)
if err != nil {
log.WithFields(log.Fields{
"s3-endpoint": bc.Endpoint,
"s3-bucketName": bc.BucketName,
"s3-accessKey": bc.AccessKey,
"s3-region": bc.Region,
"s3-endpoint-ca": bc.EndpointCA,
"s3-folder": bc.Folder,
}).Errorf("failed to set s3 server: %s", err)
return nil, fmt.Errorf("failed to set s3 server: %+v", err)
}
return client, nil
}
func CreateBackup(backupName, etcdCACert, etcdCert, etcdKey, endpoints string, backupRetries uint) (compressedFilePath string, err error) {
backupFile := fmt.Sprintf("%s/%s", backupBaseDir, backupName)
stateFile := fmt.Sprintf("%s/%s.%s", k8sBaseDir, backupName, clusterStateExtension)
var data []byte
for retries := uint(0); retries <= backupRetries; retries++ {
if retries > 0 {
time.Sleep(failureInterval)
}
// check if the cluster is healthy
cmd := exec.Command("etcdctl",
fmt.Sprintf("--endpoints=%s", endpoints),
"--cacert="+etcdCACert,
"--cert="+etcdCert,
"--key="+etcdKey,
"endpoint", "health")
data, err = cmd.CombinedOutput()
if strings.Contains(string(data), "unhealthy") {
log.WithFields(log.Fields{
"error": err,
"data": string(data),
}).Warn("Checking member health failed from etcd member")
err = fmt.Errorf("%s: %v", err, string(data))
continue
}
cmd = exec.Command("etcdctl",
fmt.Sprintf("--endpoints=%s", endpoints),
"--cacert="+etcdCACert,
"--cert="+etcdCert,
"--key="+etcdKey,
"snapshot", "save", backupFile)
startTime := time.Now()
data, err = cmd.CombinedOutput()
endTime := time.Now()
if err != nil {
log.WithFields(log.Fields{
"attempt": retries + 1,
"error": err,
"data": string(data),
}).Warn("Backup failed")
err = fmt.Errorf("%s: %v", err, string(data))
continue
}
// Determine how many files need to be in the compressed file
// 1. the compressed file
toCompressFiles := []string{backupFile}
// 2. the state file if present
if _, err = os.Stat(stateFile); err == nil {
toCompressFiles = append(toCompressFiles, stateFile)
}
// Create compressed file
compressedFilePath, err = compressFiles(backupFile, toCompressFiles)
if err != nil {
log.WithFields(log.Fields{
"attempt": retries + 1,
"error": err,
"data": string(data),
}).Warn("Compressing backup failed")
continue
}
// Remove the original file after successfully compressing it
err = os.Remove(backupFile)
if err != nil {
log.WithFields(log.Fields{
"attempt": retries + 1,
"error": err,
"data": string(data),
}).Warn("Removing uncompressed snapshot file failed")
continue
}
// Remove the state file after successfully compressing it
if _, err = os.Stat(stateFile); err == nil {
err = os.Remove(stateFile)
if err != nil {
log.WithFields(log.Fields{
"attempt": retries + 1,
"error": err,
"data": string(data),
}).Warn("Removing statefile failed")
}
}
log.WithFields(log.Fields{
"name": backupName,
"runtime": endTime.Sub(startTime),
}).Info("Created local backup")
if err = os.Chmod(compressedFilePath, 0600); err != nil {
log.WithFields(log.Fields{
"attempt": retries + 1,
"error": err,
"data": string(data),
}).Warn("changing permission of the compressed snapshot failed")
continue
}
break
}
return
}
func CreateS3Backup(backupName, compressedFilePath string, bc *backupConfig) error {
// If the minio client doesn't work now, it won't after retrying
client, err := minioClientFromConfig(bc)
if err != nil {
return err
}
compressedFile := filepath.Base(compressedFilePath)
// If folder is specified, prefix the file with the folder
if len(bc.Folder) != 0 {
compressedFile = fmt.Sprintf("%s/%s", bc.Folder, compressedFile)
}
// check if it exists already in the bucket, and if versioning is disabled on the bucket. If an error is detected,
// assume we aren't privy to that information and do multiple uploads anyway.
info, _ := client.StatObject(context.TODO(), bc.BucketName, compressedFile, minio.StatObjectOptions{})
if info.Size != 0 {
versioning, _ := client.GetBucketVersioning(context.TODO(), bc.BucketName)
if !versioning.Enabled() {
log.WithFields(log.Fields{
"name": backupName,
}).Info("Skipping upload to s3 because snapshot already exists and versioning is not enabled for the bucket")
return nil
}
}
err = uploadBackupFile(client, bc.BucketName, compressedFile, compressedFilePath, s3Retries)
if err != nil {
return err
}
return nil
}
func DeleteBackups(backupTime time.Time, retentionPeriod time.Duration) {
files, err := os.ReadDir(backupBaseDir)
if err != nil {
log.WithFields(log.Fields{
"dir": backupBaseDir,
"error": err,
}).Warn("Can't read backup directory")
}
cutoffTime := backupTime.Add(retentionPeriod * -1)
for _, file := range files {
if file.IsDir() {
log.WithFields(log.Fields{
"name": file.Name(),
}).Warn("Ignored directory, expecting file")
continue
}
backupTime, err2 := time.Parse(time.RFC3339, strings.Split(file.Name(), "_")[0])
if err2 != nil {
log.WithFields(log.Fields{
"name": file.Name(),
"error": err2,
}).Warn("Couldn't parse backup")
} else if backupTime.Before(cutoffTime) {
_ = deleteBackup(file.Name())
}
}
}
func deleteBackup(fileName string) error {
toDelete := fmt.Sprintf("%s/%s", backupBaseDir, path.Base(fileName))
cmd := exec.Command("rm", "-f", toDelete)
startTime := time.Now()
err2 := cmd.Run()
endTime := time.Now()
if err2 != nil {
log.WithFields(log.Fields{
"name": fileName,
"error": err2,
}).Warn("Delete local backup failed")
return err2
}
log.WithFields(log.Fields{
"name": fileName,
"runtime": endTime.Sub(startTime),
}).Info("Deleted local backup")
return nil
}
func DeleteS3Backups(backupTime time.Time, retentionPeriod time.Duration, bc *backupConfig) {
log.WithFields(log.Fields{
"retention": retentionPeriod,
}).Info("Invoking delete s3 backup files")
var backupDeleteList []string
client, err := minioClientFromConfig(bc)
if err != nil {
// An error on setting minio client is not a reason to bail out
// Having a snapshot without an upload to s3 is more valuable than not having a snapshot at all
log.WithFields(log.Fields{
"error": err,
}).Warn("Error while trying to configure minio client")
return
}
cutoffTime := backupTime.Add(retentionPeriod * -1)
isRecursive := false
prefix := ""
if len(bc.Folder) != 0 {
prefix = bc.Folder
// Recurse will show us the files in the folder
isRecursive = true
}
objectCh := client.ListObjects(context.TODO(), bc.BucketName, minio.ListObjectsOptions{
Prefix: prefix,
Recursive: isRecursive,
})
re := regexp.MustCompile(fmt.Sprintf(".+_etcd(|.%s)$", compressedExtension))
for object := range objectCh {
if object.Err != nil {
log.Error("error to fetch s3 file:", object.Err)
return
}
// only parse backup file names that matches *_etcd format
if re.MatchString(object.Key) {
filename := object.Key
if len(bc.Folder) != 0 {
// example object.Key with folder: folder/timestamp_etcd.zip
// folder and separator needs to be stripped so time can be parsed below
log.Debugf("Stripping [%s] from [%s]", fmt.Sprintf("%s/", prefix), filename)
filename = strings.TrimPrefix(filename, fmt.Sprintf("%s/", prefix))
}
log.Debugf("object.Key: [%s], filename: [%s]", object.Key, filename)
backupTime, err := time.Parse(time.RFC3339, strings.Split(filename, "_")[0])
if err != nil {
log.WithFields(log.Fields{
"name": filename,
"objectKey": object.Key,
"error": err,
}).Warn("Couldn't parse s3 backup")
} else if backupTime.Before(cutoffTime) {
// We use object.Key here as we need the full path when a folder is used
log.Debugf("Adding [%s] to files to delete, backupTime: [%q], cutoffTime: [%q]", object.Key, backupTime, cutoffTime)
backupDeleteList = append(backupDeleteList, object.Key)
}
}
}
log.Debugf("Found %d files to delete", len(backupDeleteList))
for i := range backupDeleteList {
log.Infof("Start to delete s3 backup file [%s]", backupDeleteList[i])
err := client.RemoveObject(context.TODO(), bc.BucketName, backupDeleteList[i], minio.RemoveObjectOptions{})
if err != nil {
log.Errorf("Error detected during deletion: %v", err)
} else {
log.Infof("Success delete s3 backup file [%s]", backupDeleteList[i])
}
}
}
func DeleteBackupAction(c *cli.Context) error {
name := c.String("name")
if name == "" {
return fmt.Errorf("snapshot name is required")
}
compressedPath := fmt.Sprintf("/backup/%s.%s", name, compressedExtension)
uncompressedPath := fmt.Sprintf("/backup/%s", name)
// Since we have to support compressed and uncompressed versions of snapshots.
// We can't remove the uncompressed snapshot during cleanup unless we are
// sure the compressed is there, hence the complex check.
if c.Bool("cleanup") {
if _, err := os.Stat(compressedPath); err == nil {
// for cleanup, we only want to delete the uncompressed snapshot.
// we don't need to go to s3
return deleteBackup(uncompressedPath)
}
} else {
for _, p := range []string{compressedPath, uncompressedPath} {
if err := deleteBackup(p); err != nil {
return err
}
}
}
if !c.Bool("s3-backup") {
return nil
}
bc := &backupConfig{
Endpoint: c.String("s3-endpoint"),
AccessKey: c.String("s3-accessKey"),
SecretKey: c.String("s3-secretKey"),
BucketName: c.String("s3-bucketName"),
Region: c.String("s3-region"),
EndpointCA: c.String("s3-endpoint-ca"),
Folder: c.String("s3-folder"),
}
client, err := setS3Service(bc, true)
if err != nil {
log.WithFields(log.Fields{
"s3-endpoint": bc.Endpoint,
"s3-bucketName": bc.BucketName,
"s3-accessKey": bc.AccessKey,
"s3-region": bc.Region,
"s3-endpoint-ca": bc.EndpointCA,
"s3-folder": bc.Folder,
}).Errorf("failed to set s3 server: %s", err)
return fmt.Errorf("failed to set s3 server: %+v", err)
}
folder := c.String("s3-folder")
if len(folder) != 0 {
name = fmt.Sprintf("%s/%s", folder, name)
}
doneCh := make(chan struct{})
defer close(doneCh)
// list objects with prefix=name, this will include uncompressed and compressed backup objects
objectCh := client.ListObjects(context.TODO(), bc.BucketName, minio.ListObjectsOptions{
Prefix: name,
Recursive: false,
})
var removed []string
for object := range objectCh {
if object.Err != nil {
log.Errorf("failed to list objects in backup buckets [%s]: %v", bc.BucketName, object.Err)
return object.Err
}
log.Infof("deleting object with key: %s that matches prefix: %s", object.Key, name)
err = client.RemoveObject(context.TODO(), bc.BucketName, object.Key, minio.RemoveObjectOptions{})
if err != nil {
return err
}
removed = append(removed, object.Key)
}
log.Infof("removed backups: %s from object store", strings.Join(removed, ", "))
return nil
}
func setS3Service(bc *backupConfig, useSSL bool) (*minio.Client, error) {
// Initialize minio client object.
log.WithFields(log.Fields{
"s3-endpoint": bc.Endpoint,
"s3-bucketName": bc.BucketName,
"s3-accessKey": bc.AccessKey,
"s3-region": bc.Region,
"s3-endpoint-ca": bc.EndpointCA,
"s3-folder": bc.Folder,
}).Info("invoking set s3 service client")
var err error
var client = &minio.Client{}
var cred *credentials.Credentials
var tr = http.DefaultTransport
if bc.EndpointCA != "" {
tr, err = setTransportCA(tr, bc.EndpointCA)
if err != nil {
return nil, err
}
}
bucketLookup := getBucketLookupType(bc.Endpoint)
for retries := 0; retries <= defaultS3Retries; retries++ {
// if the s3 access key and secret is not set use iam role
if len(bc.AccessKey) == 0 && len(bc.SecretKey) == 0 {
log.Info("invoking set s3 service client use IAM role")
cred = credentials.NewIAM("")
if bc.Endpoint == "" {
bc.Endpoint = s3Endpoint
}
} else {
// Base64 decoding S3 accessKey and secretKey before create static credentials
// To be backward compatible, just updating base64 encoded values
accessKey := bc.AccessKey
secretKey := bc.SecretKey
if len(accessKey) > 0 {
v, err := base64.StdEncoding.DecodeString(accessKey)
if err == nil {
accessKey = string(v)
}
}
if len(secretKey) > 0 {
v, err := base64.StdEncoding.DecodeString(secretKey)
if err == nil {
secretKey = string(v)
}
}
cred = credentials.NewStatic(accessKey, secretKey, "", credentials.SignatureDefault)
}
client, err = minio.New(bc.Endpoint, &minio.Options{
Creds: cred,
Secure: useSSL,
Region: bc.Region,
BucketLookup: bucketLookup,
Transport: tr,
})
if err != nil {
log.Infof("failed to init s3 client server: %v, retried %d times", err, retries)
if retries >= defaultS3Retries {
return nil, fmt.Errorf("failed to set s3 server: %v", err)
}
continue
}
break
}
found, err := client.BucketExists(context.TODO(), bc.BucketName)
if err != nil {
return nil, fmt.Errorf("failed to check s3 bucket:%s, err:%v", bc.BucketName, err)
}
if !found {
return nil, fmt.Errorf("bucket %s is not found", bc.BucketName)
}
return client, nil
}
func getBucketLookupType(endpoint string) minio.BucketLookupType {
if endpoint == "" {
return minio.BucketLookupAuto
}
if strings.Contains(endpoint, "aliyun") {
return minio.BucketLookupDNS
}
return minio.BucketLookupAuto
}
func uploadBackupFile(svc *minio.Client, bucketName, fileName, filePath string, s3Retries uint) error {
var info minio.UploadInfo
var err error
// Upload the zip file with FPutObject
log.Infof("invoking uploading backup file [%s] to s3", fileName)
for i := uint(0); i <= s3Retries; i++ {
info, err = svc.FPutObject(context.TODO(), bucketName, fileName, filePath, minio.PutObjectOptions{ContentType: contentType})
if err == nil {
log.Infof("Successfully uploaded [%s] of size [%d]", fileName, info.Size)
return nil
}
log.Infof("failed to upload etcd snapshot file: %v, retried %d times", err, i)
}
return fmt.Errorf("failed to upload etcd snapshot file: %v", err)
}
func DownloadBackupAction(c *cli.Context) error {
log.Info("Initializing Download Backups")
SetLoggingLevel(c.Bool("debug"))
if c.Bool("s3-backup") {
return DownloadS3Backup(c)
}
return DownloadLocalBackup(c)
}
func ExtractStateFileAction(c *cli.Context) error {
SetLoggingLevel(c.Bool("debug"))
name := path.Base(c.String("name"))
log.Infof("Trying to get statefile from backup [%s]", name)
if c.Bool("s3-backup") {
err := DownloadS3Backup(c)
if err != nil {
return err
}
}
// Destination filename for statefile
stateFilePath := fmt.Sprintf("%s/%s.%s", k8sBaseDir, name, clusterStateExtension)
// Location of the compressed snapshot file
compressedFilePath := fmt.Sprintf("/backup/%s.%s", name, compressedExtension)
// Check if compressed snapshot file exists
if _, err := os.Stat(compressedFilePath); err != nil {
return err
}
// Extract statefile content in archive
err := decompressFile(compressedFilePath, stateFilePath, tmpStateFilePath)
if err != nil {
return fmt.Errorf("Unable to extract file [%s] from file [%s] to destination [%s]: %v", stateFilePath, compressedFilePath, tmpStateFilePath, err)
}
log.Infof("Successfully extracted file [%s] from file [%s] to destination [%s]", stateFilePath, compressedFilePath, tmpStateFilePath)
return nil
}
func DownloadS3Backup(c *cli.Context) error {
bc := &backupConfig{
Endpoint: c.String("s3-endpoint"),
AccessKey: c.String("s3-accessKey"),
SecretKey: c.String("s3-secretKey"),
BucketName: c.String("s3-bucketName"),
Region: c.String("s3-region"),
EndpointCA: c.String("s3-endpoint-ca"),
Folder: c.String("s3-folder"),
}
client, err := setS3Service(bc, true)
if err != nil {
log.WithFields(log.Fields{
"s3-endpoint": bc.Endpoint,
"s3-bucketName": bc.BucketName,
"s3-accessKey": bc.AccessKey,
"s3-region": bc.Region,
"s3-endpoint-ca": bc.EndpointCA,
"s3-folder": bc.Folder,
}).Errorf("failed to set s3 server: %s", err)
return fmt.Errorf("failed to set s3 server: %+v", err)
}
prefix := c.String("name")
if len(prefix) == 0 {
return fmt.Errorf("empty backup name")
}
folder := c.String("s3-folder")
if len(folder) != 0 {
prefix = fmt.Sprintf("%s/%s", folder, prefix)
}
// we need download with prefix because we don't know if the file is ziped or not
filename, err := downloadFromS3WithPrefix(client, prefix, bc.BucketName)
if err != nil {
return err
}
if isCompressed(filename) {
log.Infof("Decompressing etcd snapshot file [%s]", filename)
compressedFilePath := fmt.Sprintf("%s/%s", backupBaseDir, filename)
fileLocation := fmt.Sprintf("%s/%s", backupBaseDir, decompressedName(filename))
err := decompressFile(compressedFilePath, fileLocation, fileLocation)
if err != nil {
return fmt.Errorf("Unable to decompress [%s] to [%s]: %v", compressedFilePath, fileLocation, err)
}
log.Infof("Decompressed [%s] to [%s]", compressedFilePath, fileLocation)
}
return nil
}
func DownloadLocalBackup(c *cli.Context) error {
snapshot := path.Base(c.String("name"))
endpoint := c.String("local-endpoint")
if snapshot == "." || snapshot == "/" {
return fmt.Errorf("snapshot name is required")
}
if len(endpoint) == 0 {
return fmt.Errorf("local-endpoint is required")
}
certs, err := getCertsFromCli(c)
if err != nil {
return err
}
tlsConfig, err := setupTLSConfig(certs, false)
if err != nil {
return err
}
client := http.Client{Transport: &http.Transport{TLSClientConfig: tlsConfig}}
snapshotURL := fmt.Sprintf("https://%s:%s/%s", endpoint, serverPort, snapshot)
log.Infof("Invoking downloading backup files: %s", snapshot)
log.Infof("Trying to download backup file from: %s", snapshotURL)
resp, err := client.Get(snapshotURL)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
log.Errorf("backup download failed: %v", resp.Body)
return fmt.Errorf("backup download failed: %v", resp.Body)
}
defer resp.Body.Close()
snapshotFileLocation := fmt.Sprintf("%s/%s", backupBaseDir, snapshot)
snapshotFile, err := os.Create(snapshotFileLocation)
if err != nil {
return err
}
defer snapshotFile.Close()
if _, err := io.Copy(snapshotFile, resp.Body); err != nil {
return err
}
if err := os.Chmod(snapshotFileLocation, 0600); err != nil {
log.WithFields(log.Fields{
"error": err,