1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.wal;
20
21 import java.io.EOFException;
22 import java.io.FileNotFoundException;
23 import java.io.IOException;
24 import java.io.InterruptedIOException;
25 import java.text.ParseException;
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.LinkedList;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.NavigableSet;
34 import java.util.Set;
35 import java.util.TreeMap;
36 import java.util.TreeSet;
37 import java.util.UUID;
38 import java.util.concurrent.Callable;
39 import java.util.concurrent.CompletionService;
40 import java.util.concurrent.ConcurrentHashMap;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.ExecutorCompletionService;
43 import java.util.concurrent.Future;
44 import java.util.concurrent.ThreadFactory;
45 import java.util.concurrent.ThreadPoolExecutor;
46 import java.util.concurrent.TimeUnit;
47 import java.util.concurrent.atomic.AtomicBoolean;
48 import java.util.concurrent.atomic.AtomicLong;
49 import java.util.concurrent.atomic.AtomicReference;
50 import java.util.regex.Matcher;
51 import java.util.regex.Pattern;
52
53 import org.apache.commons.logging.Log;
54 import org.apache.commons.logging.LogFactory;
55 import org.apache.hadoop.conf.Configuration;
56 import org.apache.hadoop.fs.FileAlreadyExistsException;
57 import org.apache.hadoop.fs.FileStatus;
58 import org.apache.hadoop.fs.FileSystem;
59 import org.apache.hadoop.fs.Path;
60 import org.apache.hadoop.fs.PathFilter;
61 import org.apache.hadoop.hbase.Cell;
62 import org.apache.hadoop.hbase.CellScanner;
63 import org.apache.hadoop.hbase.CellUtil;
64 import org.apache.hadoop.hbase.CoordinatedStateException;
65 import org.apache.hadoop.hbase.CoordinatedStateManager;
66 import org.apache.hadoop.hbase.HBaseConfiguration;
67 import org.apache.hadoop.hbase.HConstants;
68 import org.apache.hadoop.hbase.HRegionInfo;
69 import org.apache.hadoop.hbase.HRegionLocation;
70 import org.apache.hadoop.hbase.RemoteExceptionHandler;
71 import org.apache.hadoop.hbase.ServerName;
72 import org.apache.hadoop.hbase.TableName;
73 import org.apache.hadoop.hbase.TableNotFoundException;
74 import org.apache.hadoop.hbase.TableStateManager;
75 import org.apache.hadoop.hbase.classification.InterfaceAudience;
76 import org.apache.hadoop.hbase.client.ConnectionUtils;
77 import org.apache.hadoop.hbase.client.Delete;
78 import org.apache.hadoop.hbase.client.Durability;
79 import org.apache.hadoop.hbase.client.HConnection;
80 import org.apache.hadoop.hbase.client.HConnectionManager;
81 import org.apache.hadoop.hbase.client.Mutation;
82 import org.apache.hadoop.hbase.client.Put;
83 import org.apache.hadoop.hbase.coordination.BaseCoordinatedStateManager;
84 import org.apache.hadoop.hbase.coordination.ZKSplitLogManagerCoordination;
85 import org.apache.hadoop.hbase.exceptions.RegionOpeningException;
86 import org.apache.hadoop.hbase.io.HeapSize;
87 import org.apache.hadoop.hbase.master.SplitLogManager;
88 import org.apache.hadoop.hbase.monitoring.MonitoredTask;
89 import org.apache.hadoop.hbase.monitoring.TaskMonitor;
90 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
91 import org.apache.hadoop.hbase.protobuf.RequestConverter;
92 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService.BlockingInterface;
93 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
94 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse;
95 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.WALEntry;
96 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType;
97 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionStoreSequenceIds;
98 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.StoreSequenceId;
99 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
100 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
101 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
102 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
103 import org.apache.hadoop.hbase.regionserver.HRegion;
104 import org.apache.hadoop.hbase.regionserver.LastSequenceId;
105
106 import org.apache.hadoop.hbase.regionserver.wal.FSHLog;
107 import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
108 import org.apache.hadoop.hbase.regionserver.wal.WALCellCodec;
109 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
110 import org.apache.hadoop.hbase.regionserver.wal.WALEditsReplaySink;
111 import org.apache.hadoop.hbase.util.Bytes;
112 import org.apache.hadoop.hbase.util.CancelableProgressable;
113 import org.apache.hadoop.hbase.util.ClassSize;
114 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
115 import org.apache.hadoop.hbase.util.FSUtils;
116 import org.apache.hadoop.hbase.util.Pair;
117 import org.apache.hadoop.hbase.util.Threads;
118 import org.apache.hadoop.hbase.wal.WAL.Entry;
119 import org.apache.hadoop.hbase.wal.WAL.Reader;
120 import org.apache.hadoop.hbase.wal.WALProvider.Writer;
121 import org.apache.hadoop.hbase.zookeeper.ZKSplitLog;
122 import org.apache.hadoop.io.MultipleIOException;
123
124 import com.google.common.annotations.VisibleForTesting;
125 import com.google.common.base.Preconditions;
126 import com.google.common.collect.Lists;
127 import com.google.protobuf.ServiceException;
128 import com.google.protobuf.TextFormat;
129
130
131
132
133
134
135 @InterfaceAudience.Private
136 public class WALSplitter {
137 private static final Log LOG = LogFactory.getLog(WALSplitter.class);
138
139
140 public static final boolean SPLIT_SKIP_ERRORS_DEFAULT = false;
141
142
143 protected final Path walDir;
144 protected final FileSystem walFS;
145 protected final Configuration conf;
146
147
148
149 PipelineController controller;
150 OutputSink outputSink;
151 EntryBuffers entryBuffers;
152
153 private Set<TableName> disablingOrDisabledTables =
154 new HashSet<TableName>();
155 private BaseCoordinatedStateManager csm;
156 private final WALFactory walFactory;
157
158 private MonitoredTask status;
159
160
161 protected final LastSequenceId sequenceIdChecker;
162
163 protected boolean distributedLogReplay;
164
165 private final boolean splitWriterCreationBounded;
166
167
168
169 protected Map<String, Long> lastFlushedSequenceIds = new ConcurrentHashMap<String, Long>();
170
171
172 protected Map<String, Map<byte[], Long>> regionMaxSeqIdInStores =
173 new ConcurrentHashMap<String, Map<byte[], Long>>();
174
175
176 protected String failedServerName = "";
177
178
179 private final int numWriterThreads;
180
181
182 private final int minBatchSize;
183
184
185 private FileStatus fileBeingSplit;
186
187 public final static String SPLIT_WRITER_CREATION_BOUNDED = "hbase.split.writer.creation.bounded";
188
189 @VisibleForTesting
190 WALSplitter(final WALFactory factory, Configuration conf, Path walDir,
191 FileSystem walFS, LastSequenceId idChecker,
192 CoordinatedStateManager csm, RecoveryMode mode) {
193 this.conf = HBaseConfiguration.create(conf);
194 String codecClassName = conf
195 .get(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, WALCellCodec.class.getName());
196 this.conf.set(HConstants.RPC_CODEC_CONF_KEY, codecClassName);
197 this.walDir = walDir;
198 this.walFS = walFS;
199 this.sequenceIdChecker = idChecker;
200 this.csm = (BaseCoordinatedStateManager)csm;
201 this.walFactory = factory;
202 this.controller = new PipelineController();
203 this.splitWriterCreationBounded = conf.getBoolean(SPLIT_WRITER_CREATION_BOUNDED, false);
204 entryBuffers = new EntryBuffers(controller,
205 this.conf.getInt("hbase.regionserver.hlog.splitlog.buffersize",
206 128*1024*1024), splitWriterCreationBounded);
207
208
209
210 this.minBatchSize = this.conf.getInt("hbase.regionserver.wal.logreplay.batch.size", 64);
211 this.distributedLogReplay = (RecoveryMode.LOG_REPLAY == mode);
212
213 this.numWriterThreads = this.conf.getInt("hbase.regionserver.hlog.splitlog.writer.threads", 3);
214 if (csm != null && this.distributedLogReplay) {
215 outputSink = new LogReplayOutputSink(controller, entryBuffers, numWriterThreads);
216 } else {
217 if (this.distributedLogReplay) {
218 LOG.info("ZooKeeperWatcher is passed in as NULL so disable distrubitedLogRepaly.");
219 }
220 this.distributedLogReplay = false;
221 if(splitWriterCreationBounded){
222 outputSink = new BoundedLogWriterCreationOutputSink(controller,
223 entryBuffers, numWriterThreads);
224 }else {
225 outputSink = new LogRecoveredEditsOutputSink(controller, entryBuffers, numWriterThreads);
226 }
227 }
228
229 }
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247 public static boolean splitLogFile(Path walDir, FileStatus logfile, FileSystem walFS,
248 Configuration conf, CancelableProgressable reporter, LastSequenceId idChecker,
249 CoordinatedStateManager cp, RecoveryMode mode, final WALFactory factory) throws IOException {
250 WALSplitter s = new WALSplitter(factory, conf, walDir, walFS, idChecker, cp, mode);
251 return s.splitLogFile(logfile, reporter);
252 }
253
254
255
256
257
258 public static List<Path> split(Path walRootDir, Path logDir, Path oldLogDir,
259 FileSystem walFs, Configuration conf, final WALFactory factory) throws IOException {
260 final FileStatus[] logfiles = SplitLogManager.getFileList(conf,
261 Collections.singletonList(logDir), null);
262 List<Path> splits = new ArrayList<Path>();
263 if (logfiles != null && logfiles.length > 0) {
264 for (FileStatus logfile: logfiles) {
265 WALSplitter s = new WALSplitter(factory, conf, walRootDir, walFs, null, null,
266 RecoveryMode.LOG_SPLITTING);
267 if (s.splitLogFile(logfile, null)) {
268 finishSplitLogFile(walRootDir, oldLogDir, logfile.getPath(), conf);
269 if (s.outputSink.splits != null) {
270 splits.addAll(s.outputSink.splits);
271 }
272 }
273 }
274 }
275 if (!walFs.delete(logDir, true)) {
276 throw new IOException("Unable to delete src dir: " + logDir);
277 }
278 return splits;
279 }
280
281
282
283
284
285 @VisibleForTesting
286 boolean splitLogFile(FileStatus logfile, CancelableProgressable reporter) throws IOException {
287 Preconditions.checkState(status == null);
288 Preconditions.checkArgument(logfile.isFile(),
289 "passed in file status is for something other than a regular file.");
290 boolean isCorrupted = false;
291 boolean skipErrors = conf.getBoolean("hbase.hlog.split.skip.errors",
292 SPLIT_SKIP_ERRORS_DEFAULT);
293 int interval = conf.getInt("hbase.splitlog.report.interval.loglines", 1024);
294 Path logPath = logfile.getPath();
295 boolean outputSinkStarted = false;
296 boolean progress_failed = false;
297 int editsCount = 0;
298 int editsSkipped = 0;
299
300 status =
301 TaskMonitor.get().createStatus(
302 "Splitting log file " + logfile.getPath() + "into a temporary staging area.");
303 Reader in = null;
304 this.fileBeingSplit = logfile;
305 try {
306 long logLength = logfile.getLen();
307 LOG.info("Splitting wal: " + logPath + ", length=" + logLength);
308 LOG.info("DistributedLogReplay = " + this.distributedLogReplay);
309 status.setStatus("Opening log file");
310 if (reporter != null && !reporter.progress()) {
311 progress_failed = true;
312 return false;
313 }
314 try {
315 in = getReader(logfile, skipErrors, reporter);
316 } catch (CorruptedLogFileException e) {
317 LOG.warn("Could not get reader, corrupted log file " + logPath, e);
318 ZKSplitLog.markCorrupted(walDir, logfile.getPath().getName(), walFS);
319 isCorrupted = true;
320 }
321 if (in == null) {
322 LOG.warn("Nothing to split in log file " + logPath);
323 return true;
324 }
325 if (csm != null) {
326 try {
327 TableStateManager tsm = csm.getTableStateManager();
328 disablingOrDisabledTables = tsm.getTablesInStates(
329 ZooKeeperProtos.Table.State.DISABLED, ZooKeeperProtos.Table.State.DISABLING);
330 } catch (CoordinatedStateException e) {
331 throw new IOException("Can't get disabling/disabled tables", e);
332 }
333 }
334 int numOpenedFilesBeforeReporting = conf.getInt("hbase.splitlog.report.openedfiles", 3);
335 int numOpenedFilesLastCheck = 0;
336 outputSink.setReporter(reporter);
337 outputSink.startWriterThreads();
338 outputSinkStarted = true;
339 Entry entry;
340 Long lastFlushedSequenceId = -1L;
341 ServerName serverName = DefaultWALProvider.getServerNameFromWALDirectoryName(logPath);
342 failedServerName = (serverName == null) ? "" : serverName.getServerName();
343 while ((entry = getNextLogLine(in, logPath, skipErrors)) != null) {
344 byte[] region = entry.getKey().getEncodedRegionName();
345 String encodedRegionNameAsStr = Bytes.toString(region);
346 lastFlushedSequenceId = lastFlushedSequenceIds.get(encodedRegionNameAsStr);
347 if (lastFlushedSequenceId == null) {
348 if (this.distributedLogReplay) {
349 RegionStoreSequenceIds ids =
350 csm.getSplitLogWorkerCoordination().getRegionFlushedSequenceId(failedServerName,
351 encodedRegionNameAsStr);
352 if (ids != null) {
353 lastFlushedSequenceId = ids.getLastFlushedSequenceId();
354 if (LOG.isDebugEnabled()) {
355 LOG.debug("DLR Last flushed sequenceid for " + encodedRegionNameAsStr + ": " +
356 TextFormat.shortDebugString(ids));
357 }
358 }
359 } else if (sequenceIdChecker != null) {
360 RegionStoreSequenceIds ids = sequenceIdChecker.getLastSequenceId(region);
361 Map<byte[], Long> maxSeqIdInStores = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
362 for (StoreSequenceId storeSeqId : ids.getStoreSequenceIdList()) {
363 maxSeqIdInStores.put(storeSeqId.getFamilyName().toByteArray(),
364 storeSeqId.getSequenceId());
365 }
366 regionMaxSeqIdInStores.put(encodedRegionNameAsStr, maxSeqIdInStores);
367 lastFlushedSequenceId = ids.getLastFlushedSequenceId();
368 if (LOG.isDebugEnabled()) {
369 LOG.debug("DLS Last flushed sequenceid for " + encodedRegionNameAsStr + ": " +
370 TextFormat.shortDebugString(ids));
371 }
372 }
373 if (lastFlushedSequenceId == null) {
374 lastFlushedSequenceId = -1L;
375 }
376 lastFlushedSequenceIds.put(encodedRegionNameAsStr, lastFlushedSequenceId);
377 }
378 if (lastFlushedSequenceId >= entry.getKey().getLogSeqNum()) {
379 editsSkipped++;
380 continue;
381 }
382
383 if (entry.getEdit().isMetaEdit() && !outputSink.keepRegionEvent(entry)) {
384 editsSkipped++;
385 continue;
386 }
387 entryBuffers.appendEntry(entry);
388 editsCount++;
389 int moreWritersFromLastCheck = this.getNumOpenWriters() - numOpenedFilesLastCheck;
390
391 if (editsCount % interval == 0
392 || moreWritersFromLastCheck > numOpenedFilesBeforeReporting) {
393 numOpenedFilesLastCheck = this.getNumOpenWriters();
394 String countsStr = (editsCount - (editsSkipped + outputSink.getSkippedEdits()))
395 + " edits, skipped " + editsSkipped + " edits.";
396 status.setStatus("Split " + countsStr);
397 if (reporter != null && !reporter.progress()) {
398 progress_failed = true;
399 return false;
400 }
401 }
402 }
403 } catch (InterruptedException ie) {
404 IOException iie = new InterruptedIOException();
405 iie.initCause(ie);
406 throw iie;
407 } catch (CorruptedLogFileException e) {
408 LOG.warn("Could not parse, corrupted log file " + logPath, e);
409 csm.getSplitLogWorkerCoordination().markCorrupted(walDir,
410 logfile.getPath().getName(), walFS);
411 isCorrupted = true;
412 } catch (IOException e) {
413 e = RemoteExceptionHandler.checkIOException(e);
414 throw e;
415 } finally {
416 LOG.debug("Finishing writing output logs and closing down.");
417 try {
418 if (null != in) {
419 in.close();
420 }
421 } catch (IOException exception) {
422 LOG.warn("Could not close wal reader: " + exception.getMessage());
423 LOG.debug("exception details", exception);
424 }
425 try {
426 if (outputSinkStarted) {
427
428
429 progress_failed = true;
430 progress_failed = outputSink.finishWritingAndClose() == null;
431 }
432 } finally {
433 String msg =
434 "Processed " + editsCount + " edits across " + outputSink.getNumberOfRecoveredRegions()
435 + " regions; edits skipped=" + editsSkipped + "; log file=" + logPath +
436 ", length=" + logfile.getLen() +
437 ", corrupted=" + isCorrupted + ", progress failed=" + progress_failed;
438 LOG.info(msg);
439 status.markComplete(msg);
440 }
441 }
442 return !progress_failed;
443 }
444
445
446
447
448
449
450
451
452
453
454
455
456 public static void finishSplitLogFile(String logfile,
457 Configuration conf) throws IOException {
458 Path walDir = FSUtils.getWALRootDir(conf);
459 Path oldLogDir = new Path(walDir, HConstants.HREGION_OLDLOGDIR_NAME);
460 Path logPath;
461 if (FSUtils.isStartingWithPath(walDir, logfile)) {
462 logPath = new Path(logfile);
463 } else {
464 logPath = new Path(walDir, logfile);
465 }
466 finishSplitLogFile(walDir, oldLogDir, logPath, conf);
467 }
468
469 private static void finishSplitLogFile(Path walDir, Path oldLogDir,
470 Path logPath, Configuration conf) throws IOException {
471 List<Path> processedLogs = new ArrayList<Path>();
472 List<Path> corruptedLogs = new ArrayList<Path>();
473 FileSystem walFS = walDir.getFileSystem(conf);
474 if (ZKSplitLog.isCorrupted(walDir, logPath.getName(), walFS)) {
475 corruptedLogs.add(logPath);
476 } else {
477 processedLogs.add(logPath);
478 }
479 archiveLogs(corruptedLogs, processedLogs, oldLogDir, walFS, conf);
480 Path stagingDir = ZKSplitLog.getSplitLogDir(walDir, logPath.getName());
481 walFS.delete(stagingDir, true);
482 }
483
484
485
486
487
488
489
490
491
492
493
494
495
496 private static void archiveLogs(
497 final List<Path> corruptedLogs,
498 final List<Path> processedLogs, final Path oldLogDir,
499 final FileSystem walFS, final Configuration conf) throws IOException {
500 final Path corruptDir = new Path(FSUtils.getWALRootDir(conf), conf.get(
501 "hbase.regionserver.hlog.splitlog.corrupt.dir", HConstants.CORRUPT_DIR_NAME));
502
503 if (!walFS.mkdirs(corruptDir)) {
504 LOG.info("Unable to mkdir " + corruptDir);
505 }
506 walFS.mkdirs(oldLogDir);
507
508
509
510 for (Path corrupted : corruptedLogs) {
511 Path p = new Path(corruptDir, corrupted.getName());
512 if (walFS.exists(corrupted)) {
513 if (!walFS.rename(corrupted, p)) {
514 LOG.warn("Unable to move corrupted log " + corrupted + " to " + p);
515 } else {
516 LOG.warn("Moved corrupted log " + corrupted + " to " + p);
517 }
518 }
519 }
520
521 for (Path p : processedLogs) {
522 Path newPath = FSHLog.getWALArchivePath(oldLogDir, p);
523 if (walFS.exists(p)) {
524 if (!FSUtils.renameAndSetModifyTime(walFS, p, newPath)) {
525 LOG.warn("Unable to move " + p + " to " + newPath);
526 } else {
527 LOG.info("Archived processed log " + p + " to " + newPath);
528 }
529 }
530 }
531 }
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546 @SuppressWarnings("deprecation")
547 @VisibleForTesting
548 static Path getRegionSplitEditsPath(final Entry logEntry, String fileNameBeingSplit,
549 String tmpDirName, Configuration conf) throws IOException {
550 FileSystem walFS = FSUtils.getWALFileSystem(conf);
551 TableName tableName = logEntry.getKey().getTablename();
552 String encodedRegionName = Bytes.toString(logEntry.getKey().getEncodedRegionName());
553 Path regionDir = FSUtils.getWALRegionDir(conf, tableName, encodedRegionName);
554 Path dir = getRegionDirRecoveredEditsDir(regionDir);
555
556 if (walFS.exists(dir) && walFS.isFile(dir)) {
557 Path tmp = new Path(tmpDirName);
558 if (!walFS.exists(tmp)) {
559 walFS.mkdirs(tmp);
560 }
561 tmp = new Path(tmp, HConstants.RECOVERED_EDITS_DIR + "_" + encodedRegionName);
562 LOG.warn("Found existing old file: " + dir + ". It could be some "
563 + "leftover of an old installation. It should be a folder instead. "
564 + "So moving it to " + tmp);
565 if (!walFS.rename(dir, tmp)) {
566 LOG.warn("Failed to sideline old file " + dir);
567 }
568 }
569
570 if (!walFS.exists(dir) && !walFS.mkdirs(dir)) {
571 LOG.warn("mkdir failed on " + dir);
572 }
573
574
575
576 String fileName = formatRecoveredEditsFileName(logEntry.getKey().getLogSeqNum());
577 fileName = getTmpRecoveredEditsFileName(fileName + "-" + fileNameBeingSplit);
578 return new Path(dir, fileName);
579 }
580
581 private static String getTmpRecoveredEditsFileName(String fileName) {
582 return fileName + RECOVERED_LOG_TMPFILE_SUFFIX;
583 }
584
585
586
587
588
589
590
591
592
593 private static Path getCompletedRecoveredEditsFilePath(Path srcPath,
594 long maximumEditLogSeqNum) {
595 String fileName = formatRecoveredEditsFileName(maximumEditLogSeqNum);
596 return new Path(srcPath.getParent(), fileName);
597 }
598
599 @VisibleForTesting
600 static String formatRecoveredEditsFileName(final long seqid) {
601 return String.format("%019d", seqid);
602 }
603
604 private static final Pattern EDITFILES_NAME_PATTERN = Pattern.compile("-?[0-9]+");
605 private static final String RECOVERED_LOG_TMPFILE_SUFFIX = ".temp";
606
607
608
609
610
611
612
613 public static Path getRegionDirRecoveredEditsDir(final Path regionDir) {
614 return new Path(regionDir, HConstants.RECOVERED_EDITS_DIR);
615 }
616
617
618
619
620
621
622
623
624
625
626 public static NavigableSet<Path> getSplitEditFilesSorted(final FileSystem walFS,
627 final Path regionDir) throws IOException {
628 NavigableSet<Path> filesSorted = new TreeSet<Path>();
629 Path editsdir = getRegionDirRecoveredEditsDir(regionDir);
630 if (!walFS.exists(editsdir)) {
631 return filesSorted;
632 }
633 FileStatus[] files = FSUtils.listStatus(walFS, editsdir, new PathFilter() {
634 @Override
635 public boolean accept(Path p) {
636 boolean result = false;
637 try {
638
639
640
641
642 Matcher m = EDITFILES_NAME_PATTERN.matcher(p.getName());
643 result = walFS.isFile(p) && m.matches();
644
645
646 if (p.getName().endsWith(RECOVERED_LOG_TMPFILE_SUFFIX)) {
647 result = false;
648 }
649
650 if (isSequenceIdFile(p)) {
651 result = false;
652 }
653 } catch (IOException e) {
654 LOG.warn("Failed isFile check on " + p);
655 }
656 return result;
657 }
658 });
659 if (files == null) {
660 return filesSorted;
661 }
662 for (FileStatus status : files) {
663 filesSorted.add(status.getPath());
664 }
665 return filesSorted;
666 }
667
668
669
670
671
672
673
674
675
676
677 public static Path moveAsideBadEditsFile(final FileSystem walFS, final Path edits)
678 throws IOException {
679 Path moveAsideName = new Path(edits.getParent(), edits.getName() + "."
680 + System.currentTimeMillis());
681 if (!walFS.rename(edits, moveAsideName)) {
682 LOG.warn("Rename failed from " + edits + " to " + moveAsideName);
683 }
684 return moveAsideName;
685 }
686
687 private static final String SEQUENCE_ID_FILE_SUFFIX = ".seqid";
688 private static final String OLD_SEQUENCE_ID_FILE_SUFFIX = "_seqid";
689 private static final int SEQUENCE_ID_FILE_SUFFIX_LENGTH = SEQUENCE_ID_FILE_SUFFIX.length();
690
691
692
693
694 @VisibleForTesting
695 public static boolean isSequenceIdFile(final Path file) {
696 return file.getName().endsWith(SEQUENCE_ID_FILE_SUFFIX)
697 || file.getName().endsWith(OLD_SEQUENCE_ID_FILE_SUFFIX);
698 }
699
700
701
702
703
704
705
706
707
708
709 public static long writeRegionSequenceIdFile(final FileSystem walFS, final Path regionDir,
710 long newSeqId, long saftyBumper) throws IOException {
711
712 Path editsdir = WALSplitter.getRegionDirRecoveredEditsDir(regionDir);
713 long maxSeqId = 0;
714 FileStatus[] files = null;
715 if (walFS.exists(editsdir)) {
716 files = FSUtils.listStatus(walFS, editsdir, new PathFilter() {
717 @Override
718 public boolean accept(Path p) {
719 return isSequenceIdFile(p);
720 }
721 });
722 if (files != null) {
723 for (FileStatus status : files) {
724 String fileName = status.getPath().getName();
725 try {
726 Long tmpSeqId = Long.parseLong(fileName.substring(0, fileName.length()
727 - SEQUENCE_ID_FILE_SUFFIX_LENGTH));
728 maxSeqId = Math.max(tmpSeqId, maxSeqId);
729 } catch (NumberFormatException ex) {
730 LOG.warn("Invalid SeqId File Name=" + fileName);
731 }
732 }
733 }
734 }
735 if (maxSeqId > newSeqId) {
736 newSeqId = maxSeqId;
737 }
738 newSeqId += saftyBumper;
739
740
741 Path newSeqIdFile = new Path(editsdir, newSeqId + SEQUENCE_ID_FILE_SUFFIX);
742 if (newSeqId != maxSeqId) {
743 try {
744 if (!walFS.createNewFile(newSeqIdFile) && !walFS.exists(newSeqIdFile)) {
745 throw new IOException("Failed to create SeqId file:" + newSeqIdFile);
746 }
747 if (LOG.isDebugEnabled()) {
748 LOG.debug("Wrote region seqId=" + newSeqIdFile + " to file, newSeqId=" + newSeqId
749 + ", maxSeqId=" + maxSeqId);
750 }
751 } catch (FileAlreadyExistsException ignored) {
752
753 }
754 }
755
756 if (files != null) {
757 for (FileStatus status : files) {
758 if (newSeqIdFile.equals(status.getPath())) {
759 continue;
760 }
761 walFS.delete(status.getPath(), false);
762 }
763 }
764 return newSeqId;
765 }
766
767
768
769
770
771
772
773
774
775 protected Reader getReader(FileStatus file, boolean skipErrors, CancelableProgressable reporter)
776 throws IOException, CorruptedLogFileException {
777 Path path = file.getPath();
778 long length = file.getLen();
779 Reader in;
780
781
782
783
784 if (length <= 0) {
785 LOG.warn("File " + path + " might be still open, length is 0");
786 }
787
788 try {
789 FSUtils.getInstance(walFS, conf).recoverFileLease(walFS, path, conf, reporter);
790 try {
791 in = getReader(path, reporter);
792 } catch (EOFException e) {
793 if (length <= 0) {
794
795
796
797
798
799 LOG.warn("Could not open " + path + " for reading. File is empty", e);
800 return null;
801 } else {
802
803 return null;
804 }
805 }
806 } catch (IOException e) {
807 if (e instanceof FileNotFoundException) {
808
809 LOG.warn("File " + path + " doesn't exist anymore.", e);
810 return null;
811 }
812 if (!skipErrors || e instanceof InterruptedIOException) {
813 throw e;
814 }
815 CorruptedLogFileException t =
816 new CorruptedLogFileException("skipErrors=true Could not open wal " +
817 path + " ignoring");
818 t.initCause(e);
819 throw t;
820 }
821 return in;
822 }
823
824 static private Entry getNextLogLine(Reader in, Path path, boolean skipErrors)
825 throws CorruptedLogFileException, IOException {
826 try {
827 return in.next();
828 } catch (EOFException eof) {
829
830 LOG.info("EOF from wal " + path + ". continuing");
831 return null;
832 } catch (IOException e) {
833
834
835 if (e.getCause() != null &&
836 (e.getCause() instanceof ParseException ||
837 e.getCause() instanceof org.apache.hadoop.fs.ChecksumException)) {
838 LOG.warn("Parse exception " + e.getCause().toString() + " from wal "
839 + path + ". continuing");
840 return null;
841 }
842 if (!skipErrors) {
843 throw e;
844 }
845 CorruptedLogFileException t =
846 new CorruptedLogFileException("skipErrors=true Ignoring exception" +
847 " while parsing wal " + path + ". Marking as corrupted");
848 t.initCause(e);
849 throw t;
850 }
851 }
852
853
854
855
856
857 protected Writer createWriter(Path logfile)
858 throws IOException {
859 return walFactory.createRecoveredEditsWriter(walFS, logfile);
860 }
861
862
863
864
865
866 protected Reader getReader(Path curLogFile, CancelableProgressable reporter) throws IOException {
867 return walFactory.createReader(walFS, curLogFile, reporter);
868 }
869
870
871
872
873 private int getNumOpenWriters() {
874 int result = 0;
875 if (this.outputSink != null) {
876 result += this.outputSink.getNumOpenWriters();
877 }
878 return result;
879 }
880
881
882
883
884 public static class PipelineController {
885
886
887 AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
888
889
890
891 public final Object dataAvailable = new Object();
892
893 void writerThreadError(Throwable t) {
894 thrown.compareAndSet(null, t);
895 }
896
897
898
899
900 void checkForErrors() throws IOException {
901 Throwable thrown = this.thrown.get();
902 if (thrown == null) return;
903 if (thrown instanceof IOException) {
904 throw new IOException(thrown);
905 } else {
906 throw new RuntimeException(thrown);
907 }
908 }
909 }
910
911
912
913
914
915
916
917
918 public static class EntryBuffers {
919 PipelineController controller;
920
921 Map<byte[], RegionEntryBuffer> buffers =
922 new TreeMap<byte[], RegionEntryBuffer>(Bytes.BYTES_COMPARATOR);
923
924
925
926
927 Set<byte[]> currentlyWriting = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);
928
929 long totalBuffered = 0;
930 final long maxHeapUsage;
931 boolean splitWriterCreationBounded;
932
933
934 public EntryBuffers(PipelineController controller, long maxHeapUsage) {
935 this(controller, maxHeapUsage, false);
936 }
937
938 public EntryBuffers(PipelineController controller, long maxHeapUsage,
939 boolean splitWriterCreationBounded) {
940 this.controller = controller;
941 this.maxHeapUsage = maxHeapUsage;
942 this.splitWriterCreationBounded = splitWriterCreationBounded;
943 }
944
945
946
947
948
949
950
951
952 public void appendEntry(Entry entry) throws InterruptedException, IOException {
953 WALKey key = entry.getKey();
954
955 RegionEntryBuffer buffer;
956 long incrHeap;
957 synchronized (this) {
958 buffer = buffers.get(key.getEncodedRegionName());
959 if (buffer == null) {
960 buffer = new RegionEntryBuffer(key.getTablename(), key.getEncodedRegionName());
961 buffers.put(key.getEncodedRegionName(), buffer);
962 }
963 incrHeap= buffer.appendEntry(entry);
964 }
965
966
967 synchronized (controller.dataAvailable) {
968 totalBuffered += incrHeap;
969 while (totalBuffered > maxHeapUsage && controller.thrown.get() == null) {
970 LOG.debug("Used " + totalBuffered + " bytes of buffered edits, waiting for IO threads...");
971 controller.dataAvailable.wait(2000);
972 }
973 controller.dataAvailable.notifyAll();
974 }
975 controller.checkForErrors();
976 }
977
978
979
980
981 synchronized RegionEntryBuffer getChunkToWrite() {
982
983
984
985
986 if(splitWriterCreationBounded && totalBuffered < maxHeapUsage){
987 return null;
988 }
989
990 long biggestSize = 0;
991 byte[] biggestBufferKey = null;
992
993 for (Map.Entry<byte[], RegionEntryBuffer> entry : buffers.entrySet()) {
994 long size = entry.getValue().heapSize();
995 if (size > biggestSize && (!currentlyWriting.contains(entry.getKey()))) {
996 biggestSize = size;
997 biggestBufferKey = entry.getKey();
998 }
999 }
1000 if (biggestBufferKey == null) {
1001 return null;
1002 }
1003
1004 RegionEntryBuffer buffer = buffers.remove(biggestBufferKey);
1005 currentlyWriting.add(biggestBufferKey);
1006 return buffer;
1007 }
1008
1009 void doneWriting(RegionEntryBuffer buffer) {
1010 synchronized (this) {
1011 boolean removed = currentlyWriting.remove(buffer.encodedRegionName);
1012 assert removed;
1013 }
1014 long size = buffer.heapSize();
1015
1016 synchronized (controller.dataAvailable) {
1017 totalBuffered -= size;
1018
1019 controller.dataAvailable.notifyAll();
1020 }
1021 }
1022
1023 synchronized boolean isRegionCurrentlyWriting(byte[] region) {
1024 return currentlyWriting.contains(region);
1025 }
1026
1027 public void waitUntilDrained() {
1028 synchronized (controller.dataAvailable) {
1029 while (totalBuffered > 0) {
1030 try {
1031 controller.dataAvailable.wait(2000);
1032 } catch (InterruptedException e) {
1033 LOG.warn("Got interrupted while waiting for EntryBuffers is drained");
1034 Thread.interrupted();
1035 break;
1036 }
1037 }
1038 }
1039 }
1040 }
1041
1042
1043
1044
1045
1046
1047
1048 public static class RegionEntryBuffer implements HeapSize {
1049 long heapInBuffer = 0;
1050 List<Entry> entryBuffer;
1051 TableName tableName;
1052 byte[] encodedRegionName;
1053
1054 RegionEntryBuffer(TableName tableName, byte[] region) {
1055 this.tableName = tableName;
1056 this.encodedRegionName = region;
1057 this.entryBuffer = new LinkedList<Entry>();
1058 }
1059
1060 long appendEntry(Entry entry) {
1061 internify(entry);
1062 entryBuffer.add(entry);
1063 long incrHeap = entry.getEdit().heapSize() +
1064 ClassSize.align(2 * ClassSize.REFERENCE) +
1065 0;
1066 heapInBuffer += incrHeap;
1067 return incrHeap;
1068 }
1069
1070 private void internify(Entry entry) {
1071 WALKey k = entry.getKey();
1072 k.internTableName(this.tableName);
1073 k.internEncodedRegionName(this.encodedRegionName);
1074 }
1075
1076 @Override
1077 public long heapSize() {
1078 return heapInBuffer;
1079 }
1080
1081 public byte[] getEncodedRegionName() {
1082 return encodedRegionName;
1083 }
1084
1085 public List<Entry> getEntryBuffer() {
1086 return entryBuffer;
1087 }
1088
1089 public TableName getTableName() {
1090 return tableName;
1091 }
1092 }
1093
1094 public static class WriterThread extends Thread {
1095 private volatile boolean shouldStop = false;
1096 private PipelineController controller;
1097 private EntryBuffers entryBuffers;
1098 private OutputSink outputSink = null;
1099
1100 WriterThread(PipelineController controller, EntryBuffers entryBuffers, OutputSink sink, int i){
1101 super(Thread.currentThread().getName() + "-Writer-" + i);
1102 this.controller = controller;
1103 this.entryBuffers = entryBuffers;
1104 outputSink = sink;
1105 }
1106
1107 @Override
1108 public void run() {
1109 try {
1110 doRun();
1111 } catch (Throwable t) {
1112 LOG.error("Exiting thread", t);
1113 controller.writerThreadError(t);
1114 }
1115 }
1116
1117 private void doRun() throws IOException {
1118 if (LOG.isTraceEnabled()) LOG.trace("Writer thread starting");
1119 while (true) {
1120 RegionEntryBuffer buffer = entryBuffers.getChunkToWrite();
1121 if (buffer == null) {
1122
1123 synchronized (controller.dataAvailable) {
1124 if (shouldStop && !this.outputSink.flush()) {
1125 return;
1126 }
1127 try {
1128 controller.dataAvailable.wait(500);
1129 } catch (InterruptedException ie) {
1130 if (!shouldStop) {
1131 throw new RuntimeException(ie);
1132 }
1133 }
1134 }
1135 continue;
1136 }
1137
1138 assert buffer != null;
1139 try {
1140 writeBuffer(buffer);
1141 } finally {
1142 entryBuffers.doneWriting(buffer);
1143 }
1144 }
1145 }
1146
1147 private void writeBuffer(RegionEntryBuffer buffer) throws IOException {
1148 outputSink.append(buffer);
1149 }
1150
1151 void finish() {
1152 synchronized (controller.dataAvailable) {
1153 shouldStop = true;
1154 controller.dataAvailable.notifyAll();
1155 }
1156 }
1157 }
1158
1159
1160
1161
1162
1163 public static abstract class OutputSink {
1164
1165 protected PipelineController controller;
1166 protected EntryBuffers entryBuffers;
1167
1168 protected ConcurrentHashMap<String, SinkWriter> writers = new ConcurrentHashMap<>();
1169 protected ConcurrentHashMap<String, Long> regionMaximumEditLogSeqNum =
1170 new ConcurrentHashMap<>();
1171
1172 protected final List<WriterThread> writerThreads = Lists.newArrayList();
1173
1174
1175 protected final Set<byte[]> blacklistedRegions = Collections
1176 .synchronizedSet(new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR));
1177
1178 protected boolean closeAndCleanCompleted = false;
1179
1180 protected boolean writersClosed = false;
1181
1182 protected final int numThreads;
1183
1184 protected CancelableProgressable reporter = null;
1185
1186 protected AtomicLong skippedEdits = new AtomicLong();
1187
1188 protected List<Path> splits = null;
1189
1190 public OutputSink(PipelineController controller, EntryBuffers entryBuffers, int numWriters) {
1191 numThreads = numWriters;
1192 this.controller = controller;
1193 this.entryBuffers = entryBuffers;
1194 }
1195
1196 void setReporter(CancelableProgressable reporter) {
1197 this.reporter = reporter;
1198 }
1199
1200
1201
1202
1203 public synchronized void startWriterThreads() {
1204 for (int i = 0; i < numThreads; i++) {
1205 WriterThread t = new WriterThread(controller, entryBuffers, this, i);
1206 t.start();
1207 writerThreads.add(t);
1208 }
1209 }
1210
1211
1212
1213
1214
1215 void updateRegionMaximumEditLogSeqNum(Entry entry) {
1216
1217 synchronized (regionMaximumEditLogSeqNum) {
1218 String encodedRegionName = Bytes.toString(entry.getKey().getEncodedRegionName());
1219 Long currentMaxSeqNum = regionMaximumEditLogSeqNum.get(encodedRegionName);
1220 if (currentMaxSeqNum == null || entry.getKey().getLogSeqNum() > currentMaxSeqNum) {
1221 regionMaximumEditLogSeqNum.put(encodedRegionName, entry.getKey()
1222 .getLogSeqNum());
1223 }
1224 }
1225 }
1226
1227 Long getRegionMaximumEditLogSeqNum(byte[] region) {
1228 return regionMaximumEditLogSeqNum.get(Bytes.toString(region));
1229 }
1230
1231
1232
1233
1234 int getNumOpenWriters() {
1235 return this.writers.size();
1236 }
1237
1238 long getSkippedEdits() {
1239 return this.skippedEdits.get();
1240 }
1241
1242
1243
1244
1245
1246
1247 protected boolean finishWriting(boolean interrupt) throws IOException {
1248 LOG.debug("Waiting for split writer threads to finish");
1249 boolean progress_failed = false;
1250 for (WriterThread t : writerThreads) {
1251 t.finish();
1252 }
1253 if (interrupt) {
1254 for (WriterThread t : writerThreads) {
1255 t.interrupt();
1256 }
1257 }
1258
1259 for (WriterThread t : writerThreads) {
1260 if (!progress_failed && reporter != null && !reporter.progress()) {
1261 progress_failed = true;
1262 }
1263 try {
1264 t.join();
1265 } catch (InterruptedException ie) {
1266 IOException iie = new InterruptedIOException();
1267 iie.initCause(ie);
1268 throw iie;
1269 }
1270 }
1271 controller.checkForErrors();
1272 LOG.info(this.writerThreads.size() + " split writers finished; closing...");
1273 return (!progress_failed);
1274 }
1275
1276 public abstract List<Path> finishWritingAndClose() throws IOException;
1277
1278
1279
1280
1281 public abstract Map<byte[], Long> getOutputCounts();
1282
1283
1284
1285
1286 public abstract int getNumberOfRecoveredRegions();
1287
1288
1289
1290
1291
1292 public abstract void append(RegionEntryBuffer buffer) throws IOException;
1293
1294
1295
1296
1297
1298 public boolean flush() throws IOException {
1299 return false;
1300 }
1301
1302
1303
1304
1305
1306
1307
1308 public abstract boolean keepRegionEvent(Entry entry);
1309 }
1310
1311
1312
1313
1314 class LogRecoveredEditsOutputSink extends OutputSink {
1315
1316 public LogRecoveredEditsOutputSink(PipelineController controller, EntryBuffers entryBuffers,
1317 int numWriters) {
1318
1319
1320
1321
1322
1323 super(controller, entryBuffers, numWriters);
1324 }
1325
1326
1327
1328
1329
1330 @Override
1331 public List<Path> finishWritingAndClose() throws IOException {
1332 boolean isSuccessful = false;
1333 List<Path> result = null;
1334 try {
1335 isSuccessful = finishWriting(false);
1336 } finally {
1337 result = close();
1338 List<IOException> thrown = closeLogWriters(null);
1339 if (thrown != null && !thrown.isEmpty()) {
1340 throw MultipleIOException.createIOException(thrown);
1341 }
1342 }
1343 if (isSuccessful) {
1344 splits = result;
1345 }
1346 return splits;
1347 }
1348
1349
1350 void deleteOneWithFewerEntries(WriterAndPath wap, Path dst)
1351 throws IOException {
1352 long dstMinLogSeqNum = -1L;
1353 try (WAL.Reader reader = walFactory.createReader(walFS, dst)) {
1354 WAL.Entry entry = reader.next();
1355 if (entry != null) {
1356 dstMinLogSeqNum = entry.getKey().getLogSeqNum();
1357 }
1358 } catch (EOFException e) {
1359 if (LOG.isDebugEnabled()) {
1360 LOG.debug(
1361 "Got EOF when reading first WAL entry from " + dst + ", an empty or broken WAL file?",
1362 e);
1363 }
1364 }
1365 if (wap.minLogSeqNum < dstMinLogSeqNum) {
1366 LOG.warn("Found existing old edits file. It could be the result of a previous failed"
1367 + " split attempt or we have duplicated wal entries. Deleting " + dst + ", length="
1368 + walFS.getFileStatus(dst).getLen());
1369 if (!walFS.delete(dst, false)) {
1370 LOG.warn("Failed deleting of old " + dst);
1371 throw new IOException("Failed deleting of old " + dst);
1372 }
1373 } else {
1374 LOG.warn("Found existing old edits file and we have less entries. Deleting " + wap.p
1375 + ", length=" + walFS.getFileStatus(wap.p).getLen());
1376 if (!walFS.delete(wap.p, false)) {
1377 LOG.warn("Failed deleting of " + wap.p);
1378 throw new IOException("Failed deleting of " + wap.p);
1379 }
1380 }
1381 }
1382
1383
1384
1385
1386
1387 List<Path> close() throws IOException {
1388 Preconditions.checkState(!closeAndCleanCompleted);
1389
1390 final List<Path> paths = new ArrayList<Path>();
1391 final List<IOException> thrown = Lists.newArrayList();
1392 ThreadPoolExecutor closeThreadPool = Threads.getBoundedCachedThreadPool(numThreads, 30L,
1393 TimeUnit.SECONDS, new ThreadFactory() {
1394 private int count = 1;
1395
1396 @Override
1397 public Thread newThread(Runnable r) {
1398 Thread t = new Thread(r, "split-log-closeStream-" + count++);
1399 return t;
1400 }
1401 });
1402 CompletionService<Void> completionService =
1403 new ExecutorCompletionService<Void>(closeThreadPool);
1404 boolean progress_failed;
1405 try{
1406 progress_failed = executeCloseTask(completionService, thrown, paths);
1407 } catch (InterruptedException e) {
1408 IOException iie = new InterruptedIOException();
1409 iie.initCause(e);
1410 throw iie;
1411 } catch (ExecutionException e) {
1412 throw new IOException(e.getCause());
1413 } finally {
1414 closeThreadPool.shutdownNow();
1415 }
1416
1417 if (!thrown.isEmpty()) {
1418 throw MultipleIOException.createIOException(thrown);
1419 }
1420 writersClosed = true;
1421 closeAndCleanCompleted = true;
1422 if (progress_failed) {
1423 return null;
1424 }
1425 return paths;
1426 }
1427
1428 boolean executeCloseTask(CompletionService<Void> completionService,
1429 final List<IOException> thrown, final List<Path> paths)
1430 throws InterruptedException, ExecutionException {
1431 for (final Map.Entry<String, SinkWriter> writersEntry : writers.entrySet()) {
1432 if (LOG.isTraceEnabled()) {
1433 LOG.trace("Submitting close of " + ((WriterAndPath) writersEntry.getValue()).p);
1434 }
1435 completionService.submit(new Callable<Void>() {
1436 @Override public Void call() throws Exception {
1437 WriterAndPath wap = (WriterAndPath) writersEntry.getValue();
1438 Path dst = closeWriter(writersEntry.getKey(), wap, thrown);
1439 paths.add(dst);
1440 return null;
1441 }
1442 });
1443 }
1444 boolean progress_failed = false;
1445 for (int i = 0, n = this.writers.size(); i < n; i++) {
1446 Future<Void> future = completionService.take();
1447 future.get();
1448 if (!progress_failed && reporter != null && !reporter.progress()) {
1449 progress_failed = true;
1450 }
1451 }
1452 return progress_failed;
1453 }
1454
1455 Path closeWriter(String encodedRegionName, WriterAndPath wap, List<IOException> thrown)
1456 throws IOException {
1457 if (LOG.isTraceEnabled()) {
1458 LOG.trace("Closing " + wap.p);
1459 }
1460
1461 try {
1462 wap.w.close();
1463 } catch (IOException ioe) {
1464 LOG.error("Couldn't close log at " + wap.p, ioe);
1465 thrown.add(ioe);
1466 return null;
1467 }
1468 if (LOG.isDebugEnabled()) {
1469 LOG.debug("Closed wap " + wap.p + " (wrote " + wap.editsWritten
1470 + " edits, skipped " + wap.editsSkipped + " edits in "
1471 + (wap.nanosSpent / 1000 / 1000) + "ms");
1472 }
1473 if (wap.editsWritten == 0) {
1474
1475 if (walFS.exists(wap.p) && !walFS.delete(wap.p, false)) {
1476 LOG.warn("Failed deleting empty " + wap.p);
1477 throw new IOException("Failed deleting empty " + wap.p);
1478 }
1479 return null;
1480 }
1481
1482 Path dst = getCompletedRecoveredEditsFilePath(wap.p,
1483 regionMaximumEditLogSeqNum.get(encodedRegionName));
1484 try {
1485 if (!dst.equals(wap.p) && walFS.exists(dst)) {
1486 deleteOneWithFewerEntries(wap, dst);
1487 }
1488
1489
1490
1491 if (walFS.exists(wap.p)) {
1492 if (!walFS.rename(wap.p, dst)) {
1493 throw new IOException("Failed renaming " + wap.p + " to " + dst);
1494 }
1495 LOG.info("Rename " + wap.p + " to " + dst);
1496 }
1497 } catch (IOException ioe) {
1498 LOG.error("Couldn't rename " + wap.p + " to " + dst, ioe);
1499 thrown.add(ioe);
1500 return null;
1501 }
1502 return dst;
1503 }
1504
1505
1506 private List<IOException> closeLogWriters(List<IOException> thrown) throws IOException {
1507 if (writersClosed) {
1508 return thrown;
1509 }
1510
1511 if (thrown == null) {
1512 thrown = Lists.newArrayList();
1513 }
1514 try {
1515 for (WriterThread t : writerThreads) {
1516 while (t.isAlive()) {
1517 t.shouldStop = true;
1518 t.interrupt();
1519 try {
1520 t.join(10);
1521 } catch (InterruptedException e) {
1522 IOException iie = new InterruptedIOException();
1523 iie.initCause(e);
1524 throw iie;
1525 }
1526 }
1527 }
1528 } finally {
1529 WriterAndPath wap = null;
1530 for (SinkWriter tmpWAP : writers.values()) {
1531 try {
1532 wap = (WriterAndPath) tmpWAP;
1533 wap.w.close();
1534 } catch (IOException ioe) {
1535 LOG.error("Couldn't close log at " + wap.p, ioe);
1536 thrown.add(ioe);
1537 continue;
1538 }
1539 LOG.info(
1540 "Closed log " + wap.p + " (wrote " + wap.editsWritten + " edits in " + (wap.nanosSpent
1541 / 1000 / 1000) + "ms)");
1542 }
1543 writersClosed = true;
1544 }
1545
1546 return thrown;
1547 }
1548
1549
1550
1551
1552
1553
1554 WriterAndPath getWriterAndPath(Entry entry, boolean reusable) throws IOException {
1555 byte region[] = entry.getKey().getEncodedRegionName();
1556 String regionName = Bytes.toString(region);
1557 WriterAndPath ret = (WriterAndPath) writers.get(regionName);
1558 if (ret != null) {
1559 return ret;
1560 }
1561
1562
1563 if (blacklistedRegions.contains(region)) {
1564 return null;
1565 }
1566 ret = createWAP(region, entry);
1567 if (ret == null) {
1568 blacklistedRegions.add(region);
1569 return null;
1570 }
1571
1572 if(reusable) {
1573 writers.put(regionName, ret);
1574 }
1575 return ret;
1576 }
1577
1578
1579
1580
1581 WriterAndPath createWAP(byte[] region, Entry entry) throws IOException {
1582 String tmpDirName = conf.get(HConstants.TEMPORARY_FS_DIRECTORY_KEY,
1583 HConstants.DEFAULT_TEMPORARY_HDFS_DIRECTORY);
1584 Path regionedits = getRegionSplitEditsPath(entry,
1585 fileBeingSplit.getPath().getName(), tmpDirName, conf);
1586 if (regionedits == null) {
1587 return null;
1588 }
1589 if (walFS.exists(regionedits)) {
1590 LOG.warn("Found old edits file. It could be the "
1591 + "result of a previous failed split attempt. Deleting " + regionedits + ", length="
1592 + walFS.getFileStatus(regionedits).getLen());
1593 if (!walFS.delete(regionedits, false)) {
1594 LOG.warn("Failed delete of old " + regionedits);
1595 }
1596 }
1597 Writer w = createWriter(regionedits);
1598 LOG.debug("Creating writer path=" + regionedits);
1599 return new WriterAndPath(regionedits, w, entry.getKey().getLogSeqNum());
1600 }
1601
1602 void filterCellByStore(Entry logEntry) {
1603 Map<byte[], Long> maxSeqIdInStores =
1604 regionMaxSeqIdInStores.get(Bytes.toString(logEntry.getKey().getEncodedRegionName()));
1605 if (maxSeqIdInStores == null || maxSeqIdInStores.isEmpty()) {
1606 return;
1607 }
1608
1609
1610 ArrayList<Cell> keptCells = new ArrayList<Cell>(logEntry.getEdit().getCells().size());
1611 for (Cell cell : logEntry.getEdit().getCells()) {
1612 if (CellUtil.matchingFamily(cell, WALEdit.METAFAMILY)) {
1613 keptCells.add(cell);
1614 } else {
1615 byte[] family = CellUtil.cloneFamily(cell);
1616 Long maxSeqId = maxSeqIdInStores.get(family);
1617
1618
1619 if (maxSeqId == null || maxSeqId.longValue() < logEntry.getKey().getLogSeqNum()) {
1620 keptCells.add(cell);
1621 }
1622 }
1623 }
1624
1625
1626
1627
1628 logEntry.getEdit().setCells(keptCells);
1629 }
1630
1631 @Override
1632 public void append(RegionEntryBuffer buffer) throws IOException {
1633 appendBuffer(buffer, true);
1634 }
1635
1636
1637 WriterAndPath appendBuffer(RegionEntryBuffer buffer, boolean reusable) throws IOException{
1638 List<Entry> entries = buffer.entryBuffer;
1639 if (entries.isEmpty()) {
1640 LOG.warn("got an empty buffer, skipping");
1641 return null;
1642 }
1643 WriterAndPath wap = null;
1644
1645 long startTime = System.nanoTime();
1646 try {
1647 int editsCount = 0;
1648
1649 for (Entry logEntry : entries) {
1650 if (wap == null) {
1651 wap = getWriterAndPath(logEntry, reusable);
1652 if (wap == null) {
1653 if (LOG.isDebugEnabled()) {
1654 LOG.debug("getWriterAndPath decided we don't need to write edits for " + logEntry);
1655 }
1656 return null;
1657 }
1658 }
1659 filterCellByStore(logEntry);
1660 if (!logEntry.getEdit().isEmpty()) {
1661 wap.w.append(logEntry);
1662 this.updateRegionMaximumEditLogSeqNum(logEntry);
1663 editsCount++;
1664 } else {
1665 wap.incrementSkippedEdits(1);
1666 }
1667 }
1668
1669 wap.incrementEdits(editsCount);
1670 wap.incrementNanoTime(System.nanoTime() - startTime);
1671 } catch (IOException e) {
1672 e = RemoteExceptionHandler.checkIOException(e);
1673 LOG.fatal(" Got while writing log entry to log", e);
1674 throw e;
1675 }
1676 return wap;
1677 }
1678
1679 @Override
1680 public boolean keepRegionEvent(Entry entry) {
1681 ArrayList<Cell> cells = entry.getEdit().getCells();
1682 for (int i = 0; i < cells.size(); i++) {
1683 if (WALEdit.isCompactionMarker(cells.get(i))) {
1684 return true;
1685 }
1686 }
1687 return false;
1688 }
1689
1690
1691
1692
1693 @Override
1694 public Map<byte[], Long> getOutputCounts() {
1695 TreeMap<byte[], Long> ret = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
1696 synchronized (writers) {
1697 for (Map.Entry<String, SinkWriter> entry : writers.entrySet()) {
1698 ret.put(Bytes.toBytes(entry.getKey()), entry.getValue().editsWritten);
1699 }
1700 }
1701 return ret;
1702 }
1703
1704 @Override
1705 public int getNumberOfRecoveredRegions() {
1706 return writers.size();
1707 }
1708 }
1709
1710
1711
1712
1713 class BoundedLogWriterCreationOutputSink extends LogRecoveredEditsOutputSink{
1714
1715 ConcurrentHashMap<String, Long> regionRecoverStatMap = new ConcurrentHashMap<>();
1716
1717
1718 public BoundedLogWriterCreationOutputSink(PipelineController controller,
1719 EntryBuffers entryBuffers, int numWriters){
1720 super(controller, entryBuffers, numWriters);
1721 }
1722
1723 @Override
1724 public List<Path> finishWritingAndClose() throws IOException {
1725 boolean isSuccessful;
1726 List<Path> result;
1727 try {
1728 isSuccessful = finishWriting(false);
1729 } finally {
1730 result = close();
1731 }
1732 if (isSuccessful) {
1733 splits = result;
1734 }
1735 return splits;
1736 }
1737
1738 @Override
1739 boolean executeCloseTask(CompletionService<Void> closeCompletionService,
1740 final List<IOException> thrown, final List<Path> paths)
1741 throws InterruptedException, ExecutionException {
1742 for (final Map.Entry<byte[], RegionEntryBuffer> buffer : entryBuffers.buffers.entrySet()) {
1743 LOG.info("Submitting write then close of " +
1744 Bytes.toString(buffer.getValue().encodedRegionName));
1745 closeCompletionService.submit(new Callable<Void>() {
1746 public Void call() throws Exception {
1747 Path dst = writeThenClose(buffer.getValue());
1748 paths.add(dst);
1749 return null;
1750 }
1751 });
1752 }
1753
1754 boolean progress_failed = false;
1755 for (int i = 0, n = entryBuffers.buffers.size(); i < n; i++) {
1756 Future<Void> future = closeCompletionService.take();
1757 future.get();
1758 if (!progress_failed && reporter != null && !reporter.progress()) {
1759 progress_failed = true;
1760 }
1761 }
1762 return progress_failed;
1763 }
1764
1765 @Override
1766 public Map<byte[], Long> getOutputCounts() {
1767 Map<byte[], Long> regionRecoverStatMapResult = new HashMap<>();
1768 for(Map.Entry<String, Long> entry: regionRecoverStatMap.entrySet()){
1769 regionRecoverStatMapResult.put(Bytes.toBytes(entry.getKey()), entry.getValue());
1770 }
1771 return regionRecoverStatMapResult;
1772 }
1773
1774 @Override
1775 public int getNumberOfRecoveredRegions() {
1776 return regionRecoverStatMap.size();
1777 }
1778
1779 @Override
1780 public void append(RegionEntryBuffer buffer) throws IOException {
1781 writeThenClose(buffer);
1782 }
1783
1784 private Path writeThenClose(RegionEntryBuffer buffer) throws IOException {
1785 WriterAndPath wap = appendBuffer(buffer, false);
1786 Path dst = null;
1787 if(wap != null){
1788 String encodedRegionName = Bytes.toString(buffer.encodedRegionName);
1789 Long value = regionRecoverStatMap.putIfAbsent(encodedRegionName, wap.editsWritten);
1790 if(value != null){
1791 Long newValue = regionRecoverStatMap.get(encodedRegionName) + wap.editsWritten;
1792 regionRecoverStatMap.put(encodedRegionName, newValue);
1793 }
1794 }
1795
1796 List<IOException> thrown = new ArrayList<>();
1797 if(wap != null) {
1798 dst = closeWriter(Bytes.toString(buffer.encodedRegionName), wap, thrown);
1799 }
1800
1801 if(!thrown.isEmpty()){
1802 throw MultipleIOException.createIOException(thrown);
1803 }
1804 return dst;
1805 }
1806 }
1807
1808
1809
1810
1811
1812 public abstract static class SinkWriter {
1813
1814 long editsWritten = 0;
1815
1816 long editsSkipped = 0;
1817
1818 long nanosSpent = 0;
1819
1820 void incrementEdits(int edits) {
1821 editsWritten += edits;
1822 }
1823
1824 void incrementSkippedEdits(int skipped) {
1825 editsSkipped += skipped;
1826 }
1827
1828 void incrementNanoTime(long nanos) {
1829 nanosSpent += nanos;
1830 }
1831 }
1832
1833
1834
1835
1836
1837 private final static class WriterAndPath extends SinkWriter {
1838 final Path p;
1839 final Writer w;
1840 final long minLogSeqNum;
1841
1842 WriterAndPath(final Path p, final Writer w, final long minLogSeqNum) {
1843 this.p = p;
1844 this.w = w;
1845 this.minLogSeqNum = minLogSeqNum;
1846 }
1847 }
1848
1849
1850
1851
1852 class LogReplayOutputSink extends OutputSink {
1853 private static final double BUFFER_THRESHOLD = 0.35;
1854 private static final String KEY_DELIMITER = "#";
1855
1856 private long waitRegionOnlineTimeOut;
1857 private final Set<String> recoveredRegions = Collections.synchronizedSet(new HashSet<String>());
1858 private final Map<String, RegionServerWriter> writers =
1859 new ConcurrentHashMap<String, RegionServerWriter>();
1860
1861 private final Map<String, HRegionLocation> onlineRegions =
1862 new ConcurrentHashMap<String, HRegionLocation>();
1863
1864 private Map<TableName, HConnection> tableNameToHConnectionMap = Collections
1865 .synchronizedMap(new TreeMap<TableName, HConnection>());
1866
1867
1868
1869
1870 private Map<String, List<Pair<HRegionLocation, Entry>>> serverToBufferQueueMap =
1871 new ConcurrentHashMap<String, List<Pair<HRegionLocation, Entry>>>();
1872 private List<Throwable> thrown = new ArrayList<Throwable>();
1873
1874
1875
1876
1877
1878 private LogRecoveredEditsOutputSink logRecoveredEditsOutputSink;
1879 private boolean hasEditsInDisablingOrDisabledTables = false;
1880
1881 public LogReplayOutputSink(PipelineController controller, EntryBuffers entryBuffers,
1882 int numWriters) {
1883 super(controller, entryBuffers, numWriters);
1884 this.waitRegionOnlineTimeOut = conf.getInt(HConstants.HBASE_SPLITLOG_MANAGER_TIMEOUT,
1885 ZKSplitLogManagerCoordination.DEFAULT_TIMEOUT);
1886 this.logRecoveredEditsOutputSink = new LogRecoveredEditsOutputSink(controller,
1887 entryBuffers, numWriters);
1888 this.logRecoveredEditsOutputSink.setReporter(reporter);
1889 }
1890
1891 @Override
1892 public void append(RegionEntryBuffer buffer) throws IOException {
1893 List<Entry> entries = buffer.entryBuffer;
1894 if (entries.isEmpty()) {
1895 LOG.warn("got an empty buffer, skipping");
1896 return;
1897 }
1898
1899
1900 if (disablingOrDisabledTables.contains(buffer.tableName)) {
1901
1902 logRecoveredEditsOutputSink.append(buffer);
1903 hasEditsInDisablingOrDisabledTables = true;
1904
1905 addToRecoveredRegions(Bytes.toString(buffer.encodedRegionName));
1906 return;
1907 }
1908
1909
1910 groupEditsByServer(entries);
1911
1912
1913 String maxLocKey = null;
1914 int maxSize = 0;
1915 List<Pair<HRegionLocation, Entry>> maxQueue = null;
1916 synchronized (this.serverToBufferQueueMap) {
1917 for (Map.Entry<String, List<Pair<HRegionLocation, Entry>>> entry:
1918 serverToBufferQueueMap.entrySet()) {
1919 List<Pair<HRegionLocation, Entry>> curQueue = entry.getValue();
1920 if (curQueue.size() > maxSize) {
1921 maxSize = curQueue.size();
1922 maxQueue = curQueue;
1923 maxLocKey = entry.getKey();
1924 }
1925 }
1926 if (maxSize < minBatchSize
1927 && entryBuffers.totalBuffered < BUFFER_THRESHOLD * entryBuffers.maxHeapUsage) {
1928
1929 return;
1930 } else if (maxSize > 0) {
1931 this.serverToBufferQueueMap.remove(maxLocKey);
1932 }
1933 }
1934
1935 if (maxSize > 0) {
1936 processWorkItems(maxLocKey, maxQueue);
1937 }
1938 }
1939
1940 private void addToRecoveredRegions(String encodedRegionName) {
1941 if (!recoveredRegions.contains(encodedRegionName)) {
1942 recoveredRegions.add(encodedRegionName);
1943 }
1944 }
1945
1946
1947
1948
1949
1950 private void groupEditsByServer(List<Entry> entries) throws IOException {
1951 Set<TableName> nonExistentTables = null;
1952 Long cachedLastFlushedSequenceId = -1l;
1953 for (Entry entry : entries) {
1954 WALEdit edit = entry.getEdit();
1955 TableName table = entry.getKey().getTablename();
1956
1957 entry.getKey().setScopes(null);
1958 String encodeRegionNameStr = Bytes.toString(entry.getKey().getEncodedRegionName());
1959
1960 if (nonExistentTables != null && nonExistentTables.contains(table)) {
1961 this.skippedEdits.incrementAndGet();
1962 continue;
1963 }
1964
1965 Map<byte[], Long> maxStoreSequenceIds = null;
1966 boolean needSkip = false;
1967 HRegionLocation loc = null;
1968 String locKey = null;
1969 List<Cell> cells = edit.getCells();
1970 List<Cell> skippedCells = new ArrayList<Cell>();
1971 HConnection hconn = this.getConnectionByTableName(table);
1972
1973 for (Cell cell : cells) {
1974 byte[] row = CellUtil.cloneRow(cell);
1975 byte[] family = CellUtil.cloneFamily(cell);
1976 boolean isCompactionEntry = false;
1977 if (CellUtil.matchingFamily(cell, WALEdit.METAFAMILY)) {
1978 CompactionDescriptor compaction = WALEdit.getCompaction(cell);
1979 if (compaction != null && compaction.hasRegionName()) {
1980 try {
1981 byte[][] regionName = HRegionInfo.parseRegionName(compaction.getRegionName()
1982 .toByteArray());
1983 row = regionName[1];
1984 family = compaction.getFamilyName().toByteArray();
1985 isCompactionEntry = true;
1986 } catch (Exception ex) {
1987 LOG.warn("Unexpected exception received, ignoring " + ex);
1988 skippedCells.add(cell);
1989 continue;
1990 }
1991 } else {
1992 skippedCells.add(cell);
1993 continue;
1994 }
1995 }
1996
1997 try {
1998 loc =
1999 locateRegionAndRefreshLastFlushedSequenceId(hconn, table, row,
2000 encodeRegionNameStr);
2001
2002 if (isCompactionEntry && !encodeRegionNameStr.equalsIgnoreCase(
2003 loc.getRegionInfo().getEncodedName())) {
2004 LOG.info("Not replaying a compaction marker for an older region: "
2005 + encodeRegionNameStr);
2006 needSkip = true;
2007 }
2008 } catch (TableNotFoundException ex) {
2009
2010 LOG.info("Table " + table + " doesn't exist. Skip log replay for region "
2011 + encodeRegionNameStr);
2012 lastFlushedSequenceIds.put(encodeRegionNameStr, Long.MAX_VALUE);
2013 if (nonExistentTables == null) {
2014 nonExistentTables = new TreeSet<TableName>();
2015 }
2016 nonExistentTables.add(table);
2017 this.skippedEdits.incrementAndGet();
2018 needSkip = true;
2019 break;
2020 }
2021
2022 cachedLastFlushedSequenceId =
2023 lastFlushedSequenceIds.get(loc.getRegionInfo().getEncodedName());
2024 if (cachedLastFlushedSequenceId != null
2025 && cachedLastFlushedSequenceId >= entry.getKey().getLogSeqNum()) {
2026
2027 this.skippedEdits.incrementAndGet();
2028 needSkip = true;
2029 break;
2030 } else {
2031 if (maxStoreSequenceIds == null) {
2032 maxStoreSequenceIds =
2033 regionMaxSeqIdInStores.get(loc.getRegionInfo().getEncodedName());
2034 }
2035 if (maxStoreSequenceIds != null) {
2036 Long maxStoreSeqId = maxStoreSequenceIds.get(family);
2037 if (maxStoreSeqId == null || maxStoreSeqId >= entry.getKey().getLogSeqNum()) {
2038
2039 skippedCells.add(cell);
2040 continue;
2041 }
2042 }
2043 }
2044 }
2045
2046
2047 if (loc == null || needSkip) continue;
2048
2049 if (!skippedCells.isEmpty()) {
2050 cells.removeAll(skippedCells);
2051 }
2052
2053 synchronized (serverToBufferQueueMap) {
2054 locKey = loc.getHostnamePort() + KEY_DELIMITER + table;
2055 List<Pair<HRegionLocation, Entry>> queue = serverToBufferQueueMap.get(locKey);
2056 if (queue == null) {
2057 queue =
2058 Collections.synchronizedList(new ArrayList<Pair<HRegionLocation, Entry>>());
2059 serverToBufferQueueMap.put(locKey, queue);
2060 }
2061 queue.add(new Pair<HRegionLocation, Entry>(loc, entry));
2062 }
2063
2064 addToRecoveredRegions(loc.getRegionInfo().getEncodedName());
2065 }
2066 }
2067
2068
2069
2070
2071
2072
2073 private HRegionLocation locateRegionAndRefreshLastFlushedSequenceId(HConnection hconn,
2074 TableName table, byte[] row, String originalEncodedRegionName) throws IOException {
2075
2076 HRegionLocation loc = onlineRegions.get(originalEncodedRegionName);
2077 if(loc != null) return loc;
2078
2079 loc = hconn.getRegionLocation(table, row, true);
2080 if (loc == null) {
2081 throw new IOException("Can't locate location for row:" + Bytes.toString(row)
2082 + " of table:" + table);
2083 }
2084
2085 if (!originalEncodedRegionName.equalsIgnoreCase(loc.getRegionInfo().getEncodedName())) {
2086
2087 lastFlushedSequenceIds.put(originalEncodedRegionName, Long.MAX_VALUE);
2088 HRegionLocation tmpLoc = onlineRegions.get(loc.getRegionInfo().getEncodedName());
2089 if (tmpLoc != null) return tmpLoc;
2090 }
2091
2092 Long lastFlushedSequenceId = -1l;
2093 AtomicBoolean isRecovering = new AtomicBoolean(true);
2094 loc = waitUntilRegionOnline(loc, row, this.waitRegionOnlineTimeOut, isRecovering);
2095 if (!isRecovering.get()) {
2096
2097
2098 lastFlushedSequenceIds.put(loc.getRegionInfo().getEncodedName(), Long.MAX_VALUE);
2099 LOG.info("logReplay skip region: " + loc.getRegionInfo().getEncodedName()
2100 + " because it's not in recovering.");
2101 } else {
2102 Long cachedLastFlushedSequenceId =
2103 lastFlushedSequenceIds.get(loc.getRegionInfo().getEncodedName());
2104
2105
2106
2107 RegionStoreSequenceIds ids =
2108 csm.getSplitLogWorkerCoordination().getRegionFlushedSequenceId(failedServerName,
2109 loc.getRegionInfo().getEncodedName());
2110 if (ids != null) {
2111 lastFlushedSequenceId = ids.getLastFlushedSequenceId();
2112 Map<byte[], Long> storeIds = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
2113 List<StoreSequenceId> maxSeqIdInStores = ids.getStoreSequenceIdList();
2114 for (StoreSequenceId id : maxSeqIdInStores) {
2115 storeIds.put(id.getFamilyName().toByteArray(), id.getSequenceId());
2116 }
2117 regionMaxSeqIdInStores.put(loc.getRegionInfo().getEncodedName(), storeIds);
2118 }
2119
2120 if (cachedLastFlushedSequenceId == null
2121 || lastFlushedSequenceId > cachedLastFlushedSequenceId) {
2122 lastFlushedSequenceIds.put(loc.getRegionInfo().getEncodedName(), lastFlushedSequenceId);
2123 }
2124 }
2125
2126 onlineRegions.put(loc.getRegionInfo().getEncodedName(), loc);
2127 return loc;
2128 }
2129
2130 private void processWorkItems(String key, List<Pair<HRegionLocation, Entry>> actions)
2131 throws IOException {
2132 RegionServerWriter rsw = null;
2133
2134 long startTime = System.nanoTime();
2135 try {
2136 rsw = getRegionServerWriter(key);
2137 rsw.sink.replayEntries(actions);
2138
2139
2140 rsw.incrementEdits(actions.size());
2141 rsw.incrementNanoTime(System.nanoTime() - startTime);
2142 } catch (IOException e) {
2143 e = RemoteExceptionHandler.checkIOException(e);
2144 LOG.fatal(" Got while writing log entry to log", e);
2145 throw e;
2146 }
2147 }
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158 private HRegionLocation waitUntilRegionOnline(HRegionLocation loc, byte[] row,
2159 final long timeout, AtomicBoolean isRecovering)
2160 throws IOException {
2161 final long endTime = EnvironmentEdgeManager.currentTime() + timeout;
2162 final long pause = conf.getLong(HConstants.HBASE_CLIENT_PAUSE,
2163 HConstants.DEFAULT_HBASE_CLIENT_PAUSE);
2164 boolean reloadLocation = false;
2165 TableName tableName = loc.getRegionInfo().getTable();
2166 int tries = 0;
2167 Throwable cause = null;
2168 while (endTime > EnvironmentEdgeManager.currentTime()) {
2169 try {
2170
2171 HConnection hconn = getConnectionByTableName(tableName);
2172 if(reloadLocation) {
2173 loc = hconn.getRegionLocation(tableName, row, true);
2174 }
2175 BlockingInterface remoteSvr = hconn.getAdmin(loc.getServerName());
2176 HRegionInfo region = loc.getRegionInfo();
2177 try {
2178 GetRegionInfoRequest request =
2179 RequestConverter.buildGetRegionInfoRequest(region.getRegionName());
2180 GetRegionInfoResponse response = remoteSvr.getRegionInfo(null, request);
2181 if (HRegionInfo.convert(response.getRegionInfo()) != null) {
2182 isRecovering.set((response.hasIsRecovering()) ? response.getIsRecovering() : true);
2183 return loc;
2184 }
2185 } catch (ServiceException se) {
2186 throw ProtobufUtil.getRemoteException(se);
2187 }
2188 } catch (IOException e) {
2189 cause = e.getCause();
2190 if(!(cause instanceof RegionOpeningException)) {
2191 reloadLocation = true;
2192 }
2193 }
2194 long expectedSleep = ConnectionUtils.getPauseTime(pause, tries);
2195 try {
2196 Thread.sleep(expectedSleep);
2197 } catch (InterruptedException e) {
2198 throw new IOException("Interrupted when waiting region " +
2199 loc.getRegionInfo().getEncodedName() + " online.", e);
2200 }
2201 tries++;
2202 }
2203
2204 throw new IOException("Timeout when waiting region " + loc.getRegionInfo().getEncodedName() +
2205 " online for " + timeout + " milliseconds.", cause);
2206 }
2207
2208 @Override
2209 public boolean flush() throws IOException {
2210 String curLoc = null;
2211 int curSize = 0;
2212 List<Pair<HRegionLocation, Entry>> curQueue = null;
2213 synchronized (this.serverToBufferQueueMap) {
2214 for (Map.Entry<String, List<Pair<HRegionLocation, Entry>>> entry :
2215 serverToBufferQueueMap.entrySet()) {
2216 String locationKey = entry.getKey();
2217 curQueue = entry.getValue();
2218 if (!curQueue.isEmpty()) {
2219 curSize = curQueue.size();
2220 curLoc = locationKey;
2221 break;
2222 }
2223 }
2224 if (curSize > 0) {
2225 this.serverToBufferQueueMap.remove(curLoc);
2226 }
2227 }
2228
2229 if (curSize > 0) {
2230 this.processWorkItems(curLoc, curQueue);
2231
2232 synchronized(controller.dataAvailable) {
2233 controller.dataAvailable.notifyAll();
2234 }
2235 return true;
2236 }
2237 return false;
2238 }
2239
2240 @Override
2241 public boolean keepRegionEvent(Entry entry) {
2242 return true;
2243 }
2244
2245 void addWriterError(Throwable t) {
2246 thrown.add(t);
2247 }
2248
2249 @Override
2250 public List<Path> finishWritingAndClose() throws IOException {
2251 try {
2252 if (!finishWriting(false)) {
2253 return null;
2254 }
2255 if (hasEditsInDisablingOrDisabledTables) {
2256 splits = logRecoveredEditsOutputSink.finishWritingAndClose();
2257 } else {
2258 splits = new ArrayList<Path>();
2259 }
2260
2261 return splits;
2262 } finally {
2263 List<IOException> thrown = closeRegionServerWriters();
2264 if (thrown != null && !thrown.isEmpty()) {
2265 throw MultipleIOException.createIOException(thrown);
2266 }
2267 }
2268 }
2269
2270 @Override
2271 int getNumOpenWriters() {
2272 return this.writers.size() + this.logRecoveredEditsOutputSink.getNumOpenWriters();
2273 }
2274
2275 private List<IOException> closeRegionServerWriters() throws IOException {
2276 List<IOException> result = null;
2277 if (!writersClosed) {
2278 result = Lists.newArrayList();
2279 try {
2280 for (WriterThread t : writerThreads) {
2281 while (t.isAlive()) {
2282 t.shouldStop = true;
2283 t.interrupt();
2284 try {
2285 t.join(10);
2286 } catch (InterruptedException e) {
2287 IOException iie = new InterruptedIOException();
2288 iie.initCause(e);
2289 throw iie;
2290 }
2291 }
2292 }
2293 } finally {
2294 synchronized (writers) {
2295 for (Map.Entry<String, RegionServerWriter> entry : writers.entrySet()) {
2296 String locationKey = entry.getKey();
2297 RegionServerWriter tmpW = entry.getValue();
2298 try {
2299 tmpW.close();
2300 } catch (IOException ioe) {
2301 LOG.error("Couldn't close writer for region server:" + locationKey, ioe);
2302 result.add(ioe);
2303 }
2304 }
2305 }
2306
2307
2308 synchronized (this.tableNameToHConnectionMap) {
2309 for (Map.Entry<TableName, HConnection> entry :
2310 tableNameToHConnectionMap.entrySet()) {
2311 TableName tableName = entry.getKey();
2312 HConnection hconn = entry.getValue();
2313 try {
2314 hconn.clearRegionCache();
2315 hconn.close();
2316 } catch (IOException ioe) {
2317 result.add(ioe);
2318 }
2319 }
2320 }
2321 writersClosed = true;
2322 }
2323 }
2324 return result;
2325 }
2326
2327 @Override
2328 public Map<byte[], Long> getOutputCounts() {
2329 TreeMap<byte[], Long> ret = new TreeMap<byte[], Long>(Bytes.BYTES_COMPARATOR);
2330 synchronized (writers) {
2331 for (Map.Entry<String, RegionServerWriter> entry : writers.entrySet()) {
2332 ret.put(Bytes.toBytes(entry.getKey()), entry.getValue().editsWritten);
2333 }
2334 }
2335 return ret;
2336 }
2337
2338 @Override
2339 public int getNumberOfRecoveredRegions() {
2340 return this.recoveredRegions.size();
2341 }
2342
2343
2344
2345
2346
2347
2348 private RegionServerWriter getRegionServerWriter(String loc) throws IOException {
2349 RegionServerWriter ret = writers.get(loc);
2350 if (ret != null) {
2351 return ret;
2352 }
2353
2354 TableName tableName = getTableFromLocationStr(loc);
2355 if(tableName == null){
2356 throw new IOException("Invalid location string:" + loc + " found. Replay aborted.");
2357 }
2358
2359 HConnection hconn = getConnectionByTableName(tableName);
2360 synchronized (writers) {
2361 ret = writers.get(loc);
2362 if (ret == null) {
2363 ret = new RegionServerWriter(conf, tableName, hconn);
2364 writers.put(loc, ret);
2365 }
2366 }
2367 return ret;
2368 }
2369
2370 private HConnection getConnectionByTableName(final TableName tableName) throws IOException {
2371 HConnection hconn = this.tableNameToHConnectionMap.get(tableName);
2372 if (hconn == null) {
2373 synchronized (this.tableNameToHConnectionMap) {
2374 hconn = this.tableNameToHConnectionMap.get(tableName);
2375 if (hconn == null) {
2376 hconn = HConnectionManager.getConnection(conf);
2377 this.tableNameToHConnectionMap.put(tableName, hconn);
2378 }
2379 }
2380 }
2381 return hconn;
2382 }
2383 private TableName getTableFromLocationStr(String loc) {
2384
2385
2386
2387 String[] splits = loc.split(KEY_DELIMITER);
2388 if (splits.length != 2) {
2389 return null;
2390 }
2391 return TableName.valueOf(splits[1]);
2392 }
2393 }
2394
2395
2396
2397
2398
2399 private final static class RegionServerWriter extends SinkWriter {
2400 final WALEditsReplaySink sink;
2401
2402 RegionServerWriter(final Configuration conf, final TableName tableName, final HConnection conn)
2403 throws IOException {
2404 this.sink = new WALEditsReplaySink(conf, tableName, conn);
2405 }
2406
2407 void close() throws IOException {
2408 }
2409 }
2410
2411 static class CorruptedLogFileException extends Exception {
2412 private static final long serialVersionUID = 1L;
2413
2414 CorruptedLogFileException(String s) {
2415 super(s);
2416 }
2417 }
2418
2419
2420 public static class MutationReplay implements Comparable<MutationReplay> {
2421 public MutationReplay(MutationType type, Mutation mutation, long nonceGroup, long nonce) {
2422 this.type = type;
2423 this.mutation = mutation;
2424 if(this.mutation.getDurability() != Durability.SKIP_WAL) {
2425
2426 this.mutation.setDurability(Durability.ASYNC_WAL);
2427 }
2428 this.nonceGroup = nonceGroup;
2429 this.nonce = nonce;
2430 }
2431
2432 public final MutationType type;
2433 public final Mutation mutation;
2434 public final long nonceGroup;
2435 public final long nonce;
2436
2437 @Override
2438 public int compareTo(final MutationReplay d) {
2439 return this.mutation.compareTo(d.mutation);
2440 }
2441
2442 @Override
2443 public boolean equals(Object obj) {
2444 if(!(obj instanceof MutationReplay)) {
2445 return false;
2446 } else {
2447 return this.compareTo((MutationReplay)obj) == 0;
2448 }
2449 }
2450
2451 @Override
2452 public int hashCode() {
2453 return this.mutation.hashCode();
2454 }
2455 }
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468 public static List<MutationReplay> getMutationsFromWALEntry(WALEntry entry, CellScanner cells,
2469 Pair<WALKey, WALEdit> logEntry, Durability durability)
2470 throws IOException {
2471 if (entry == null) {
2472
2473 return new ArrayList<MutationReplay>();
2474 }
2475
2476 long replaySeqId = (entry.getKey().hasOrigSequenceNumber()) ?
2477 entry.getKey().getOrigSequenceNumber() : entry.getKey().getLogSequenceNumber();
2478 int count = entry.getAssociatedCellCount();
2479 List<MutationReplay> mutations = new ArrayList<MutationReplay>();
2480 Cell previousCell = null;
2481 Mutation m = null;
2482 WALKey key = null;
2483 WALEdit val = null;
2484 if (logEntry != null) val = new WALEdit();
2485
2486 for (int i = 0; i < count; i++) {
2487
2488 if (!cells.advance()) {
2489 throw new ArrayIndexOutOfBoundsException("Expected=" + count + ", index=" + i);
2490 }
2491 Cell cell = cells.current();
2492 if (val != null) val.add(cell);
2493
2494 boolean isNewRowOrType =
2495 previousCell == null || previousCell.getTypeByte() != cell.getTypeByte()
2496 || !CellUtil.matchingRow(previousCell, cell);
2497 if (isNewRowOrType) {
2498
2499 if (CellUtil.isDelete(cell)) {
2500 m = new Delete(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
2501
2502 mutations.add(new MutationReplay(
2503 MutationType.DELETE, m, HConstants.NO_NONCE, HConstants.NO_NONCE));
2504 } else {
2505 m = new Put(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
2506
2507 long nonceGroup = entry.getKey().hasNonceGroup()
2508 ? entry.getKey().getNonceGroup() : HConstants.NO_NONCE;
2509 long nonce = entry.getKey().hasNonce() ? entry.getKey().getNonce() : HConstants.NO_NONCE;
2510 mutations.add(new MutationReplay(MutationType.PUT, m, nonceGroup, nonce));
2511 }
2512 }
2513 if (CellUtil.isDelete(cell)) {
2514 ((Delete) m).addDeleteMarker(cell);
2515 } else {
2516 ((Put) m).add(cell);
2517 }
2518 m.setDurability(durability);
2519 previousCell = cell;
2520 }
2521
2522
2523 if (logEntry != null) {
2524 org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey walKeyProto = entry.getKey();
2525 List<UUID> clusterIds = new ArrayList<UUID>(walKeyProto.getClusterIdsCount());
2526 for (HBaseProtos.UUID uuid : entry.getKey().getClusterIdsList()) {
2527 clusterIds.add(new UUID(uuid.getMostSigBits(), uuid.getLeastSigBits()));
2528 }
2529
2530 key = new HLogKey(walKeyProto.getEncodedRegionName().toByteArray(), TableName.valueOf(
2531 walKeyProto.getTableName().toByteArray()), replaySeqId, walKeyProto.getWriteTime(),
2532 clusterIds, walKeyProto.getNonceGroup(), walKeyProto.getNonce(), null);
2533 logEntry.setFirst(key);
2534 logEntry.setSecond(val);
2535 }
2536
2537 return mutations;
2538 }
2539 }