1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.replication.regionserver;
20
21 import java.io.Closeable;
22 import java.io.FileNotFoundException;
23 import java.io.IOException;
24 import java.util.Iterator;
25 import java.util.NoSuchElementException;
26 import java.util.concurrent.PriorityBlockingQueue;
27
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.apache.hadoop.conf.Configuration;
31 import org.apache.hadoop.fs.FileStatus;
32 import org.apache.hadoop.fs.FileSystem;
33 import org.apache.hadoop.fs.Path;
34 import org.apache.hadoop.hbase.HConstants;
35 import org.apache.hadoop.hbase.classification.InterfaceAudience;
36 import org.apache.hadoop.hbase.classification.InterfaceStability;
37 import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader;
38 import org.apache.hadoop.hbase.util.CancelableProgressable;
39 import org.apache.hadoop.hbase.util.FSUtils;
40 import org.apache.hadoop.hbase.util.LeaseNotRecoveredException;
41 import org.apache.hadoop.hbase.wal.WAL.Entry;
42 import org.apache.hadoop.hbase.wal.WAL.Reader;
43 import org.apache.hadoop.hbase.wal.WALFactory;
44 import org.apache.hadoop.ipc.RemoteException;
45
46
47
48
49
50
51 @InterfaceAudience.Private
52 @InterfaceStability.Evolving
53 public class WALEntryStream implements Iterator<Entry>, Closeable, Iterable<Entry> {
54 private static final Log LOG = LogFactory.getLog(WALEntryStream.class);
55
56 private Reader reader;
57 private Path currentPath;
58
59 private Entry currentEntry;
60
61 private long currentPosition = 0;
62 private PriorityBlockingQueue<Path> logQueue;
63 private FileSystem fs;
64 private Configuration conf;
65 private MetricsSource metrics;
66
67
68
69
70
71
72
73
74
75 public WALEntryStream(PriorityBlockingQueue<Path> logQueue, FileSystem fs, Configuration conf,
76 MetricsSource metrics)
77 throws IOException {
78 this(logQueue, fs, conf, 0, metrics);
79 }
80
81
82
83
84
85
86
87
88
89 public WALEntryStream(PriorityBlockingQueue<Path> logQueue, FileSystem fs, Configuration conf,
90 long startPosition, MetricsSource metrics) throws IOException {
91 this.logQueue = logQueue;
92 this.fs = fs;
93 this.conf = conf;
94 this.currentPosition = startPosition;
95 this.metrics = metrics;
96 }
97
98
99
100
101
102 @Override
103 public boolean hasNext() {
104 if (currentEntry == null) {
105 try {
106 tryAdvanceEntry();
107 } catch (Exception e) {
108 throw new WALEntryStreamRuntimeException(e);
109 }
110 }
111 return currentEntry != null;
112 }
113
114
115
116
117
118
119 @Override
120 public Entry next() {
121 if (!hasNext()) throw new NoSuchElementException();
122 Entry save = currentEntry;
123 currentEntry = null;
124 return save;
125 }
126
127
128
129
130 @Override
131 public void remove() {
132 throw new UnsupportedOperationException();
133 }
134
135
136
137
138 @Override
139 public void close() throws IOException {
140 closeReader();
141 }
142
143
144
145
146 @Override
147 public Iterator<Entry> iterator() {
148 return this;
149 }
150
151
152
153
154 public long getPosition() {
155 return currentPosition;
156 }
157
158
159
160
161 public Path getCurrentPath() {
162 return currentPath;
163 }
164
165 private String getCurrentPathStat() {
166 StringBuilder sb = new StringBuilder();
167 if (currentPath != null) {
168 sb.append("currently replicating from: ").append(currentPath).append(" at position: ")
169 .append(currentPosition).append("\n");
170 } else {
171 sb.append("no replication ongoing, waiting for new log");
172 }
173 return sb.toString();
174 }
175
176
177
178
179
180
181 public void reset() throws IOException {
182 if (reader != null && currentPath != null) {
183 resetReader();
184 }
185 }
186
187 private void setPosition(long position) {
188 currentPosition = position;
189 }
190
191 private void setCurrentPath(Path path) {
192 this.currentPath = path;
193 }
194
195 private void tryAdvanceEntry() throws IOException {
196 if (checkReader()) {
197 readNextEntryAndSetPosition();
198 if (currentEntry == null) {
199 if (logQueue.size() > 1) {
200
201
202
203 resetReader();
204 readNextEntryAndSetPosition();
205 if (currentEntry == null) {
206 if (checkAllBytesParsed()) {
207 dequeueCurrentLog();
208 if (openNextLog()) {
209 readNextEntryAndSetPosition();
210 }
211 }
212 }
213 }
214 }
215 }
216
217 }
218
219
220 private boolean checkAllBytesParsed() throws IOException {
221
222 final long trailerSize = currentTrailerSize();
223 FileStatus stat = null;
224 try {
225 stat = fs.getFileStatus(this.currentPath);
226 } catch (IOException exception) {
227 LOG.warn("Couldn't get file length information about log " + this.currentPath + ", it "
228 + (trailerSize < 0 ? "was not" : "was") + " closed cleanly " + getCurrentPathStat());
229 metrics.incrUnknownFileLengthForClosedWAL();
230 }
231 if (stat != null) {
232 if (trailerSize < 0) {
233 if (currentPosition < stat.getLen()) {
234 final long skippedBytes = stat.getLen() - currentPosition;
235 if (LOG.isDebugEnabled()) {
236 LOG.debug("Reached the end of WAL file '" + currentPath
237 + "'. It was not closed cleanly, so we did not parse " + skippedBytes
238 + " bytes of data. This is normally ok.");
239 }
240 metrics.incrUncleanlyClosedWALs();
241 metrics.incrBytesSkippedInUncleanlyClosedWALs(skippedBytes);
242 }
243 } else if (currentPosition + trailerSize < stat.getLen()) {
244 LOG.warn("Processing end of WAL file '" + currentPath + "'. At position " + currentPosition
245 + ", which is too far away from reported file length " + stat.getLen()
246 + ". Restarting WAL reading (see HBASE-15983 for details). " + getCurrentPathStat());
247 setPosition(0);
248 resetReader();
249 metrics.incrRestartedWALReading();
250 metrics.incrRepeatedFileBytes(currentPosition);
251 return false;
252 }
253 }
254 if (LOG.isTraceEnabled()) {
255 LOG.trace("Reached the end of log " + this.currentPath + ", and the length of the file is "
256 + (stat == null ? "N/A" : stat.getLen()));
257 }
258 metrics.incrCompletedWAL();
259 return true;
260 }
261
262 private void dequeueCurrentLog() throws IOException {
263 if (LOG.isDebugEnabled()) {
264 LOG.debug("Reached the end of log " + currentPath);
265 }
266 closeReader();
267 logQueue.remove();
268 setPosition(0);
269 metrics.decrSizeOfLogQueue();
270 }
271
272 private void readNextEntryAndSetPosition() throws IOException {
273 Entry readEntry = reader.next();
274 long readerPos = reader.getPosition();
275 if (readEntry != null) {
276 metrics.incrLogEditsRead();
277 metrics.incrLogReadInBytes(readerPos - currentPosition);
278 }
279 currentEntry = readEntry;
280 setPosition(readerPos);
281 }
282
283 private void closeReader() throws IOException {
284 if (reader != null) {
285 reader.close();
286 reader = null;
287 }
288 }
289
290
291 private boolean checkReader() throws IOException {
292 if (reader == null) {
293 return openNextLog();
294 }
295 return true;
296 }
297
298
299 private boolean openNextLog() throws IOException {
300 Path nextPath = logQueue.peek();
301 if (nextPath != null) {
302 openReader(nextPath);
303 if (reader != null) return true;
304 }
305 return false;
306 }
307
308 private Path getArchivedLog(Path path) throws IOException {
309 Path rootDir = FSUtils.getRootDir(conf);
310 Path oldLogDir = new Path(rootDir, HConstants.HREGION_OLDLOGDIR_NAME);
311 Path archivedLogLocation = new Path(oldLogDir, path.getName());
312 if (fs.exists(archivedLogLocation)) {
313 LOG.info("Log " + path + " was moved to " + archivedLogLocation);
314 return archivedLogLocation;
315 } else {
316 LOG.error("Couldn't locate log: " + path);
317 return path;
318 }
319 }
320
321 private void handleFileNotFound(Path path, FileNotFoundException fnfe) throws IOException {
322
323 Path archivedLog = getArchivedLog(path);
324 if (!path.equals(archivedLog)) {
325 openReader(archivedLog);
326 } else {
327 throw fnfe;
328 }
329 }
330 private void openReader(Path path) throws IOException {
331 try {
332
333
334 if (reader == null || !getCurrentPath().equals(path)) {
335 closeReader();
336 reader = WALFactory.createReader(fs, path, conf);
337 seek();
338 setCurrentPath(path);
339 } else {
340 resetReader();
341 }
342 } catch (FileNotFoundException fnfe) {
343 handleFileNotFound(path, fnfe);
344 } catch (RemoteException re) {
345 IOException ioe = re.unwrapRemoteException(FileNotFoundException.class);
346 if (!(ioe instanceof FileNotFoundException)) throw ioe;
347 handleFileNotFound(path, (FileNotFoundException)ioe);
348 } catch (LeaseNotRecoveredException lnre) {
349
350 LOG.warn("Try to recover the WAL lease " + currentPath, lnre);
351 recoverLease(conf, currentPath);
352 reader = null;
353 } catch (NullPointerException npe) {
354
355
356
357 LOG.warn("Got NPE opening reader, will retry.");
358 reader = null;
359 }
360 }
361
362
363 private void recoverLease(final Configuration conf, final Path path) {
364 try {
365 final FileSystem dfs = FSUtils.getCurrentFileSystem(conf);
366 FSUtils fsUtils = FSUtils.getInstance(dfs, conf);
367 fsUtils.recoverFileLease(dfs, path, conf, new CancelableProgressable() {
368 @Override
369 public boolean progress() {
370 LOG.debug("recover WAL lease: " + path);
371 return true;
372 }
373 });
374 } catch (IOException e) {
375 LOG.warn("unable to recover lease for WAL: " + path, e);
376 }
377 }
378
379 private void resetReader() throws IOException {
380 try {
381 reader.reset();
382 seek();
383 } catch (FileNotFoundException fnfe) {
384
385 Path archivedLog = getArchivedLog(currentPath);
386 if (!currentPath.equals(archivedLog)) {
387 openReader(archivedLog);
388 } else {
389 throw fnfe;
390 }
391 } catch (NullPointerException npe) {
392 throw new IOException("NPE resetting reader, likely HDFS-4380", npe);
393 }
394 }
395
396 private void seek() throws IOException {
397 if (currentPosition != 0) {
398 reader.seek(currentPosition);
399 }
400 }
401
402 private long currentTrailerSize() {
403 long size = -1L;
404 if (reader instanceof ProtobufLogReader) {
405 final ProtobufLogReader pblr = (ProtobufLogReader) reader;
406 size = pblr.trailerSize();
407 }
408 return size;
409 }
410
411 @InterfaceAudience.Private
412 public static class WALEntryStreamRuntimeException extends RuntimeException {
413 private static final long serialVersionUID = -6298201811259982568L;
414
415 public WALEntryStreamRuntimeException(Exception e) {
416 super(e);
417 }
418 }
419
420 }