Debian Codegraph @

cmd/influx_inspect/verify/seriesfile/verify.go

raw symbols SCIP
1 package seriesfile
2
3 import (
4 "fmt"
5 "io/ioutil"
6 "os"
7 "path/filepath"
8 "runtime"
9 "sort"
10 "sync"
11
12 "github.com/influxdata/influxdb/tsdb"
13 "go.uber.org/zap"
14 )
15
16 // verifyResult contains the result of a Verify... call
17 type verifyResult struct {
18 valid bool
19 err error
20 }
21
22 // Verify contains configuration for running verification of series files.
23 type Verify struct {
24 Concurrent int
25 Logger *zap.Logger
26
27 done chan struct{}
28 }
29
30 // NewVerify constructs a Verify with good defaults.
31 func NewVerify() Verify {
32 return Verify{
33 Concurrent: runtime.GOMAXPROCS(0),
34 Logger: zap.NewNop(),
35 }
36 }
37
38 // VerifySeriesFile performs verifications on a series file. The error is only returned
39 // if there was some fatal problem with operating, not if there was a problem with the series file.
40 func (v Verify) VerifySeriesFile(filePath string) (valid bool, err error) {
41 v.Logger = v.Logger.With(zap.String("path", filePath))
42 v.Logger.Info("Verifying series file")
43
44 defer func() {
45 if rec := recover(); rec != nil {
46 v.Logger.Error("Panic verifying file", zap.String("recovered", fmt.Sprint(rec)))
47 valid = false
48 }
49 }()
50
51 partitionInfos, err := ioutil.ReadDir(filePath)
52 if os.IsNotExist(err) {
53 v.Logger.Error("Series file does not exist")
54 return false, nil
55 }
56 if err != nil {
57 return false, err
58 }
59
60 // Check every partition in concurrently.
61 concurrent := v.Concurrent
62 if concurrent <= 0 {
63 concurrent = 1
64 }
65 in := make(chan string, len(partitionInfos))
66 out := make(chan verifyResult, len(partitionInfos))
67
68 // Make sure all the workers are cleaned up when we return.
69 var wg sync.WaitGroup
70 defer wg.Wait()
71
72 // Set up cancellation. Any return will cause the workers to be cancelled.
73 v.done = make(chan struct{})
74 defer close(v.done)
75
76 for i := 0; i < concurrent; i++ {
77 wg.Add(1)
78 go func() {
79 defer wg.Done()
80
81 for partitionPath := range in {
82 valid, err := v.VerifyPartition(partitionPath)
83 select {
84 case out <- verifyResult{valid: valid, err: err}:
85 case <-v.done:
86 return
87 }
88 }
89 }()
90 }
91
92 // send off the work and read the results.
93 for _, partitionInfo := range partitionInfos {
94 in <- filepath.Join(filePath, partitionInfo.Name())
95 }
96 close(in)
97
98 for range partitionInfos {
99 result := <-out
100 if result.err != nil {
101 return false, err
102 } else if !result.valid {
103 return false, nil
104 }
105 }
106
107 return true, nil
108 }
109
110 // VerifyPartition performs verifications on a partition of a series file. The error is only returned
111 // if there was some fatal problem with operating, not if there was a problem with the partition.
112 func (v Verify) VerifyPartition(partitionPath string) (valid bool, err error) {
113 v.Logger = v.Logger.With(zap.String("partition", filepath.Base(partitionPath)))
114 v.Logger.Info("Verifying partition")
115
116 defer func() {
117 if rec := recover(); rec != nil {
118 v.Logger.Error("Panic verifying partition", zap.String("recovered", fmt.Sprint(rec)))
119 valid = false
120 }
121 }()
122
123 segmentInfos, err := ioutil.ReadDir(partitionPath)
124 if err != nil {
125 return false, err
126 }
127
128 segments := make([]*tsdb.SeriesSegment, 0, len(segmentInfos))
129 ids := make(map[uint64]IDData)
130
131 // check every segment
132 for _, segmentInfo := range segmentInfos {
133 select {
134 default:
135 case <-v.done:
136 return false, nil
137 }
138
139 segmentPath := filepath.Join(partitionPath, segmentInfo.Name())
140 segmentID, err := tsdb.ParseSeriesSegmentFilename(segmentInfo.Name())
141 if err != nil {
142 continue
143 }
144
145 if valid, err := v.VerifySegment(segmentPath, ids); err != nil {
146 return false, err
147 } else if !valid {
148 return false, nil
149 }
150
151 // open the segment for verifying the index. we want it to be open outside
152 // the for loop as well, so the defer is ok.
153 segment := tsdb.NewSeriesSegment(segmentID, segmentPath)
154 if err := segment.Open(); err != nil {
155 return false, err
156 }
157 defer segment.Close()
158
159 segments = append(segments, segment)
160 }
161
162 // check the index
163 indexPath := filepath.Join(partitionPath, "index")
164 if valid, err := v.VerifyIndex(indexPath, segments, ids); err != nil {
165 return false, err
166 } else if !valid {
167 return false, nil
168 }
169
170 return true, nil
171 }
172
173 // IDData keeps track of data about a series ID.
174 type IDData struct {
175 Offset int64
176 Key []byte
177 Deleted bool
178 }
179
180 // VerifySegment performs verifications on a segment of a series file. The error is only returned
181 // if there was some fatal problem with operating, not if there was a problem with the partition.
182 // The ids map is populated with information about the ids stored in the segment.
183 func (v Verify) VerifySegment(segmentPath string, ids map[uint64]IDData) (valid bool, err error) {
184 segmentName := filepath.Base(segmentPath)
185 v.Logger = v.Logger.With(zap.String("segment", segmentName))
186 v.Logger.Info("Verifying segment")
187
188 // Open up the segment and grab it's data.
189 segmentID, err := tsdb.ParseSeriesSegmentFilename(segmentName)
190 if err != nil {
191 return false, err
192 }
193 segment := tsdb.NewSeriesSegment(segmentID, segmentPath)
194 if err := segment.Open(); err != nil {
195 v.Logger.Error("Error opening segment", zap.Error(err))
196 return false, nil
197 }
198 defer segment.Close()
199 buf := newBuffer(segment.Data())
200
201 defer func() {
202 if rec := recover(); rec != nil {
203 v.Logger.Error("Panic verifying segment", zap.String("recovered", fmt.Sprint(rec)),
204 zap.Int64("offset", buf.offset))
205 valid = false
206 }
207 }()
208
209 // Skip the header: it has already been verified by the Open call.
210 if err := buf.advance(tsdb.SeriesSegmentHeaderSize); err != nil {
211 v.Logger.Error("Unable to advance buffer",
212 zap.Int64("offset", buf.offset),
213 zap.Error(err))
214 return false, nil
215 }
216
217 prevID, firstID := uint64(0), true
218
219 entries:
220 for len(buf.data) > 0 {
221 select {
222 default:
223 case <-v.done:
224 return false, nil
225 }
226
227 flag, id, key, sz := tsdb.ReadSeriesEntry(buf.data)
228
229 // Check the flag is valid and for id monotonicity.
230 switch flag {
231 case tsdb.SeriesEntryInsertFlag:
232 if !firstID && prevID > id {
233 v.Logger.Error("ID is not monotonically increasing",
234 zap.Uint64("prev_id", prevID),
235 zap.Uint64("id", id),
236 zap.Int64("offset", buf.offset))
237 return false, nil
238 }
239
240 firstID = false
241 prevID = id
242
243 if ids != nil {
244 keyCopy := make([]byte, len(key))
245 copy(keyCopy, key)
246
247 ids[id] = IDData{
248 Offset: tsdb.JoinSeriesOffset(segment.ID(), uint32(buf.offset)),
249 Key: keyCopy,
250 }
251 }
252
253 case tsdb.SeriesEntryTombstoneFlag:
254 if ids != nil {
255 data := ids[id]
256 data.Deleted = true
257 ids[id] = data
258 }
259
260 case 0: // if zero, there are no more entries
261 if err := buf.advance(sz); err != nil {
262 v.Logger.Error("Unable to advance buffer",
263 zap.Int64("offset", buf.offset),
264 zap.Error(err))
265 return false, nil
266 }
267 break entries
268
269 default:
270 v.Logger.Error("Invalid flag",
271 zap.Uint8("flag", flag),
272 zap.Int64("offset", buf.offset))
273 return false, nil
274 }
275
276 // Ensure the key parses. This may panic, but our defer handler should
277 // make the error message more usable by providing the key.
278 parsed := false
279 func() {
280 defer func() {
281 if rec := recover(); rec != nil {
282 v.Logger.Error("Panic parsing key",
283 zap.String("key", fmt.Sprintf("%x", key)),
284 zap.Int64("offset", buf.offset),
285 zap.String("recovered", fmt.Sprint(rec)))
286 }
287 }()
288 tsdb.ParseSeriesKey(key)
289 parsed = true
290 }()
291 if !parsed {
292 return false, nil
293 }
294
295 // Advance past the entry.
296 if err := buf.advance(sz); err != nil {
297 v.Logger.Error("Unable to advance buffer",
298 zap.Int64("offset", buf.offset),
299 zap.Error(err))
300 return false, nil
301 }
302 }
303
304 return true, nil
305 }
306
307 // VerifyIndex performs verification on an index in a series file. The error is only returned
308 // if there was some fatal problem with operating, not if there was a problem with the partition.
309 // The ids map must be built from verifying the passed in segments.
310 func (v Verify) VerifyIndex(indexPath string, segments []*tsdb.SeriesSegment,
311 ids map[uint64]IDData) (valid bool, err error) {
312 v.Logger.Info("Verifying index")
313
314 defer func() {
315 if rec := recover(); rec != nil {
316 v.Logger.Error("Panic verifying index", zap.String("recovered", fmt.Sprint(rec)))
317 valid = false
318 }
319 }()
320
321 index := tsdb.NewSeriesIndex(indexPath)
322 if err := index.Open(); err != nil {
323 v.Logger.Error("Error opening index", zap.Error(err))
324 return false, nil
325 }
326 defer index.Close()
327
328 if err := index.Recover(segments); err != nil {
329 v.Logger.Error("Error recovering index", zap.Error(err))
330 return false, nil
331 }
332
333 // we check all the ids in a consistent order to get the same errors if
334 // there is a problem
335 idsList := make([]uint64, 0, len(ids))
336 for id := range ids {
337 idsList = append(idsList, id)
338 }
339 sort.Slice(idsList, func(i, j int) bool {
340 return idsList[i] < idsList[j]
341 })
342
343 for _, id := range idsList {
344 select {
345 default:
346 case <-v.done:
347 return false, nil
348 }
349
350 IDData := ids[id]
351
352 expectedOffset, expectedID := IDData.Offset, id
353 if IDData.Deleted {
354 expectedOffset, expectedID = 0, 0
355 }
356
357 // check both that the offset is right and that we get the right
358 // id for the key
359 if gotOffset := index.FindOffsetByID(id); gotOffset != expectedOffset {
360 v.Logger.Error("Index inconsistency",
361 zap.Uint64("id", id),
362 zap.Int64("got_offset", gotOffset),
363 zap.Int64("expected_offset", expectedOffset))
364 return false, nil
365 }
366
367 if gotID := index.FindIDBySeriesKey(segments, IDData.Key); gotID != expectedID {
368 v.Logger.Error("Index inconsistency",
369 zap.Uint64("id", id),
370 zap.Uint64("got_id", gotID),
371 zap.Uint64("expected_id", expectedID))
372 return false, nil
373 }
374 }
375
376 return true, nil
377 }
378
379 // buffer allows one to safely advance a byte slice and keep track of how many bytes were advanced.
380 type buffer struct {
381 offset int64
382 data []byte
383 }
384
385 // newBuffer constructs a buffer with the provided data.
386 func newBuffer(data []byte) *buffer {
387 return &buffer{
388 offset: 0,
389 data: data,
390 }
391 }
392
393 // advance will consume n bytes from the data slice and return an error if there is not enough
394 // data to do so.
395 func (b *buffer) advance(n int64) error {
396 if int64(len(b.data)) < n {
397 return fmt.Errorf("unable to advance %d bytes: %d remaining", n, len(b.data))
398 }
399 b.data = b.data[n:]
400 b.offset += n
401 return nil
402 }