aboutsummaryrefslogtreecommitdiff
path: root/backup/fsck.go
blob: e7da7e010cc54c2a6f3b158153aeb031a089de18 (plain)
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
package backup

import (
	"code.laria.me/petrific/logging"
	"code.laria.me/petrific/objects"
	"code.laria.me/petrific/storage"
	"fmt"
	"runtime"
	"strings"
	"sync"
)

type FsckProblemType int

const (
	FsckStorageError FsckProblemType = iota
	FsckDeserializationError
	FsckUnexpectedBlobSize
)

type FsckProblem struct {
	Id                 objects.ObjectId
	Ancestors          []AncestorInfo
	ProblemType        FsckProblemType
	Err                error
	WantSize, HaveSize int
}

func (problem FsckProblem) String() string {
	desc := ""

	switch problem.ProblemType {
	case FsckStorageError:
		desc = fmt.Sprintf("Failed retrieving object from storage: %s", problem.Err)
	case FsckDeserializationError:
		desc = fmt.Sprintf("Object could not be deserialized: %s", problem.Err)
	case FsckUnexpectedBlobSize:
		desc = fmt.Sprintf("Unexpected blob size: have %d, want %d", problem.HaveSize, problem.WantSize)
	}

	ancestors := make([]string, len(problem.Ancestors))
	for i, a := range problem.Ancestors {
		ancestors[i] = a.String()
	}

	return fmt.Sprintf("%s. Object %s (path: %s)", desc, problem.Id, strings.Join(ancestors, " / "))
}

type AncestorInfo struct {
	Id   objects.ObjectId
	Type objects.ObjectType
	Name string
}

func (a AncestorInfo) String() string {
	if a.Name == "" {
		return string(a.Type) + " " + a.Id.String()
	} else {
		return fmt.Sprintf("%s of %s %s", a.Name, a.Type, a.Id)
	}
}

type queueElement struct {
	Id        objects.ObjectId
	Ancestors []AncestorInfo
	Extra     interface{}
}

type fsckProcess struct {
	st       storage.Storage
	blobs    bool
	problems chan<- FsckProblem
	wait     *sync.WaitGroup
	queue    chan queueElement
	seen     map[string]struct{}
	seenLock sync.Locker
	log      *logging.Log
}

func (fsck fsckProcess) onlyUnseen(elems []queueElement) []queueElement {
	fsck.seenLock.Lock()
	defer fsck.seenLock.Unlock()

	newElems := make([]queueElement, 0, len(elems))
	for _, elem := range elems {
		id := elem.Id.String()
		_, ok := fsck.seen[id]
		if !ok {
			newElems = append(newElems, elem)

			fsck.seen[id] = struct{}{}
		}
		fsck.log.Debug().Printf("seen %s? %t", id, ok)
	}

	return newElems
}

func (fsck fsckProcess) enqueue(elems []queueElement) {
	fsck.log.Debug().Printf("enqueueing %d elements", len(elems))

	elems = fsck.onlyUnseen(elems)

	fsck.wait.Add(len(elems))
	go func() {
		for _, elem := range elems {
			fsck.log.Debug().Printf("enqueueing %v", elem)
			fsck.queue <- elem
		}
	}()
}

func (fsck fsckProcess) handle(elem queueElement) {
	defer fsck.wait.Done()

	rawobj, err := storage.GetObject(fsck.st, elem.Id)
	if err != nil {
		fsck.problems <- FsckProblem{
			Id:          elem.Id,
			Ancestors:   elem.Ancestors,
			ProblemType: FsckStorageError,
			Err:         err,
		}

		return
	}

	obj, err := rawobj.Object()
	if err != nil {
		fsck.problems <- FsckProblem{
			Id:          elem.Id,
			Ancestors:   elem.Ancestors,
			ProblemType: FsckDeserializationError,
			Err:         err,
		}

		return
	}

	switch obj.Type() {
	case objects.OTBlob:
		fsck.handleBlob(elem, obj.(*objects.Blob))
	case objects.OTFile:
		fsck.handleFile(elem, obj.(*objects.File))
	case objects.OTTree:
		fsck.handleTree(elem, obj.(objects.Tree))
	case objects.OTSnapshot:
		fsck.handleSnapshot(elem, obj.(*objects.Snapshot))
	}
}

func (fsck fsckProcess) handleBlob(elem queueElement, obj *objects.Blob) {
	if elem.Extra == nil {
		return
	}

	want, ok := elem.Extra.(int)
	if !ok {
		return
	}
	have := len(*obj)

	if have != want {
		fsck.problems <- FsckProblem{
			Id:          elem.Id,
			Ancestors:   elem.Ancestors,
			ProblemType: FsckUnexpectedBlobSize,
			WantSize:    want,
			HaveSize:    have,
		}
	}
}

func (fsck fsckProcess) handleFile(elem queueElement, obj *objects.File) {
	if !fsck.blobs {
		return
	}

	enqueue := make([]queueElement, 0, len(*obj))

	for _, fragment := range *obj {
		enqueue = append(enqueue, queueElement{
			Id: fragment.Blob,
			Ancestors: append(elem.Ancestors, AncestorInfo{
				Id:   elem.Id,
				Type: objects.OTFile,
			}),
			Extra: int(fragment.Size),
		})
	}

	fsck.enqueue(enqueue)
}

func (fsck fsckProcess) handleTree(elem queueElement, obj objects.Tree) {
	ancestors := func(name string) []AncestorInfo {
		return append(elem.Ancestors, AncestorInfo{
			Id:   elem.Id,
			Type: objects.OTTree,
			Name: name,
		})
	}

	enqueue := make([]queueElement, 0, len(obj))

	for name, entry := range obj {
		switch entry.Type() {
		case objects.TETDir:
			enqueue = append(enqueue, queueElement{
				Id:        entry.(objects.TreeEntryDir).Ref,
				Ancestors: ancestors(name),
			})
		case objects.TETFile:
			enqueue = append(enqueue, queueElement{
				Id:        entry.(objects.TreeEntryFile).Ref,
				Ancestors: ancestors(name),
			})
		}
	}

	fsck.enqueue(enqueue)
}

func (fsck fsckProcess) handleSnapshot(elem queueElement, obj *objects.Snapshot) {
	fsck.enqueue([]queueElement{
		{Id: obj.Tree},
	})
}

func (fsck fsckProcess) worker(i int) {
	for elem := range fsck.queue {
		fsck.handle(elem)
	}
	fsck.log.Debug().Printf("stopping worker %d", i)
}

// Fsck checks the consistency of objects in a storage
func Fsck(
	st storage.Storage,
	start *objects.ObjectId,
	blobs bool,
	problems chan<- FsckProblem,
	log *logging.Log,
) error {
	proc := fsckProcess{
		st:       st,
		blobs:    blobs,
		problems: problems,
		wait:     new(sync.WaitGroup),
		queue:    make(chan queueElement),
		seen:     make(map[string]struct{}),
		seenLock: new(sync.Mutex),
		log:      log,
	}

	enqueue := []queueElement{}

	if start == nil {
		types := []objects.ObjectType{
			objects.OTFile,
			objects.OTTree,
			objects.OTSnapshot,
		}
		for _, t := range types {
			ids, err := st.List(t)
			if err != nil {
				return err
			}

			for _, id := range ids {
				enqueue = append(enqueue, queueElement{Id: id})
			}
		}
	} else {
		enqueue = []queueElement{
			{Id: *start},
		}
	}

	if len(enqueue) == 0 {
		return nil
	}

	for i := 0; i < runtime.NumCPU(); i++ {
		log.Debug().Printf("starting worker %d", i)
		go proc.worker(i)
	}

	proc.enqueue(enqueue)

	proc.wait.Wait()
	close(proc.queue)
	return nil
}