-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
120 lines (106 loc) · 2.56 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
package main
import (
"archive/zip"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/minio/minio-go"
"github.com/robfig/cron"
)
// RecursiveZip is function to create zip for given directory
func RecursiveZip(pathToZip, destinationPath string) error {
destinationFile, err := os.Create(destinationPath)
if err != nil {
return err
}
myZip := zip.NewWriter(destinationFile)
err = filepath.Walk(pathToZip, func(filePath string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if err != nil {
return err
}
relPath := strings.TrimPrefix(filePath, filepath.Dir(pathToZip))
zipFile, err := myZip.Create(relPath)
if err != nil {
return err
}
fsFile, err := os.Open(filePath)
if err != nil {
return err
}
_, err = io.Copy(zipFile, fsFile)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
err = myZip.Close()
if err != nil {
return err
}
return nil
}
// Upload is function to upload zip to Spaces
func Upload() {
s3Client, err := minio.New(os.Getenv("S3_URL"), os.Getenv("ACCESS_KEY_ID"), os.Getenv("SECRET_ACCESS_KEY"), true)
if err != nil {
log.Fatalln(err)
}
sourceFolderPath := "/data"
fileName := fmt.Sprintf("%d.zip", time.Now().Unix())
RecursiveZip(sourceFolderPath, fileName)
log.Printf("%s zip created.\n", fileName)
// check if file exist before upload and delete after uploading finished.
if _, err := os.Stat(fileName); err == nil {
if _, err := s3Client.FPutObject(os.Getenv("BUCKET_NAME"), fileName, fileName, minio.PutObjectOptions{
ContentType: "application/zip",
}); err != nil {
log.Println(err)
}
log.Printf("%s uploaded successfully.\n", fileName)
err := os.Remove(fileName)
if err != nil {
fmt.Println(err)
return
}
log.Printf("%s file deleted after upload.\n", fileName)
} else if os.IsNotExist(err) {
log.Printf("%s file does not exist.\n", fileName)
} else {
log.Fatalln(err)
}
}
func main() {
if os.Getenv("ACCESS_KEY_ID") == "" {
log.Fatalln("ACCESS_KEY_ID can't be blank.")
}
if os.Getenv("BUCKET_NAME") == "" {
log.Fatalln("BUCKET_NAME can't be blank.")
}
if os.Getenv("CRON_SCHEDULE") == "" {
log.Fatalln("CRON_SCHEDULE can't be blank.")
}
if os.Getenv("S3_URL") == "" {
log.Fatalln("S3_URL can't be blank")
}
if os.Getenv("SECRET_ACCESS_KEY") == "" {
log.Fatalln("SECRET_ACCESS_KEY can't be blank.")
}
c := cron.New()
c.AddFunc(os.Getenv("CRON_SCHEDULE"), Upload)
c.Start()
log.Println("Backup scheduler started successfully.")
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
}