forked from perkeep/perkeep
/
reindex.go
252 lines (227 loc) · 6.37 KB
/
reindex.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
/*
Copyright 2013 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package diskpacked
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strconv"
"camlistore.org/pkg/blob"
"camlistore.org/pkg/context"
"camlistore.org/pkg/jsonconfig"
"camlistore.org/pkg/sorted"
// possible index formats
_ "camlistore.org/pkg/sorted/kvfile"
_ "camlistore.org/pkg/sorted/leveldb"
_ "camlistore.org/pkg/sorted/sqlite"
)
var camliDebug, _ = strconv.ParseBool(os.Getenv("CAMLI_DEBUG"))
// Reindex rewrites the index files of the diskpacked .pack files
func Reindex(root string, overwrite bool, indexConf jsonconfig.Obj) (err error) {
// there is newStorage, but that may open a file for writing
var s = &storage{root: root}
index, err := newIndex(root, indexConf)
if err != nil {
return err
}
defer func() {
closeErr := index.Close()
// just returning the first error - if the index or disk is corrupt
// and can't close, it's very likely these two errors are related and
// have the same root cause.
if err == nil {
err = closeErr
}
}()
ctx := context.TODO() // TODO(tgulacsi): get the verbosity from context
for i := 0; i >= 0; i++ {
fh, err := os.Open(s.filename(i))
if err != nil {
if os.IsNotExist(err) {
break
}
return err
}
err = s.reindexOne(ctx, index, overwrite, i)
fh.Close()
if err != nil {
return err
}
}
return nil
}
func (s *storage) reindexOne(ctx *context.Context, index sorted.KeyValue, overwrite bool, packID int) error {
var batch sorted.BatchMutation
if overwrite {
batch = index.BeginBatch()
}
allOk := true
// TODO(tgulacsi): proper verbose from context
verbose := camliDebug
misses := make(map[blob.Ref]string, 8)
err := s.walkPack(verbose, packID,
func(packID int, ref blob.Ref, offset int64, size uint32) error {
if !ref.Valid() {
if camliDebug {
log.Printf("found deleted blob in %d at %d with size %d", packID, offset, size)
}
return nil
}
meta := blobMeta{packID, offset, size}.String()
if overwrite && batch != nil {
batch.Set(ref.String(), meta)
return nil
}
if _, ok := misses[ref]; ok { // maybe this is the last of this blob.
delete(misses, ref)
}
if old, err := index.Get(ref.String()); err != nil {
allOk = false
if err == sorted.ErrNotFound {
log.Println(ref.String() + ": cannot find in index!")
} else {
log.Println(ref.String()+": error getting from index: ", err.Error())
}
} else if old != meta {
if old > meta {
misses[ref] = meta
log.Printf("WARN: possible duplicate blob %s", ref.String())
} else {
allOk = false
log.Printf("ERROR: index mismatch for %s - index=%s, meta=%s!", ref.String(), old, meta)
}
}
return nil
})
if err != nil {
return err
}
for ref, meta := range misses {
log.Printf("ERROR: index mismatch for %s (%s)!", ref.String(), meta)
allOk = false
}
if overwrite && batch != nil {
if err := index.CommitBatch(batch); err != nil {
return err
}
} else if !allOk {
return fmt.Errorf("index does not match data in %d", packID)
}
return nil
}
// Walk walks the storage and calls the walker callback with each blobref
// stops if walker returns non-nil error, and returns that
func (s *storage) Walk(ctx *context.Context,
walker func(packID int, ref blob.Ref, offset int64, size uint32) error) error {
// TODO(tgulacsi): proper verbose flag from context
verbose := camliDebug
for i := 0; i >= 0; i++ {
fh, err := os.Open(s.filename(i))
if err != nil {
if os.IsNotExist(err) {
break
}
return err
}
fh.Close()
if err = s.walkPack(verbose, i, walker); err != nil {
return err
}
}
return nil
}
// walkPack walks the given pack and calls the walker callback with each blobref.
// Stops if walker returns non-nil error and returns that.
func (s *storage) walkPack(verbose bool, packID int,
walker func(packID int, ref blob.Ref, offset int64, size uint32) error) error {
fh, err := os.Open(s.filename(packID))
if err != nil {
return err
}
defer fh.Close()
name := fh.Name()
var (
pos int64
size uint32
ref blob.Ref
)
errAt := func(prefix, suffix string) error {
if prefix != "" {
prefix = prefix + " "
}
if suffix != "" {
suffix = " " + suffix
}
return fmt.Errorf(prefix+"at %d (0x%x) in %q:"+suffix, pos, pos, name)
}
br := bufio.NewReaderSize(fh, 512)
for {
if b, err := br.ReadByte(); err != nil {
if err == io.EOF {
break
}
return errAt("error while reading", err.Error())
} else if b != '[' {
return errAt(fmt.Sprintf("found byte 0x%x", b), "but '[' should be here!")
}
chunk, err := br.ReadSlice(']')
if err != nil {
if err == io.EOF {
break
}
return errAt("error reading blob header", err.Error())
}
m := len(chunk)
chunk = chunk[:m-1]
i := bytes.IndexByte(chunk, byte(' '))
if i <= 0 {
return errAt("", fmt.Sprintf("bad header format (no space in %q)", chunk))
}
size64, err := strconv.ParseUint(string(chunk[i+1:]), 10, 32)
if err != nil {
return errAt(fmt.Sprintf("cannot parse size %q as int", chunk[i+1:]), err.Error())
}
size = uint32(size64)
if deletedBlobRef.Match(chunk[:i]) {
ref = blob.Ref{}
if verbose {
log.Printf("found deleted at %d", pos)
}
} else {
var ok bool
ref, ok = blob.Parse(string(chunk[:i]))
if !ok {
return errAt("", fmt.Sprintf("cannot parse %q as blobref", chunk[:i]))
}
if verbose {
log.Printf("found %s at %d", ref, pos)
}
}
if err = walker(packID, ref, pos+1+int64(m), size); err != nil {
return err
}
pos += 1 + int64(m)
// TODO(tgulacsi): not just seek, but check the hashes of the files
// maybe with a different command-line flag, only.
if pos, err = fh.Seek(pos+int64(size), 0); err != nil {
return errAt("", "cannot seek +"+strconv.FormatUint(size64, 10)+" bytes")
}
// drain the buffer after the underlying reader Seeks
io.CopyN(ioutil.Discard, br, int64(br.Buffered()))
}
return nil
}