/
snapshot.go
78 lines (67 loc) · 1.91 KB
/
snapshot.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
package integritymonitor
import (
"context"
"os"
"runtime"
"strings"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
"github.com/ScienceSoft-Inc/integrity-sum/internal/walker"
"github.com/ScienceSoft-Inc/integrity-sum/internal/worker"
)
const DefaultHashSize = 128
// CalculateAndWriteHashes calculates file hashes of a given directory and store
// them as a file for further usage.
func CalculateAndWriteHashes() error {
rootPath := viper.GetString("root-fs") + "/"
dirs := viper.GetStringSlice("dir")
file, err := os.Create(viper.GetString("out"))
if err != nil {
return err
}
defer func() {
file.Close()
if err != nil {
os.Remove(file.Name())
}
}()
hashes := make([]worker.FileHash, 0, DefaultHashSize*len(dirs))
for _, v := range dirs {
dir := rootPath + v
if _, err = os.Stat(dir); os.IsNotExist(err) {
logrus.Errorf("dir %s does not exist", dir)
return err
}
hashes = append(hashes, HashDir(rootPath, v, viper.GetString("algorithm"))...)
}
err = writeAsPlainText(file, hashes)
return err
}
// HashDir calculates file hashes of a given directory
func HashDir(rootPath, pathToMonitor, alg string) []worker.FileHash {
ctx, cancel := context.WithTimeout(context.Background(), viper.GetDuration("scan-dir-timeout"))
defer cancel()
log := logrus.StandardLogger()
fileHachC := worker.WorkersPool(
runtime.NumCPU(),
walker.ChanWalkDir(ctx, []string{rootPath + pathToMonitor}, log),
worker.NewWorker(ctx, alg, log),
)
hashes := make([]worker.FileHash, 0, DefaultHashSize)
for v := range fileHachC {
v.Path = strings.TrimPrefix(v.Path, rootPath)
hashes = append(hashes, v)
}
return hashes
}
func writeAsPlainText(file *os.File, hashes []worker.FileHash) error {
separator := " "
for _, v := range hashes {
_, err := file.WriteString(v.Hash + separator + v.Path + "\n")
if err != nil {
logrus.Errorf("failed to write hashes: %v", err)
return err
}
}
return nil
}