-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbacky.go
279 lines (240 loc) Β· 8.11 KB
/
backy.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
package main
import (
"encoding/json"
"errors"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"strconv"
"strings"
"time"
)
const version string = "1.2"
type Task struct {
VerboseLog bool `json:"verbose_log"`
Multiprocessing bool `json:"multiprocessing"`
Destination string `json:"destination"`
ArchivingCycle string `json:"archiving_cycle"`
Exclude []string `json:"exclude"`
DirectoriesToSync []string `json:"directories_to_sync"`
DirectoriesToArchive []string `json:"directories_to_archive"`
}
func removeDuplicates(elements []string) (unique_elements []string) {
encountered := map[string]bool{}
for i := range elements {
if encountered[elements[i]] == true {
} else {
encountered[elements[i]] = true
unique_elements = append(unique_elements, elements[i])
}
}
return unique_elements
}
func normilizePaths(paths []string) (normalized_paths []string) {
homedir, _ := os.UserHomeDir()
for i, p := range paths {
if string(p[0]) == "~" {
p = strings.Replace(p, "~", homedir, 1)
}
paths[i] = strings.TrimRight(string(p), "/")
}
return paths
}
func getBasePath(path string) (base_path string) {
hostname, err := os.Hostname()
if err != nil {
hostname = "local"
}
return strings.Replace(hostname+path, "/", "_", -1)
}
func formatExcludeArgs(exclude_args_list []string) (exclude_args []string) {
for _, i := range exclude_args_list {
exclude_args = append(exclude_args, "--exclude="+i)
}
return exclude_args
}
func generateArchiveFilePath(path string, archiving_cycle string) (file_path string) {
var result_file_path [1]string
dt := time.Now()
_, iso_week := dt.ISOWeek()
base_path := getBasePath(path)
switch archiving_cycle {
case "hourly":
result_file_path[0] = base_path + dt.Format("_2006_January_") + strconv.Itoa(dt.Day()) + dt.Format("_15hr") + ".tar.bz2"
case "daily":
result_file_path[0] = base_path + dt.Format("_2006_January_") + strconv.Itoa(dt.Day()) + ".tar.bz2"
case "weekly":
result_file_path[0] = base_path + dt.Format("_2006_January_") + strconv.Itoa(iso_week) + "wk.tar.bz2"
case "monthly":
result_file_path[0] = base_path + dt.Format("_2006_January") + ".tar.bz2"
case "yearly":
result_file_path[0] = base_path + dt.Format("_2006") + ".tar.bz2"
default:
result_file_path[0] = base_path + dt.Format("_2006_January") + ".tar.bz2"
}
return result_file_path[0]
}
func getTaskFromJson(file_path string) (config_err error, task_config Task) {
jsonFile, err := os.Open(file_path)
if err != nil {
config_err = errors.New("Can't open task file")
}
log.Println("π", "Working with", file_path, "...")
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
json.Unmarshal(byteValue, &task_config)
if task_config.Destination != "" {
task_config.Destination = normilizePaths([]string{task_config.Destination})[0]
task_config.DirectoriesToSync = removeDuplicates(normilizePaths(task_config.DirectoriesToSync))
task_config.DirectoriesToArchive = removeDuplicates(normilizePaths(task_config.DirectoriesToArchive))
task_config.Exclude = formatExcludeArgs(removeDuplicates(task_config.Exclude))
} else {
log.Println("π°", "Task configuration: destination must be specified!")
config_err = errors.New("Wrong task format")
}
return config_err, task_config
}
func filterArchiveDirs(archive_dirs []string, archiving_cycle string, dest string) (filtered_archive_dirs []string) {
for _, i := range archive_dirs {
_, e := os.Stat(path.Join(dest, generateArchiveFilePath(i, archiving_cycle)))
if os.IsNotExist(e) {
filtered_archive_dirs = append(filtered_archive_dirs, i)
}
}
return filtered_archive_dirs
}
func logProgress(amount int, indicator string) {
progress_indicator_step := " " + indicator
for i := 1; i < amount; i++ {
indicator += progress_indicator_step
}
log.Println(indicator)
}
func checkStatus(status error, process string, element string) (status_err error) {
if status != nil {
log.Println("π’", process, "failed for:", element)
status_err = errors.New("process failed")
}
return status_err
}
func setProcessOutput(process *exec.Cmd, print_outtput bool) {
if print_outtput == true {
process.Stdout = os.Stdout
process.Stderr = os.Stderr
}
}
func runProcess(c string, args []string, print_outtput bool) (status error) {
cmd := exec.Command(c, args...)
setProcessOutput(cmd, print_outtput)
return cmd.Run()
}
func startProcess(c string, args []string, print_outtput bool) (handle *exec.Cmd) {
cmd := exec.Command(c, args...)
setProcessOutput(cmd, print_outtput)
cmd.Start()
return cmd
}
func startRsync(src_dirs []string, dest string, args []string, multiprocessing bool, print_outtput bool) (rsync_err error) {
var processes []*exec.Cmd
if len(src_dirs) > 0 {
log.Println("π€", "Syncing from:", src_dirs)
log.Println("π₯", "To:", dest, "...")
for p, i := range src_dirs {
if multiprocessing == true {
processes = append(processes, startProcess("rsync", append(args, []string{i, dest}...), print_outtput))
} else {
logProgress(p+1, "π")
if checkStatus(runProcess("rsync", append(args, []string{i, dest}...), print_outtput), "Syncronization", i) != nil {
rsync_err = errors.New("rsync failed")
}
}
}
if multiprocessing == true {
for i, p := range processes {
logProgress(i+1, "π")
if checkStatus(p.Wait(), "Syncronization", src_dirs[i]) != nil {
rsync_err = errors.New("rsync failed")
}
}
}
} else {
log.Println("π€", "Nothing to sync")
}
return rsync_err
}
func startTar(archive_dirs []string, dest string, mode string, args []string, archiving_cycle string, multiprocessing bool, print_outtput bool) (tar_err error) {
var processes []*exec.Cmd
dirs_to_archive := filterArchiveDirs(archive_dirs, archiving_cycle, dest)
if len(dirs_to_archive) > 0 {
log.Println("π€", "Archiving:", dirs_to_archive)
log.Println("π₯", "To:", dest, "...")
for p, i := range dirs_to_archive {
completed_archive := path.Join(dest, generateArchiveFilePath(i, archiving_cycle))
in_progress_archive := completed_archive + ".part"
task_args := append([]string{mode, in_progress_archive}, append(args, i)...)
_, e := os.Stat(in_progress_archive)
if !os.IsNotExist(e) {
os.Remove(in_progress_archive)
}
if multiprocessing == true {
processes = append(processes, startProcess("tar", task_args, print_outtput))
} else {
logProgress(p+1, "π¦")
if checkStatus(runProcess("tar", task_args, print_outtput), "Archiving", i) != nil {
os.Remove(in_progress_archive)
tar_err = errors.New("tar failed")
} else {
os.Rename(in_progress_archive, completed_archive)
}
}
}
if multiprocessing == true {
for i, p := range processes {
completed_archive := path.Join(dest, generateArchiveFilePath(dirs_to_archive[i], archiving_cycle))
in_progress_archive := completed_archive + ".part"
logProgress(i+1, "π¦")
if checkStatus(p.Wait(), "Archiving", dirs_to_archive[i]) != nil {
os.Remove(in_progress_archive)
tar_err = errors.New("tar failed")
} else {
os.Rename(in_progress_archive, completed_archive)
}
}
}
} else {
log.Println("π€", "Nothing to archive")
}
return tar_err
}
func main() {
var status int = 0
log.SetOutput(os.Stdout)
log.Println("π", "backy", version)
if len(os.Args[1:]) < 1 {
log.Println("βοΈ", "No task configuration provided")
log.Println("π°", "Usage: backy <task.json>")
status = 1
} else {
err, task := getTaskFromJson(os.Args[1])
if err != nil {
log.Println("βοΈ", "Can't read provided task configuration")
status = 2
} else {
if startRsync(task.DirectoriesToSync, task.Destination, append([]string{"-avW", "--delete", "--delete-excluded"}, task.Exclude...), task.Multiprocessing, task.VerboseLog) != nil {
status = 3
log.Println("βοΈ", "Synchronization completed with errors")
}
if startTar(task.DirectoriesToArchive, task.Destination, "-jcvf", task.Exclude, task.ArchivingCycle, task.Multiprocessing, task.VerboseLog) != nil {
if status != 3 {
status = 4
} else {
status = 5
}
log.Println("βοΈ", "Archiving completed with errors")
}
}
}
os.Exit(status)
}