forked from rancher/rke-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1130 lines (1026 loc) · 29.3 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"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path"
"regexp"
"strings"
"time"
"github.com/minio/minio-go"
"github.com/minio/minio-go/pkg/credentials"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
)
const (
backupBaseDir = "/backup"
backupRetries = 4
compressedExtension = "zip"
s3ServerRetries = 3
contentType = "application/zip"
ServerPort = "2379"
s3Endpoint = "s3.amazonaws.com"
)
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 sanpshot 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: snapshotFlags,
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: "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)
} 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"),
}
var client = &minio.Client{}
var tr = http.DefaultTransport
var err error
if s3Backup {
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)
}
if bc.EndpointCA != "" {
tr, err = setTransportCA(tr, bc.EndpointCA)
if err != nil {
return err
}
}
client.SetCustomTransport(tr)
}
if c.Bool("once") {
backupName := c.String("name")
log.WithFields(log.Fields{
"name": backupName,
}).Info("Initializing Onetime Backup")
if err := CreateBackup(backupName, etcdCACert, etcdCert, etcdKey, etcdEndpoints, client, bc); 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))
if err := CreateBackup(backupName, etcdCACert, etcdCert, etcdKey, etcdEndpoints, client, bc); err == nil {
DeleteBackups(backupTime, retentionPeriod)
if s3Backup {
DeleteS3Backups(backupTime, retentionPeriod, client, bc)
}
}
}
}
}
func CreateBackup(backupName string, etcdCACert, etcdCert, etcdKey, endpoints string, svc *minio.Client, server *backupConfig) error {
failureInterval := 15 * time.Second
backupDir := fmt.Sprintf("%s/%s", backupBaseDir, backupName)
var err error
var data []byte
for retries := 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")
continue
}
cmd = exec.Command("etcdctl",
fmt.Sprintf("--endpoints=%s", endpoints),
"--cacert="+etcdCACert,
"--cert="+etcdCert,
"--key="+etcdKey,
"snapshot", "save", backupDir)
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")
continue
}
// Compress backup
compressedFilePath, err := compressFile(backupDir)
if err != nil {
log.WithFields(log.Fields{
"attempt": retries + 1,
"error": err,
"data": string(data),
}).Warn("Compressing backup failed")
continue
}
// Set the full path to the compressed file for uploading
compressedFile := fmt.Sprintf("%s.%s", backupName, compressedExtension)
// Remove the original file after succesfully compressing it
err = os.Remove(backupDir)
if err != nil {
log.WithFields(log.Fields{
"attempt": retries + 1,
"error": err,
"data": string(data),
}).Warn("Removing uncompressed snapshot file failed")
}
log.WithFields(log.Fields{
"name": backupName,
"runtime": endTime.Sub(startTime),
}).Info("Created 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")
}
if server.Backup {
// If folder is specified, prefix the file with the folder
if len(server.Folder) != 0 {
compressedFile = fmt.Sprintf("%s/%s", server.Folder, compressedFile)
}
err = uploadBackupFile(svc, server.BucketName, compressedFile, compressedFilePath)
if err == nil {
return nil
}
}
break
}
// Include the cmd output (data) into the error
if err != nil {
return fmt.Errorf("%s: %v", err, string(data))
}
return err
}
func DeleteBackups(backupTime time.Time, retentionPeriod time.Duration) {
files, err := ioutil.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 backup failed")
return err2
}
log.WithFields(log.Fields{
"name": fileName,
"runtime": endTime.Sub(startTime),
}).Info("Deleted backup")
return nil
}
func DeleteS3Backups(backupTime time.Time, retentionPeriod time.Duration, svc *minio.Client, bc *backupConfig) {
log.WithFields(log.Fields{
"retention": retentionPeriod,
}).Info("Invoking delete s3 backup files")
var backupDeleteList []string
cutoffTime := backupTime.Add(retentionPeriod * -1)
// Create a done channel to control 'ListObjectsV2' go routine.
doneCh := make(chan struct{})
// Indicate to our routine to exit cleanly upon return.
defer close(doneCh)
isRecursive := false
prefix := ""
if len(bc.Folder) != 0 {
prefix = bc.Folder
}
objectCh := svc.ListObjects(bc.BucketName, prefix, isRecursive, doneCh)
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) {
backupTime, err := time.Parse(time.RFC3339, strings.Split(object.Key, "_")[0])
if err != nil {
log.WithFields(log.Fields{
"name": object.Key,
"error": err,
}).Warn("Couldn't parse s3 backup")
} else if backupTime.Before(cutoffTime) {
backupDeleteList = append(backupDeleteList, object.Key)
}
}
}
for i := range backupDeleteList {
log.Infof("Start to delete s3 backup file [%s]", backupDeleteList[i])
err := svc.RemoveObject(bc.BucketName, backupDeleteList[i])
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)
}
for _, p := range []string{name, fmt.Sprintf("%s.%s", name, compressedExtension)} {
if err = client.RemoveObject(bc.BucketName, p); err != nil {
return err
}
}
return nil
}
func setS3Service(bc *backupConfig, useSSL bool) (*minio.Client, error) {
// Initialize minio client object.
log.Info("invoking set s3 service client")
var err error
var client = &minio.Client{}
var cred = &credentials.Credentials{}
var tr = http.DefaultTransport
bucketLookup := getBucketLookupType(bc.Endpoint)
for retries := 0; retries <= s3ServerRetries; 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 {
cred = credentials.NewStatic(bc.AccessKey, bc.SecretKey, "", credentials.SignatureDefault)
}
client, err = minio.NewWithOptions(bc.Endpoint, &minio.Options{
Creds: cred,
Secure: useSSL,
Region: bc.Region,
BucketLookup: bucketLookup,
})
if err != nil {
log.Infof("failed to init s3 client server: %v, retried %d times", err, retries)
if retries >= s3ServerRetries {
return nil, fmt.Errorf("failed to set s3 server: %v", err)
}
continue
}
if bc.EndpointCA != "" {
tr, err = setTransportCA(tr, bc.EndpointCA)
if err != nil {
return nil, err
}
}
client.SetCustomTransport(tr)
break
}
found, err := client.BucketExists(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) error {
// Upload the zip file with FPutObject
log.Infof("invoking uploading backup file %s to s3", fileName)
for retries := 0; retries <= s3ServerRetries; retries++ {
n, err := svc.FPutObject(bucketName, fileName, filePath, minio.PutObjectOptions{ContentType: contentType})
if err != nil {
log.Infof("failed to upload etcd snapshot file: %v, retried %d times", err, retries)
if retries >= s3ServerRetries {
return fmt.Errorf("failed to upload etcd snapshot file: %v", err)
}
continue
}
log.Infof("Successfully uploaded %s of size %d\n", fileName, n)
break
}
return nil
}
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 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)
compressedFileLocation := fmt.Sprintf("%s/%s", backupBaseDir, filename)
fileLocation := fmt.Sprintf("%s/%s", backupBaseDir, decompressedName(filename))
err := decompressFile(compressedFileLocation, fileLocation)
if err != nil {
return fmt.Errorf("Unable to decompress [%s] to [%s]: %v", compressedFileLocation, fileLocation, err)
}
log.Infof("Decompressed [%s] to [%s]", compressedFileLocation, 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,
}).Warn("changing permission of the locally downloaded snapshot failed")
}
log.Infof("Successfully download %s from %s ", snapshot, endpoint)
return nil
}
func DeleteNamedBackups(retentionPeriod time.Duration, prefix string) error {
files, err := ioutil.ReadDir(backupBaseDir)
if err != nil {
log.WithFields(log.Fields{
"dir": backupBaseDir,
"error": err,
}).Warn("Can't read backup directory")
return err
}
cutoffTime := time.Now().Add(retentionPeriod * -1)
for _, file := range files {
if strings.HasPrefix(file.Name(), prefix) && file.ModTime().Before(cutoffTime) && IsRecurringSnapshot(file.Name()) {
if err = deleteBackup(file.Name()); err != nil {
return err
}
}
}
return nil
}
func getNamePrefix(name string) string {
re := regexp.MustCompile("^c-[a-z0-9].*?-")
m := re.FindStringSubmatch(name)
if len(m) == 0 {
return ""
}
return m[0]
}
func ServeBackupAction(c *cli.Context) error {
snapshot := path.Base(c.String("name"))
if snapshot == "." || snapshot == "/" {
return fmt.Errorf("snapshot name is required")
}
// Check if snapshot is compressed
compressedFileLocation := fmt.Sprintf("%s/%s.%s", backupBaseDir, snapshot, compressedExtension)
if _, err := os.Stat(compressedFileLocation); err == nil {
err := decompressFile(compressedFileLocation, fmt.Sprintf("%s/%s", backupBaseDir, snapshot))
if err != nil {
return err
}
log.Infof("Extracted from %s", compressedFileLocation)
}
if _, err := os.Stat(fmt.Sprintf("%s/%s", backupBaseDir, snapshot)); err != nil {
return err
}
certs, err := getCertsFromCli(c)
if err != nil {
return err
}
tlsConfig, err := setupTLSConfig(certs, true)
if err != nil {
return err
}
httpServer := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%s", ServerPort),
TLSConfig: tlsConfig,
}
http.HandleFunc(fmt.Sprintf("/%s", snapshot), func(response http.ResponseWriter, request *http.Request) {
http.ServeFile(response, request, fmt.Sprintf("%s/%s", backupBaseDir, snapshot))
})
return httpServer.ListenAndServeTLS(certs["cert"], certs["key"])
}
func getCertsFromCli(c *cli.Context) (map[string]string, error) {
caCert := c.String("cacert")
cert := c.String("cert")
key := c.String("key")
if len(cert) == 0 || len(caCert) == 0 || len(key) == 0 {
return nil, fmt.Errorf("cacert, cert and key are required")
}
return map[string]string{"cacert": caCert, "cert": cert, "key": key}, nil
}
func setupTLSConfig(certs map[string]string, isServer bool) (*tls.Config, error) {
caCertPem, err := ioutil.ReadFile(certs["cacert"])
if err != nil {
return nil, err
}
tlsConfig := &tls.Config{}
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(caCertPem)
if isServer {
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
tlsConfig.ClientCAs = certPool
tlsConfig.MinVersion = tls.VersionTLS12
} else { // client config
x509Pair, err := tls.LoadX509KeyPair(certs["cert"], certs["key"])
if err != nil {
return nil, err
}
tlsConfig.Certificates = []tls.Certificate{x509Pair}
tlsConfig.RootCAs = certPool
// This is to avoid IP SAN errors.
tlsConfig.InsecureSkipVerify = true
}
tlsConfig.BuildNameToCertificate()
return tlsConfig, nil
}
func IsRecurringSnapshot(name string) bool {
// name is fmt.Sprintf("%s-%s%s-", cluster.Name, typeFlag, providerFlag)
// typeFlag = "r": recurring
// typeFlag = "m": manaul
//
// providerFlag = "l" local
// providerFlag = "s" s3
re := regexp.MustCompile("^c-[a-z0-9].*?-r.-")
return re.MatchString(name)
}
func downloadFromS3WithPrefix(client *minio.Client, prefix, bucket string) (string, error) {
var filename string
doneCh := make(chan struct{})
defer close(doneCh)
objectCh := client.ListObjectsV2(bucket, prefix, false, doneCh)
for object := range objectCh {
if object.Err != nil {
log.Errorf("failed to list objects in backup buckets [%s]: %v", bucket, object.Err)
return "", object.Err
}
if prefix == decompressedName(object.Key) {
filename = object.Key
break
}
}
if len(filename) == 0 {
return "", fmt.Errorf("failed to download s3 backup: no backups found")
}
// if folder is included, strip it so it doesnt end up in a folder on the host itself
targetFilename := path.Base(filename)
for retries := 0; retries <= s3ServerRetries; retries++ {
err := client.FGetObject(bucket, filename, backupBaseDir+"/"+targetFilename, minio.GetObjectOptions{})
if err != nil {
log.Infof("Failed to download etcd snapshot file [%s]: %v, retried %d times", filename, err, retries)
if retries >= s3ServerRetries {
log.Warningf("Failed to download etcd snapshot file [%s]: %v", filename, err)
break
}
}
log.Infof("Successfully downloaded [%s]", filename)
return targetFilename, nil
}
return "", fmt.Errorf("Unable to download backup file for [%s]", filename)
}
func compressFile(fileName string) (string, error) {
// Check if source file exists
fileToZip, err := os.Open(fileName)
if err != nil {
return "", err
}
defer fileToZip.Close()