1 // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. See the AUTHORS file for names of contributors.
4
5 #include "db/log_reader.h"
6
7 #include <stdio.h>
8 #include "leveldb/env.h"
9 #include "util/coding.h"
10 #include "util/crc32c.h"
11
12 namespace leveldb {
13 namespace log {
14
~Reporter()15 Reader::Reporter::~Reporter() {
16 }
17
Reader(SequentialFile * file,Reporter * reporter,bool checksum,uint64_t initial_offset)18 Reader::Reader(SequentialFile* file, Reporter* reporter, bool checksum,
19 uint64_t initial_offset)
20 : file_(file),
21 reporter_(reporter),
22 checksum_(checksum),
23 backing_store_(new char[kBlockSize]),
24 buffer_(),
25 eof_(false),
26 last_record_offset_(0),
27 end_of_buffer_offset_(0),
28 initial_offset_(initial_offset),
29 resyncing_(initial_offset > 0) {
30 }
31
~Reader()32 Reader::~Reader() {
33 delete[] backing_store_;
34 }
35
SkipToInitialBlock()36 bool Reader::SkipToInitialBlock() {
37 size_t offset_in_block = initial_offset_ % kBlockSize;
38 uint64_t block_start_location = initial_offset_ - offset_in_block;
39
40 // Don't search a block if we'd be in the trailer
41 if (offset_in_block > kBlockSize - 6) {
42 offset_in_block = 0;
43 block_start_location += kBlockSize;
44 }
45
46 end_of_buffer_offset_ = block_start_location;
47
48 // Skip to start of first block that can contain the initial record
49 if (block_start_location > 0) {
50 Status skip_status = file_->Skip(block_start_location);
51 if (!skip_status.ok()) {
52 ReportDrop(block_start_location, skip_status);
53 return false;
54 }
55 }
56
57 return true;
58 }
59
ReadRecord(Slice * record,std::string * scratch)60 bool Reader::ReadRecord(Slice* record, std::string* scratch) {
61 if (last_record_offset_ < initial_offset_) {
62 if (!SkipToInitialBlock()) {
63 return false;
64 }
65 }
66
67 scratch->clear();
68 record->clear();
69 bool in_fragmented_record = false;
70 // Record offset of the logical record that we're reading
71 // 0 is a dummy value to make compilers happy
72 uint64_t prospective_record_offset = 0;
73
74 Slice fragment;
75 while (true) {
76 const unsigned int record_type = ReadPhysicalRecord(&fragment);
77
78 // ReadPhysicalRecord may have only had an empty trailer remaining in its
79 // internal buffer. Calculate the offset of the next physical record now
80 // that it has returned, properly accounting for its header size.
81 uint64_t physical_record_offset =
82 end_of_buffer_offset_ - buffer_.size() - kHeaderSize - fragment.size();
83
84 if (resyncing_) {
85 if (record_type == kMiddleType) {
86 continue;
87 } else if (record_type == kLastType) {
88 resyncing_ = false;
89 continue;
90 } else {
91 resyncing_ = false;
92 }
93 }
94
95 switch (record_type) {
96 case kFullType:
97 if (in_fragmented_record) {
98 // Handle bug in earlier versions of log::Writer where
99 // it could emit an empty kFirstType record at the tail end
100 // of a block followed by a kFullType or kFirstType record
101 // at the beginning of the next block.
102 if (scratch->empty()) {
103 in_fragmented_record = false;
104 } else {
105 ReportCorruption(scratch->size(), "partial record without end(1)");
106 }
107 }
108 prospective_record_offset = physical_record_offset;
109 scratch->clear();
110 *record = fragment;
111 last_record_offset_ = prospective_record_offset;
112 return true;
113
114 case kFirstType:
115 if (in_fragmented_record) {
116 // Handle bug in earlier versions of log::Writer where
117 // it could emit an empty kFirstType record at the tail end
118 // of a block followed by a kFullType or kFirstType record
119 // at the beginning of the next block.
120 if (scratch->empty()) {
121 in_fragmented_record = false;
122 } else {
123 ReportCorruption(scratch->size(), "partial record without end(2)");
124 }
125 }
126 prospective_record_offset = physical_record_offset;
127 scratch->assign(fragment.data(), fragment.size());
128 in_fragmented_record = true;
129 break;
130
131 case kMiddleType:
132 if (!in_fragmented_record) {
133 ReportCorruption(fragment.size(),
134 "missing start of fragmented record(1)");
135 } else {
136 scratch->append(fragment.data(), fragment.size());
137 }
138 break;
139
140 case kLastType:
141 if (!in_fragmented_record) {
142 ReportCorruption(fragment.size(),
143 "missing start of fragmented record(2)");
144 } else {
145 scratch->append(fragment.data(), fragment.size());
146 *record = Slice(*scratch);
147 last_record_offset_ = prospective_record_offset;
148 return true;
149 }
150 break;
151
152 case kEof:
153 if (in_fragmented_record) {
154 // This can be caused by the writer dying immediately after
155 // writing a physical record but before completing the next; don't
156 // treat it as a corruption, just ignore the entire logical record.
157 scratch->clear();
158 }
159 return false;
160
161 case kBadRecord:
162 if (in_fragmented_record) {
163 ReportCorruption(scratch->size(), "error in middle of record");
164 in_fragmented_record = false;
165 scratch->clear();
166 }
167 break;
168
169 default: {
170 char buf[40];
171 snprintf(buf, sizeof(buf), "unknown record type %u", record_type);
172 ReportCorruption(
173 (fragment.size() + (in_fragmented_record ? scratch->size() : 0)),
174 buf);
175 in_fragmented_record = false;
176 scratch->clear();
177 break;
178 }
179 }
180 }
181 return false;
182 }
183
LastRecordOffset()184 uint64_t Reader::LastRecordOffset() {
185 return last_record_offset_;
186 }
187
ReportCorruption(uint64_t bytes,const char * reason)188 void Reader::ReportCorruption(uint64_t bytes, const char* reason) {
189 ReportDrop(bytes, Status::Corruption(reason));
190 }
191
ReportDrop(uint64_t bytes,const Status & reason)192 void Reader::ReportDrop(uint64_t bytes, const Status& reason) {
193 if (reporter_ != NULL &&
194 end_of_buffer_offset_ - buffer_.size() - bytes >= initial_offset_) {
195 reporter_->Corruption(static_cast<size_t>(bytes), reason);
196 }
197 }
198
ReadPhysicalRecord(Slice * result)199 unsigned int Reader::ReadPhysicalRecord(Slice* result) {
200 while (true) {
201 if (buffer_.size() < kHeaderSize) {
202 if (!eof_) {
203 // Last read was a full read, so this is a trailer to skip
204 buffer_.clear();
205 Status status = file_->Read(kBlockSize, &buffer_, backing_store_);
206 end_of_buffer_offset_ += buffer_.size();
207 if (!status.ok()) {
208 buffer_.clear();
209 ReportDrop(kBlockSize, status);
210 eof_ = true;
211 return kEof;
212 } else if (buffer_.size() < kBlockSize) {
213 eof_ = true;
214 }
215 continue;
216 } else {
217 // Note that if buffer_ is non-empty, we have a truncated header at the
218 // end of the file, which can be caused by the writer crashing in the
219 // middle of writing the header. Instead of considering this an error,
220 // just report EOF.
221 buffer_.clear();
222 return kEof;
223 }
224 }
225
226 // Parse the header
227 const char* header = buffer_.data();
228 const uint32_t a = static_cast<uint32_t>(header[4]) & 0xff;
229 const uint32_t b = static_cast<uint32_t>(header[5]) & 0xff;
230 const unsigned int type = header[6];
231 const uint32_t length = a | (b << 8);
232 if (kHeaderSize + length > buffer_.size()) {
233 size_t drop_size = buffer_.size();
234 buffer_.clear();
235 if (!eof_) {
236 ReportCorruption(drop_size, "bad record length");
237 return kBadRecord;
238 }
239 // If the end of the file has been reached without reading |length| bytes
240 // of payload, assume the writer died in the middle of writing the record.
241 // Don't report a corruption.
242 return kEof;
243 }
244
245 if (type == kZeroType && length == 0) {
246 // Skip zero length record without reporting any drops since
247 // such records are produced by the mmap based writing code in
248 // env_posix.cc that preallocates file regions.
249 buffer_.clear();
250 return kBadRecord;
251 }
252
253 // Check crc
254 if (checksum_) {
255 uint32_t expected_crc = crc32c::Unmask(DecodeFixed32(header));
256 uint32_t actual_crc = crc32c::Value(header + 6, 1 + length);
257 if (actual_crc != expected_crc) {
258 // Drop the rest of the buffer since "length" itself may have
259 // been corrupted and if we trust it, we could find some
260 // fragment of a real log record that just happens to look
261 // like a valid log record.
262 size_t drop_size = buffer_.size();
263 buffer_.clear();
264 ReportCorruption(drop_size, "checksum mismatch");
265 return kBadRecord;
266 }
267 }
268
269 buffer_.remove_prefix(kHeaderSize + length);
270
271 // Skip physical record that started before initial_offset_
272 if (end_of_buffer_offset_ - buffer_.size() - kHeaderSize - length <
273 initial_offset_) {
274 result->clear();
275 return kBadRecord;
276 }
277
278 *result = Slice(header + kHeaderSize, length);
279 return type;
280 }
281 }
282
283 } // namespace log
284 } // namespace leveldb
285