/
hash.go
425 lines (341 loc) · 10.6 KB
/
hash.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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package replica
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"hash"
"hash/crc64"
"io"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/gofrs/flock"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/longhorn/sparse-tools/sparse"
xattrType "github.com/longhorn/sparse-tools/types"
"github.com/longhorn/longhorn-engine/pkg/types"
diskutil "github.com/longhorn/longhorn-engine/pkg/util/disk"
)
const (
defaultHashMethod = "crc64"
FileLockDirectory = "/host/var/lib/longhorn/.lock"
HashLockFileName = "hash"
)
type SnapshotHashStatus struct {
StatusLock sync.RWMutex
State ProgressState
Checksum string
Error string
SilentlyCorrupted bool
}
type SnapshotHashJob struct {
sync.Mutex
Ctx context.Context
CancelFunc context.CancelFunc
SnapshotName string
Rehash bool
file *os.File
SnapshotHashStatus
}
func NewSnapshotHashJob(ctx context.Context, cancel context.CancelFunc, snapshotName string, rehash bool) *SnapshotHashJob {
return &SnapshotHashJob{
Ctx: ctx,
CancelFunc: cancel,
SnapshotName: snapshotName,
Rehash: rehash,
SnapshotHashStatus: SnapshotHashStatus{
State: ProgressStateInProgress,
},
}
}
func (t *SnapshotHashJob) LockFile() (fileLock *flock.Flock, err error) {
defer func() {
if err != nil && fileLock != nil && fileLock.Path() != "" {
if err := os.RemoveAll(fileLock.Path()); err != nil {
logrus.WithError(err).Warnf("Failed to remove lock file %v", fileLock.Path())
}
}
}()
err = os.MkdirAll(FileLockDirectory, 0755)
if err != nil {
return nil, err
}
fileLock = flock.New(filepath.Join(FileLockDirectory, HashLockFileName))
// Blocking lock
err = fileLock.Lock()
if err != nil {
return nil, errors.Wrapf(err, "failed to fetch the file lock for hashing snapshot %v", t.SnapshotName)
}
return fileLock, nil
}
func (t *SnapshotHashJob) UnlockFile(fileLock *flock.Flock) {
fileLock.Unlock()
}
func (t *SnapshotHashJob) Execute() (err error) {
var checksum string
var changeTime string
var lastHashedAt string
var silentlyCorrupted bool
defer func() {
t.StatusLock.Lock()
defer t.StatusLock.Unlock()
t.Checksum = checksum
t.SilentlyCorrupted = silentlyCorrupted
if err == nil {
t.State = ProgressStateComplete
logrus.Infof("Snapshot %v checksum %v", t.SnapshotName, checksum)
// Checksum is not recalculated in this task, so return directly.
if lastHashedAt == "" {
return
}
SetSnapshotHashInfoToChecksumFile(t.SnapshotName, &xattrType.SnapshotHashInfo{
Method: defaultHashMethod,
Checksum: checksum,
ChangeTime: changeTime,
LastHashedAt: lastHashedAt,
SilentlyCorrupted: silentlyCorrupted,
})
remain, err := t.isChangeTimeRemain(changeTime)
if !remain {
if err == nil {
err = fmt.Errorf("snapshot %v modification time is changed", t.SnapshotName)
}
// Do the best to delete the useless checksum file.
// The deletion failure is acceptable, because the mismatching timestamps
// will trigger the rehash in the next hash request.
DeleteSnapshotHashInfoChecksumFile(t.SnapshotName)
}
}
if err != nil {
logrus.WithError(err).Errorf("failed to hash snapshot %v", t.SnapshotName)
t.State = ProgressStateError
t.Error = err.Error()
}
}()
// Each node can have only one snapshot hashing task at the same time per node.
// When the snapshot hashing task is started, the task tries to fetch the file lock
// (${fileLockDirectory}/hash). If the lock file is held by another task, it will stuck
// here and wait for the lock. The file is unlocked after the task is completed.
fileLock, err := t.LockFile()
if err != nil {
return err
}
defer t.UnlockFile(fileLock)
changeTime, err = GetSnapshotChangeTime(t.SnapshotName)
if err != nil {
return err
}
// If the silent corruption is detected, don't need to recalculate the checksum.
// Just set SilentlyCorrupted to true and return it.
silentlyCorrupted, err = t.isSilentCorruptionAlreadyDetected(changeTime)
if err != nil {
return err
}
if silentlyCorrupted {
return nil
}
requireRehash := true
if !t.Rehash {
requireRehash, checksum, err = t.isRehashRequired(changeTime)
if err != nil {
return err
}
if !requireRehash {
return nil
}
}
logrus.Infof("Starting hashing snapshot %v", t.SnapshotName)
lastHashedAt = time.Now().UTC().Format(time.RFC3339)
checksum, err = hashSnapshot(t.Ctx, t.SnapshotName)
if err != nil {
return err
}
// If the silent corruption is detected, the checksum file will not be overrode.
// The scene will be preserved and only set silentlyCorrupted to true.
if t.isSnapshotSilentlyCorrupted(checksum) {
silentlyCorrupted = true
info, err := GetSnapshotHashInfoFromChecksumFile(t.SnapshotName)
if err != nil {
return err
}
checksum = info.Checksum
lastHashedAt = info.LastHashedAt
changeTime = info.ChangeTime
}
return nil
}
func (t *SnapshotHashJob) isSnapshotSilentlyCorrupted(checksum string) bool {
// To detect the silent corruption, read the changeTime and checksum already recorded in the snapshot disk file first.
// Then, rehash the file and compare the changeTimes and checksums.
// If the changeTimes are identical but the checksums differ, the file is silently corrupted.
info, err := GetSnapshotHashInfoFromChecksumFile(t.SnapshotName)
if err != nil || info == nil {
return false
}
existingChecksum := info.Checksum
existingChangeTime := info.ChangeTime
if existingChecksum == "" || existingChangeTime == "" {
return false
}
remain, _ := t.isChangeTimeRemain(existingChangeTime)
if !remain {
return false
}
if checksum != existingChecksum {
return true
}
return false
}
func GetSnapshotChangeTime(snapshotName string) (string, error) {
fileInfo, err := os.Stat(diskutil.GenerateSnapshotDiskName(snapshotName))
if err != nil {
return "", err
}
stat := fileInfo.Sys().(*syscall.Stat_t)
return time.Unix(int64(stat.Ctim.Sec), int64(stat.Ctim.Nsec)).String(), nil
}
func GetSnapshotHashInfoFromChecksumFile(snapshotName string) (*xattrType.SnapshotHashInfo, error) {
dir, err := os.Getwd()
if err != nil {
return nil, errors.Wrap(err, "failed to get working directory when getting snapshot hash info")
}
path := filepath.Join(dir, diskutil.GenerateSnapshotDiskChecksumName(diskutil.GenerateSnapshotDiskName(snapshotName)))
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
var info xattrType.SnapshotHashInfo
if err := json.NewDecoder(f).Decode(&info); err != nil {
return nil, err
}
return &info, nil
}
func SetSnapshotHashInfoToChecksumFile(snapshotName string, info *xattrType.SnapshotHashInfo) error {
dir, err := os.Getwd()
if err != nil {
return errors.Wrap(err, "failed to get working directory when setting snapshot hash info")
}
path := filepath.Join(dir, diskutil.GenerateSnapshotDiskChecksumName(diskutil.GenerateSnapshotDiskName(snapshotName)))
return encodeToFile(xattrType.SnapshotHashInfo{
Method: defaultHashMethod,
Checksum: info.Checksum,
ChangeTime: info.ChangeTime,
LastHashedAt: info.LastHashedAt,
SilentlyCorrupted: info.SilentlyCorrupted,
}, path)
}
func encodeToFile(obj interface{}, path string) (err error) {
tmpPath := fmt.Sprintf("%s.%s", path, tmpFileSuffix)
defer func() {
var rollbackErr error
if err != nil {
if _, err := os.Stat(tmpPath); err == nil {
if err := os.Remove(tmpPath); err != nil {
rollbackErr = err
}
}
}
err = types.GenerateFunctionErrorWithRollback(err, rollbackErr)
}()
f, err := os.Create(tmpPath)
if err != nil {
return err
}
defer f.Close()
if err := json.NewEncoder(f).Encode(&obj); err != nil {
return err
}
return os.Rename(tmpPath, path)
}
func DeleteSnapshotHashInfoChecksumFile(snapshotName string) error {
dir, err := os.Getwd()
if err != nil {
return errors.Wrap(err, "failed to get working directory when deleting snapshot hash info")
}
path := filepath.Join(dir, diskutil.GenerateSnapshotDiskChecksumName(diskutil.GenerateSnapshotDiskName(snapshotName)))
return os.RemoveAll(path)
}
func (t *SnapshotHashJob) isSilentCorruptionAlreadyDetected(currentChangeTime string) (bool, error) {
info, err := GetSnapshotHashInfoFromChecksumFile(t.SnapshotName)
if err != nil || info == nil {
if !strings.Contains(err.Error(), syscall.ENOENT.Error()) {
return false, errors.Wrapf(err, "failed to get snapshot %v last hash info from checksum file", t.SnapshotName)
}
return false, nil
}
if currentChangeTime == info.ChangeTime {
return info.SilentlyCorrupted, nil
}
return false, nil
}
func (t *SnapshotHashJob) isRehashRequired(currentChangeTime string) (bool, string, error) {
info, err := GetSnapshotHashInfoFromChecksumFile(t.SnapshotName)
if err != nil || info == nil {
if !strings.Contains(err.Error(), syscall.ENOENT.Error()) {
return true, "", errors.Wrapf(err, "failed to get snapshot %v last hash info from checksum file", t.SnapshotName)
}
return true, "", nil
}
checksum := info.Checksum
changeTime := info.ChangeTime
if changeTime != currentChangeTime || checksum == "" {
return true, "", nil
}
return false, checksum, nil
}
func (t *SnapshotHashJob) isChangeTimeRemain(oldChangeTime string) (bool, error) {
newChangeTime, err := GetSnapshotChangeTime(t.SnapshotName)
if err != nil {
return false, err
}
return oldChangeTime == newChangeTime, nil
}
func hashSnapshot(ctx context.Context, snapshotName string) (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", errors.Wrapf(err, "failed to get working directory when hashing snapshot %v", snapshotName)
}
path := filepath.Join(dir, diskutil.GenerateSnapshotDiskName(snapshotName))
f, err := sparse.NewDirectFileIoProcessor(path, os.O_RDONLY, 0)
if err != nil {
return "", errors.Wrapf(err, "failed to open %v", path)
}
defer f.Close()
h, err := newHashMethod(defaultHashMethod)
if err != nil {
return "", err
}
if err := dataCopy(ctx, h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
type readerFunc func(p []byte) (n int, err error)
func (rf readerFunc) Read(p []byte) (n int, err error) {
return rf(p)
}
func dataCopy(ctx context.Context, dst io.Writer, src io.Reader) error {
_, err := io.Copy(dst, readerFunc(func(p []byte) (int, error) {
select {
case <-ctx.Done():
return 0, ctx.Err()
default:
return src.Read(p)
}
}))
return err
}
func newHashMethod(method string) (hash.Hash, error) {
switch method {
case "crc64":
return crc64.New(crc64.MakeTable(crc64.ISO)), nil
default:
return nil, fmt.Errorf("invalid hash method %v", method)
}
}