-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpupirka.go
395 lines (350 loc) · 11.9 KB
/
pupirka.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
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/gammazero/workerpool"
logrus "github.com/sirupsen/logrus"
"io/ioutil"
"os"
"regexp"
"strconv"
"strings"
"time"
)
type Logger logrus.Logger
func ScanDevice() {
dir := ConfigV.GetString("path.devices")
files, err := ioutil.ReadDir(dir)
if err != nil {
es := fmt.Sprintf(err.Error())
LogConsole.Error(es)
LogConsole.Error("Program exit")
os.Exit(1)
}
for _, f := range files {
fr := regexp.MustCompile(`\.json$`)
if frr := string(fr.Find([]byte(f.Name()))); frr == "" {
es := fmt.Sprintf("File %s skipped, not valid file extension", f.Name())
LogConsole.Error(es)
continue
}
DeviceFiles = append(DeviceFiles, f.Name())
}
}
func ReadDevice(Dev *DeviceList) {
for _, f := range DeviceFiles {
filepath := fmt.Sprintf("%s/%s", ConfigV.GetString("path.devices"), f)
jsonFile, err := os.Open(filepath)
if err != nil {
es := fmt.Sprintf("Error file Open %s, Error:%s, Skip file", f, err.Error())
LogConsole.Error(es)
continue
}
defer jsonFile.Close()
byteValueFromFile, err := ioutil.ReadAll(jsonFile)
if err != nil {
es := fmt.Sprintf("Error file Read %s, Error:%s, Skip file", f, err.Error())
LogConsole.Error(es)
jsonFile.Close()
continue
}
var d Device
err = json.Unmarshal(byteValueFromFile, &d)
if err != nil {
es := fmt.Sprintf("Error Read file json %s, Error:%s, Skip file", f, err.Error())
LogConsole.Error(es)
jsonFile.Close()
continue
}
d.Name = f[:len(f)-5]
d.LogConfig()
SetDefaultParameter(&d)
MDeviceList[d.Name] = d
Dev.Devices = append(Dev.Devices, d)
}
}
func RotateDevice(device *DeviceList) {
LogConsole.Info("Rotate device list...")
for i, d := range device.Devices {
d.LogDebug("RotateDevice: check directory backup", d.Name, d.Dirbackup)
if _, err := os.Stat(d.Dirbackup); os.IsNotExist(err) {
_ = os.Mkdir(d.Dirbackup, os.ModePerm)
LogConsole.Info(fmt.Sprintf("Create Folder %s for backup", d.Dirbackup))
continue
}
d.LogDebug("RotateDevice: read folder backup", d.Name, d.Dirbackup)
files, err := ioutil.ReadDir(d.Dirbackup)
if err != nil {
es := fmt.Sprintf("Error read folder backup %s, Error:%s", d.Dirbackup, err.Error())
LogConsole.Error(es)
device.Devices[i].StatusJob = "skip"
continue
}
d.LogDebug("RotateDevice: Find old backup", d.Name, d.Dirbackup)
for _, f := range files {
d.LogDebug(fmt.Sprintf("RotateDevice: Check File %s, time %s", f.Name(), f.ModTime().String()))
now := time.Now()
fdifftimesecond := now.Sub(f.ModTime()).Seconds()
diffday := fdifftimesecond / 60 / 60 / 24
if int(diffday) > d.Rotate {
d.LogDebug(fmt.Sprintf("RotateDevice: File %s old backup for device %s", f.Name(), d.Name))
if len(files) > 5 {
d.LogDebug("RotateDevice: File Count > 5 in backup", d.Name)
d.LogDebug("RotateDevice: Remove old files", f.Name())
filename := fmt.Sprintf("%s/%s", d.Dirbackup, f.Name())
err := os.Remove(filename)
if err != nil {
es := fmt.Sprintf("Error Remove file %s, Error:%s", f.Name(), err.Error())
LogConsole.Error(es)
continue
}
if err := gitClient.RemoveFile(filename); err != nil {
d.LogWarn(err)
continue
}
}
}
if int(fdifftimesecond) < d.Every {
d.LogDebug(fmt.Sprintf("RotateDevice: control check file time (%f), need time (%d)", fdifftimesecond, d.Every))
d.LogDebug("RotateDevice: Device no need backup", d.Name)
device.Devices[i].StatusJob = "skip"
break
}
}
}
/*
newDev := DeviceList{}
for _, d := range device.Devices {
if d.Name == "" {
continue
}
newDev.Devices = append(newDev.Devices, d)
}
device.Devices = newDev.Devices
*/
}
func RunBackups(Dev *DeviceList) {
LogConsole.Info("Backup Start ---->")
//todo need create dynamic group, curent group 10 and wait all execute after next 10.
//todo need if one exit group, send one next to group
wp := workerpool.New(ConfigV.GetInt("process.max"))
for _, d := range Dev.Devices {
d := d
if d.StatusJob == "skip" {
d.Hook()
continue
}
d.LogDebug("RunBackups: wait groups", d.Name)
wp.Submit(func() {
d.LogDebug("RunBackups: enter groups", d.Name)
backup(&d)
d.Hook()
})
d.LogDebug("RunBackups: Exit groups", d.Name)
}
wp.StopWait()
LogConsole.Info("Backup Finish <----")
}
func backup(device *Device) {
LogConsole.Warn(fmt.Sprintf("Starting backup %s ...", device.Name))
device.LogDebug("Starting backup ", device.Name)
var bytefromsshclient []byte
if device.Parent != "" {
device.LogDebug("backup: parent exist ", device.Name)
parent, child, err := SshNeedForward(device)
if err != nil {
ers := fmt.Sprintf("Fatal error Device:%s get parent %s error: %s", device.Name, device.Parent, err.Error())
LogConsole.Error(ers)
device.LogError(ers)
device.StatusJob = "error"
return
}
newd := SshForwardNewDevice(parent, child)
bytefromsshclient, err = SshClientRun(&newd)
if err != nil {
ers := fmt.Sprintf("Fatal error Forward Device:%s: %s", device.Name, err.Error())
LogConsole.Error(ers)
device.LogError(ers)
device.StatusJob = "error"
return
}
} else {
device.LogDebug("backup: no parent ", device.Name)
bytefromssh, err := SshClientRun(device)
if err != nil {
ers := fmt.Sprintf("Fatal error Device:%s: %s", device.Name, err.Error())
LogConsole.Error(ers)
device.LogError(ers)
device.StatusJob = "error"
return
}
bytefromsshclient = bytefromssh
}
if bytefromsshclient == nil {
ers := fmt.Sprintf("Fatal error Device:%s not bytes for backup", device.Name)
LogConsole.Error(ers)
device.LogError(ers)
device.StatusJob = "error"
return
}
err := SaveBackupFile(device, bytefromsshclient)
if err != nil {
ers := fmt.Sprintf("Bad saved config device %s Error: %s", device.Name, err.Error())
LogConsole.Error(ers)
device.LogError(ers)
device.StatusJob = "error"
return
}
device.StatusJob = "backup"
device.LogInfo("Backup complete")
}
func SaveBackupFile(device *Device, b []byte) error {
device.LogDebug(fmt.Sprintf("SaveBackupFile: saved backups... %s", device.Name))
backupfile := fmt.Sprintf("%s/%s", device.Dirbackup, device.BackupFileName)
FileBackupExist := FileExistBool(backupfile)
result := b
if device.Clearstring != "" {
device.LogDebug(fmt.Sprintf("SaveBackupFile: Need clear string in config... %s", device.Name))
result = RemoveStringFromBakcup(device, b)
}
if FileBackupExist == true {
com, err := FileCompareByteBool(backupfile, result)
if err != nil {
return err
}
if com == true {
return nil
}
}
var fn *os.File
var err error
if FileBackupExist == false {
device.LogDebug(fmt.Sprintf("SaveBackupFile: Create file... %s", backupfile))
fn, err = os.Create(backupfile)
if err != nil {
return errors.New(fmt.Sprintf("SaveBackupFile: Create file Error:%s", err.Error()))
}
} else {
fn, err = os.OpenFile(backupfile, os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
return errors.New(fmt.Sprintf("SaveBackupFile: Open file Error:%s", err.Error()))
}
}
device.LogDebug(fmt.Sprintf("SaveBackupFile: Write to file... %s", backupfile))
_, err = fn.Write(result)
if err != nil {
return errors.New(fmt.Sprintf("SaveBackupFile: Write to file Error:%s", err.Error()))
}
device.LogDebug(fmt.Sprintf("SaveBackupFile: Close file... %s", backupfile))
_ = fn.Close()
if FileBackupExist {
//CommitName := fmt.Sprintf("Change backup in device %s", device.Name)
if err := gitClient.SetCommit(backupfile); err != nil {
device.LogWarn(err)
LogConsole.Error(err)
return err
}
} else {
if err := gitClient.AddFile(backupfile); err != nil {
device.LogWarn(err)
LogConsole.Error(err)
return err
}
}
return nil
}
func RemoveStringFromBakcup(device *Device, b []byte) []byte {
device.LogDebug(fmt.Sprintf("RemoveStringFromBackup: ... %s", device.Name))
device.LogDebug(fmt.Sprintf("RemoveStringFromBackup: ... %s", device.Name))
regstr := fmt.Sprintf(`(?m:^%s.*$)`, device.Clearstring)
device.LogDebug(fmt.Sprintf("RemoveStringFromBackup: regexp %s", regstr))
re := regexp.MustCompile(regstr)
device.LogDebug(fmt.Sprintf("RemoveStringFromBackup: replace string %s", device.Name))
config := re.ReplaceAllString(string(b), "")
config = strings.Trim(config, "\r\n")
device.LogDebug(fmt.Sprintf("RemoveStringFromBackup: Remove empty string %s", device.Name))
return []byte(config)
}
func SetDefaultParameter(d *Device) {
if d.Timeout == 0 {
d.Timeout = ConfigV.GetInt("devicedefault.timeout")
d.LogDebug("SetDefaultParameter: Set default Timeout ", d.Name, d.Timeout)
}
if d.Every == 0 {
d.Every = ConfigV.GetInt("devicedefault.every")
d.LogDebug("SetDefaultParameter: Set default Every ", d.Name, d.Every)
}
if d.Rotate == 0 {
d.Rotate = ConfigV.GetInt("devicedefault.rotate")
d.LogDebug("SetDefaultParameter: Set default Rotate ", d.Name, d.Rotate)
}
if d.Command == "" {
d.Command = ConfigV.GetString("devicedefault.command")
d.LogDebug("SetDefaultParameter: Set default Command ", d.Name, d.Command)
}
if d.PortSSH == 0 {
d.LogDebug("SetDefaultParameter: Set default PortSSH", d.Name)
p, err := strconv.Atoi(ConfigV.GetString("devicedefault.portshh"))
if err != nil {
d.PortSSH = 22
d.LogDebug("SetDefaultParameter: Error parse ssh port field", d.PortSSH)
}
if err == nil || p < 65535 || p > 0 {
d.PortSSH = uint16(p)
d.LogDebug("SetDefaultParameter: Set default PortSSH ", d.Name, d.PortSSH)
} else {
d.PortSSH = 22
d.LogDebug("SetDefaultParameter: Error port ssh not range 1-65535", d.Name, d.PortSSH)
}
}
d.Authkey = false
if d.Key != "" {
d.LogDebug("SetDefaultParameter: Need use private key uniq ", d.Name, d.Key)
d.Authkey = true
}
if d.Authkey == false && d.Password == "" && d.Key != "" {
d.LogDebug("SetDefaultParameter: Need use private key uniq ", d.Name, d.Key)
d.Authkey = true
}
if d.Authkey == false && d.Password == "" && d.Key == "" && ConfigV.GetString("devicedefault.key") != "" {
d.Authkey = true
d.Key = ConfigV.GetString("devicedefault.key")
d.LogDebug("SetDefaultParameter: Need use private key default ", d.Name, d.Key)
}
if d.TimeFormat == "" {
d.TimeFormat = ConfigV.GetString("devicedefault.timeformat")
d.LogDebug("SetDefaultParameter: Set default time format ", d.Name, d.TimeFormat)
}
if d.Prefix == "" {
d.Prefix = ConfigV.GetString("devicedefault.prefix")
d.LogDebug("SetDefaultParameter: Set default Prefix", d.Name, d.Prefix)
}
if d.FileNameFormat == "" {
d.FileNameFormat = ConfigV.GetString("devicedefault.filenameformat")
d.LogDebug("SetDefaultParameter: Set default FileNameFormat", d.Name, d.FileNameFormat)
}
if d.Clearstring == "" {
d.Clearstring = ConfigV.GetString("devicedefault.clearstring")
d.LogDebug("SetDefaultParameter: Set default Clear string", d.Name, d.Clearstring)
}
d.Dirbackup = fmt.Sprintf("%s/%s", ConfigV.GetString("path.backup"), d.Name)
ditetimestring := time.Now().Format(d.TimeFormat)
nameinprefix := strings.ReplaceAll(d.FileNameFormat, "%p", d.Prefix)
nameintime := strings.ReplaceAll(nameinprefix, "%t", ditetimestring)
nameinname := strings.ReplaceAll(nameintime, "%n", d.Name)
d.BackupFileName = nameinname
d.LogDebug("SetDefaultParameter: Set default BackupFileName", d.Name, d.BackupFileName)
if d.DeviceHooks.Error == "" {
d.DeviceHooks.Error = ConfigV.GetString("devicedefault.hook.error")
d.LogDebug(fmt.Sprintf("SetDefaultParameter: Set default devicedefault.hook.error Velue %s in Device %s", d.DeviceHooks.Error, d.Name))
}
if d.DeviceHooks.Backup == "" {
d.DeviceHooks.Backup = ConfigV.GetString("devicedefault.hook.backup")
d.LogDebug(fmt.Sprintf("SetDefaultParameter: Set default devicedefault.hook.backup Velue %s in Device %s", d.DeviceHooks.Backup, d.Name))
}
if d.DeviceHooks.Skip == "" {
d.DeviceHooks.Skip = ConfigV.GetString("devicedefault.hook.skip")
d.LogDebug(fmt.Sprintf("SetDefaultParameter: Set default devicedefault.hook.skip Velue %s in Device %s", d.DeviceHooks.Skip, d.Name))
}
}