-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
backup.go
92 lines (79 loc) · 1.93 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
package main
import (
"archive/zip"
"io"
"os"
"path/filepath"
"github.com/azukaar/cosmos-server/src/utils"
)
func RunBackup() {
utils.Log("Backup: Running backup")
inputDir := utils.CONFIGFOLDER
outputDir := utils.CONFIGFOLDER
if utils.GetMainConfig().BackupOutputDir != "" {
outputDir = utils.GetMainConfig().BackupOutputDir
if os.Getenv("HOSTNAME") != "" {
outputDir = "/mnt/host" + outputDir
}
}
// Recursive file listing helper
var fileList []string
err := filepath.Walk(inputDir, func(path string, f os.FileInfo, err error) error {
if !f.IsDir() && filepath.Ext(f.Name()) != ".zip" {
relPath, err := filepath.Rel(inputDir, path)
if err != nil {
return err
}
fileList = append(fileList, relPath)
}
return nil
})
if err != nil {
utils.MajorError("Backup: Error reading directory", err)
return
}
// create a new zip file
zipfile, err := os.Create(outputDir + "/cosmos-backup" + ".temp.zip")
if err != nil {
utils.MajorError("Backup: Error creating zip file", err)
return
}
defer zipfile.Close()
// create a new zip archive
zipw := zip.NewWriter(zipfile)
defer zipw.Close()
// loop through the files
for _, file := range fileList {
f, err := os.Open(filepath.Join(inputDir, file))
if err != nil {
utils.MajorError("Backup: Error opening file", err)
return
}
defer f.Close()
// add file to zip
zipf, err := zipw.Create(file)
if err != nil {
utils.MajorError("Backup: Error adding file to zip", err)
return
}
_, err = io.Copy(zipf, f)
if err != nil {
utils.MajorError("Backup: Error copying file", err)
return
}
}
// rename the file
err = os.Rename(outputDir+"/cosmos-backup.temp.zip", outputDir+"/cosmos-backup.zip")
if err != nil {
utils.MajorError("Backup: Error renaming file", err)
return
}
utils.Log("Backup: Backup complete")
utils.TriggerEvent(
"cosmos.backup",
"Cosmos Backup Succesful",
"success",
"",
map[string]interface{}{},
)
}